diff --git a/src/.DS_Store b/src/.DS_Store index 3d880586..3771dc07 100644 Binary files a/src/.DS_Store and b/src/.DS_Store differ diff --git a/src/main/.DS_Store b/src/main/.DS_Store index 51da7dfb..175747f9 100644 Binary files a/src/main/.DS_Store and b/src/main/.DS_Store differ diff --git a/src/main/java/.DS_Store b/src/main/java/.DS_Store index 93d17d5f..10f085d7 100644 Binary files a/src/main/java/.DS_Store and b/src/main/java/.DS_Store differ diff --git a/src/main/java/in/.DS_Store b/src/main/java/in/.DS_Store index 1042b909..883062c3 100644 Binary files a/src/main/java/in/.DS_Store and b/src/main/java/in/.DS_Store differ diff --git a/src/main/java/in/gov/.DS_Store b/src/main/java/in/gov/.DS_Store index 4d1f4223..9e6a46e2 100644 Binary files a/src/main/java/in/gov/.DS_Store and b/src/main/java/in/gov/.DS_Store differ diff --git a/src/main/java/in/gov/chennaicorporation/.DS_Store b/src/main/java/in/gov/chennaicorporation/.DS_Store index f095c3e0..ad057a28 100644 Binary files a/src/main/java/in/gov/chennaicorporation/.DS_Store and b/src/main/java/in/gov/chennaicorporation/.DS_Store differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/.DS_Store deleted file mode 100644 index fc62e2a7..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/GccOfficeApplication.java b/src/main/java/in/gov/chennaicorporation/gccoffice/GccOfficeApplication.java deleted file mode 100644 index 6f1730e7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/GccOfficeApplication.java +++ /dev/null @@ -1,26 +0,0 @@ -package in.gov.chennaicorporation.gccoffice; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -//import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.context.annotation.ComponentScan; - -@EntityScan(basePackages = { - "in.gov.chennaicorporation.gccoffice", - "in.gov.chennaicorporation.gccoffice.taxcollection.entity" -}) -@ComponentScan(basePackages = { - "in.gov.chennaicorporation.gccoffice", - "in.gov.chennaicorporation.gccoffice.taxcollection", - "in.gov.chennaicorporation.gccoffice.garbagecollection" -}) -@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) -//@EnableDiscoveryClient -public class GccOfficeApplication { - public static void main(String[] args) { - //System.setProperty("spring.config.name", "gcc-portal"); - SpringApplication.run(GccOfficeApplication.class, args); - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Controller/APIController.java deleted file mode 100644 index 72f5f6f1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Controller/APIController.java +++ /dev/null @@ -1,244 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.bulkwaste.Controller; - -import java.math.BigDecimal; -import java.util.Date; -import java.util.List; -import java.util.Map; -import org.springframework.http.MediaType; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.ResponseEntity; -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.gccoffice.bulkwaste.Service.BulkWasteService; -import in.gov.chennaicorporation.gccoffice.bulkwaste.Service.BulkMasterService; - -@RequestMapping("gcc/api/bulkwaste") -@RestController("BulkWasteAPIController") -public class APIController { - - @Autowired - private BulkMasterService masterService; - private BulkWasteService bulkWasteService; - - @Autowired - public APIController(BulkMasterService masterService, - BulkWasteService bulkWasteService) { - this.masterService = masterService; - this.bulkWasteService = bulkWasteService; - } - - @GetMapping(value="/getCategoryTypes") - public List getCategoryTypes() { - return masterService.getCategoryTypes(); - } - - @GetMapping(value="/getZones") - public List getZones() { - return masterService.getZones(); - } - - @GetMapping("/getWards") - public List> getWards( - @RequestParam String zoneName) { - - return masterService.getWards(zoneName); - } - - @GetMapping("/getBulkWasteRequestDetails") - public List> getBulkWasteRequestDetails( - - @RequestParam(value = "fromDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate, - - @RequestParam(value = "toDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate, - - @RequestParam(value = "categoryType", required = false) String categoryType, - @RequestParam(value = "zoneType", required = false) String zoneType, - @RequestParam(value = "wardType", required = false) String wardType) { - - return bulkWasteService.getBulkWasteRequestDetails(fromDate, toDate, categoryType, zoneType, wardType); - } - - @GetMapping("/bulkWasteRequestView") - public Map bulkWasteRequestView( - @RequestParam Long requestId) { - - return bulkWasteService.getBulkWasteRequestView(requestId); - } - - @GetMapping("/getMinSurveyDate") - public String getMinSurveyDate() { - return bulkWasteService.getMinSurveyDate(); - } - - - - @PostMapping(value="/updateBulkWasteRequest", - consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity> updateBulkWasteRequest( - - @RequestParam Long requestId, - - @RequestParam String name_of_establishment, @RequestParam Integer category_id, - @RequestParam Integer zone_id, @RequestParam Integer ward_id, - @RequestParam(required = false) String trade_license_No, - @RequestParam String person_name, @RequestParam String email_id, - @RequestParam String mobile_no, @RequestParam String address, - @RequestParam(required = false) String gst_No, - - - @RequestParam String total_builtup_area_sqmt, @RequestParam String establishment_type, - @RequestParam(required = false) Integer dwelling_units, - @RequestParam(required = false) Integer avg_daily_footfall, - @RequestParam String totalEmployees, - - @RequestParam BigDecimal wet_waste, @RequestParam BigDecimal dry_waste, - @RequestParam BigDecimal domestic_hazardous_waste, - @RequestParam BigDecimal sanitary_waste, - @RequestParam(required = false) BigDecimal cd_waste, - - @RequestParam(required = false) MultipartFile wasteAuditFile, - - @RequestParam String wet_waste_processed, - @RequestParam(required = false) String technology_used, - @RequestParam(required = false) String other_technology, - @RequestParam(required = false) BigDecimal installed_capacity_kg, - @RequestParam(required = false) Integer installation_year, - @RequestParam(required = false) String vendor_name, - @RequestParam(required = false) String unit_functional_status, - @RequestParam(required = false) MultipartFile installedUnitPhoto, - @RequestParam(defaultValue = "false") boolean removeInstalledPhoto, - - @RequestParam(required = false) String longitude, - @RequestParam(required = false) String latitude, - - @RequestParam String dry_waste_recycler, - @RequestParam(required = false) String recycler_name, - @RequestParam(required = false) String recycler_authorization_no, - - @RequestParam BigDecimal residual_waste_quantity, - @RequestParam String collection_frequency, - @RequestParam String vehicle_type, - - @RequestParam Integer update_by - - ) { - - try { - - String result = bulkWasteService.updateBulkWasteRequest( - - requestId, - - name_of_establishment, category_id, zone_id, ward_id, trade_license_No, - person_name, email_id, mobile_no, gst_No, address, - - total_builtup_area_sqmt, establishment_type, - dwelling_units, avg_daily_footfall, totalEmployees, - - wet_waste, dry_waste, domestic_hazardous_waste, sanitary_waste, cd_waste, - - wasteAuditFile, - - wet_waste_processed, technology_used, other_technology, - installed_capacity_kg, installation_year, - vendor_name, unit_functional_status, installedUnitPhoto, - - removeInstalledPhoto, // <-- ADD THIS - - longitude, latitude, - - dry_waste_recycler, recycler_name, recycler_authorization_no, - - residual_waste_quantity, collection_frequency, vehicle_type, - - update_by - ); - - if ("mobile_exists".equals(result)) { - - return ResponseEntity.ok(Map.of( - "status", false, - "message", "duplicate", - "description", "This Mobile Number is already registered." - )); - } - - if ("success".equals(result)) { - - return ResponseEntity.ok(Map.of( - "status", true, - "message", "success", - "description", "Bulk Waste Request Updated Successfully" - )); - } - - return ResponseEntity.ok(Map.of( - "status", false, - "message", "failed", - "description", "Update Failed" - )); - - } catch (Exception e) { - - e.printStackTrace(); - - return ResponseEntity.ok(Map.of( - "status", false, - "message", "error", - "description", "Something went wrong" - )); - } - } - - - @PostMapping("/deactivatebulk") - public ResponseEntity> DeactivateBulkRequest(@RequestParam int requestId, - //@RequestParam Integer userId, - @RequestParam("update_by") Integer updateBy) { - - try { - - String result = bulkWasteService.deactivatebulkrequest(requestId,updateBy); - - if (result == null || result.equals("error")) { - - return ResponseEntity.ok(Map.of( - "status", false, - "message", "failed", - "description", " Failed to Deleted Bulk " - )); - } - - return ResponseEntity.ok(Map.of( - "status", true, - "title", "success", - "message", " Bulk Deleted successfully " - )); - - } catch (Exception e) { - - e.printStackTrace(); - - return ResponseEntity.ok(Map.of( - "status", false, - "message", "error", - "description", " Something went wrong " - )); - } - } - - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Controller/MainController.java deleted file mode 100644 index 73419bfd..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Controller/MainController.java +++ /dev/null @@ -1,38 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.bulkwaste.Controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@Controller("BulkWasteController") -@RequestMapping("/gcc/bulkwaste") -public class MainController { - - private final RestTemplate restTemplate; - private String BasePath = "modules/bulkwaste/"; - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - - @GetMapping("bulkwastelist") - public String ownerList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"requestdetails"; - } - - @GetMapping("surveyorsreports") - public String surveyorsreports(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"surveyorsreports"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Service/BulkMasterService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Service/BulkMasterService.java deleted file mode 100644 index e3d3dc49..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Service/BulkMasterService.java +++ /dev/null @@ -1,65 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.bulkwaste.Service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class BulkMasterService { - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlBulkWasteDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getCategoryTypes() { - - String sqlQuery = - "SELECT * " + - "FROM category_master " + - "WHERE is_active = 1 " + - "AND is_delete = 0"; - -// getSpaceRearTypes - - return jdbcTemplate.queryForList(sqlQuery); - } - - @Transactional(readOnly = true) - public List> getZones() { - - String sqlQuery = - "SELECT * FROM zones " + - "WHERE is_active = 1 AND is_delete = 0"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - @Transactional(readOnly = true) - public List> getWards(String zoneName) { - - String sqlQuery = - "SELECT * " + - "FROM wards " + - "WHERE is_active = 1 " + - "AND is_delete = 0 " + - "AND zone_name = ?"; - - return jdbcTemplate.queryForList(sqlQuery, zoneName); - } - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Service/BulkWasteService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Service/BulkWasteService.java deleted file mode 100644 index a3d7f3a9..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/bulkwaste/Service/BulkWasteService.java +++ /dev/null @@ -1,456 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.bulkwaste.Service; - -import java.util.Date; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class BulkWasteService { - - private JdbcTemplate jdbcTemplate; - - private final Environment environment; - private String fileBaseUrl; - - public BulkWasteService(Environment environment) { - this.environment = environment; - this.fileBaseUrl = environment.getProperty("fileBaseUrl"); - } - - @Autowired - public void setDataSource(@Qualifier("mysqlBulkWasteDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - @Transactional(readOnly = true) - public List> getBulkWasteRequestDetails(Date fromDate, Date toDate, - String categoryType, String zoneType, String wardType) { - - try { - - StringBuilder sql = new StringBuilder( - "SELECT bwr.request_id, bwr.name_of_establishment, " + - "bwr.category_id, cm.category_name, " + - "bwr.zone_id, bwr.ward_id, " + - "bwr.person_name, bwr.mobile_no, bwr.cdate " + - "FROM bulk_waste_request bwr " + - "LEFT JOIN category_master cm ON cm.category_id = bwr.category_id " - ); - - List params = new ArrayList<>(); - List conditions = new ArrayList<>(); - - // Date Filter - if (fromDate != null && toDate != null) { - conditions.add("DATE(bwr.cdate) BETWEEN ? AND ?"); - params.add(fromDate); - params.add(toDate); - } - - // Category Filter - if (categoryType != null && !categoryType.trim().isEmpty()) { - conditions.add("bwr.category_id = ?"); - params.add(Integer.parseInt(categoryType)); - } - - // Zone Filter - if (zoneType != null && !zoneType.trim().isEmpty()) { - conditions.add("bwr.zone_id = ?"); - params.add(zoneType); - } - - // Ward Filter - if (wardType != null && !wardType.trim().isEmpty()) { - conditions.add("bwr.ward_id = ?"); - params.add(wardType); - } - - // Show only active records (Optional) - conditions.add("bwr.is_delete = 0"); - conditions.add("bwr.is_active = 1"); - - if (!conditions.isEmpty()) { - sql.append(" WHERE ").append(String.join(" AND ", conditions)); - } - - sql.append(" ORDER BY bwr.cdate DESC"); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - - } catch (DataAccessException e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - @Transactional(readOnly = true) - public String getMinSurveyDate() { - - String sql = "SELECT DATE(MIN(cdate)) FROM bulk_waste_request"; - - return jdbcTemplate.queryForObject(sql, String.class); - } - - @Transactional(readOnly = true) - public Map getBulkWasteRequestView(Long requestId) { - - String sql = - "SELECT bwr.request_id, " + - "bwr.name_of_establishment, bwr.person_name, " + - "bwr.category_id, cm.category_name, bwr.email_id, bwr.mobile_no, " + - "bwr.zone_id, bwr.ward_id, bwr.trade_license_No, bwr.gst_No, " + - "bwr.address, " + - "bwr.total_builtup_area_sqmt, bwr.establishment_type, " + - "bwr.dwelling_units, bwr.avg_daily_footfall, bwr.totalEmployees, " + - "bwr.wet_waste, bwr.dry_waste, bwr.domestic_hazardous_waste, " + - "bwr.sanitary_waste, bwr.cd_waste, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bwr.waste_audit_report_file) AS waste_audit_report_file, " + - "bwr.wet_waste_processed, bwr.technology_used, bwr.other_technology, " + - "bwr.installed_capacity_kg, bwr.installation_year, " + - "bwr.vendor_name, bwr.unit_functional_status, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bwr.installed_unit_photo_file) AS installed_unit_photo_file, " + - "bwr.longitude, bwr.latitude, " + - "bwr.dry_waste_recycler, bwr.recycler_name, bwr.recycler_authorization_no, " + - "bwr.residual_waste_quantity, bwr.collection_frequency, bwr.vehicle_type, " + - "bwr.is_active, bwr.is_delete, bwr.cdate " + - "FROM bulk_waste_request bwr " + - "LEFT JOIN category_master cm ON cm.category_id = bwr.category_id " + - "WHERE bwr.request_id = ?"; - - return jdbcTemplate.queryForMap(sql, requestId); - } - - - - public String fileUpload(MultipartFile file, String name) { - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory.mobile"); - String serviceFolderName = environment.getProperty("bulk_waste_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 + "_" + 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(); - - Files.write(path, bytes); - - // System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - - } - - - @Transactional - public String updateBulkWasteRequest( - - Long requestId, - - String name_of_establishment, - Integer category_id, Integer zone_id, Integer ward_id, - String trade_license_No, String person_name, String email_id, - String mobile_no, String gst_No, String address, - - String total_builtup_area_sqmt, String establishment_type, - Integer dwelling_units, Integer avg_daily_footfall, String totalEmployees, - - BigDecimal wet_waste, BigDecimal dry_waste, - BigDecimal domestic_hazardous_waste, BigDecimal sanitary_waste, BigDecimal cd_waste, - - MultipartFile wasteAuditFile, - - String wet_waste_processed, String technology_used, String other_technology, - BigDecimal installed_capacity_kg, Integer installation_year, String vendor_name, - String unit_functional_status, MultipartFile installedUnitPhoto, - - boolean removeInstalledPhoto, - - String longitude, String latitude, - - String dry_waste_recycler, String recycler_name, String recycler_authorization_no, - - BigDecimal residual_waste_quantity, String collection_frequency, String vehicle_type, - - Integer update_by - - ) { - - try { - - //===================================================== - // Store Existing Record into Log Table - //===================================================== - - String logSql = - "INSERT INTO bulk_waste_request_log(" + - "request_id,name_of_establishment,category_id,zone_id,ward_id," + - "trade_license_No,person_name,email_id,mobile_no,gst_No,address," + - "total_builtup_area_sqmt,establishment_type,dwelling_units," + - "avg_daily_footfall,totalEmployees,wet_waste,dry_waste," + - "domestic_hazardous_waste,sanitary_waste,cd_waste," + - "waste_audit_report_file,wet_waste_processed,technology_used," + - "other_technology,installed_capacity_kg,installation_year," + - "vendor_name,unit_functional_status,installed_unit_photo_file," + - "longitude,latitude,dry_waste_recycler,recycler_name," + - "recycler_authorization_no,residual_waste_quantity," + - "collection_frequency,vehicle_type,is_active,is_delete," + - "cdate,update_date,update_by,log_cdate)" + - - " SELECT " + - "request_id,name_of_establishment,category_id,zone_id,ward_id," + - "trade_license_No,person_name,email_id,mobile_no,gst_No,address," + - "total_builtup_area_sqmt,establishment_type,dwelling_units," + - "avg_daily_footfall,totalEmployees,wet_waste,dry_waste," + - "domestic_hazardous_waste,sanitary_waste,cd_waste," + - "waste_audit_report_file,wet_waste_processed,technology_used," + - "other_technology,installed_capacity_kg,installation_year," + - "vendor_name,unit_functional_status,installed_unit_photo_file," + - "longitude,latitude,dry_waste_recycler,recycler_name," + - "recycler_authorization_no,residual_waste_quantity," + - "collection_frequency,vehicle_type,is_active,is_delete," + - "cdate,update_date,update_by,NOW()" + - " FROM bulk_waste_request WHERE request_id=?"; - - jdbcTemplate.update(logSql, requestId); - - //-------------------------------------------------- - // Existing File Paths - //-------------------------------------------------- - - String wasteAuditPath = jdbcTemplate.queryForObject( - "SELECT waste_audit_report_file FROM bulk_waste_request WHERE request_id=?", - String.class, - requestId); - - String installedPhotoPath = jdbcTemplate.queryForObject( - "SELECT installed_unit_photo_file FROM bulk_waste_request WHERE request_id=?", - String.class, - requestId); - - // Remove old installed photo - if(removeInstalledPhoto){ - installedPhotoPath = null; - } - - //-------------------------------------------------- - // Upload New Files - //-------------------------------------------------- - - if (wasteAuditFile != null && !wasteAuditFile.isEmpty()) { - wasteAuditPath = fileUpload(wasteAuditFile, "waste_audit"); - - } - - if (installedUnitPhoto != null && !installedUnitPhoto.isEmpty()) { - installedPhotoPath = fileUpload(installedUnitPhoto, "installed_unit"); - } - - //---------------------------------------------------- - // If Wet Waste = No - //---------------------------------------------------- - - if ("No".equalsIgnoreCase(wet_waste_processed)) { - - technology_used = null; - other_technology = null; - - installed_capacity_kg = null; - installation_year = null; - vendor_name = null; - - unit_functional_status = null; - - longitude = null; - latitude = null; - - installedPhotoPath = null; - } - - //---------------------------------------------------- - // If Recycler = No - //---------------------------------------------------- - - if ("No".equalsIgnoreCase(dry_waste_recycler)) { - - recycler_name = null; - recycler_authorization_no = null; - } - - //-------------------------------------------------- - // Check Duplicate Mobile Number - //-------------------------------------------------- - - Integer mobileCount = jdbcTemplate.queryForObject( - - "SELECT COUNT(*) FROM bulk_waste_request " + - "WHERE mobile_no=? AND request_id<>? AND is_delete=0", - - Integer.class, - - mobile_no, - requestId - ); - - if (mobileCount != null && mobileCount > 0) { - return "mobile_exists"; - } - - - - //-------------------------------------------------- - // Update - //-------------------------------------------------- - - String sql = - - "UPDATE bulk_waste_request SET " + - - "name_of_establishment=?,category_id=?,zone_id=?,ward_id=?,trade_license_No=?," + - "person_name=?,email_id=?,mobile_no=?,gst_No=?,address=?," + - - "total_builtup_area_sqmt=?,establishment_type=?,dwelling_units=?," + - "avg_daily_footfall=?,totalEmployees=?," + - - "wet_waste=?,dry_waste=?,domestic_hazardous_waste=?,sanitary_waste=?,cd_waste=?," + - "waste_audit_report_file=?," + - - "wet_waste_processed=?,technology_used=?,other_technology=?," + - "installed_capacity_kg=?,installation_year=?,vendor_name=?," + - "unit_functional_status=?,installed_unit_photo_file=?," + - - "longitude=?,latitude=?," + - - "dry_waste_recycler=?,recycler_name=?,recycler_authorization_no=?," + - - "residual_waste_quantity=?,collection_frequency=?,vehicle_type=?," + - - "update_date=NOW()," + - "update_by=? " + - - "WHERE request_id=?"; - - int count = jdbcTemplate.update( - - sql, - - name_of_establishment, category_id, zone_id, ward_id, - trade_license_No, person_name, email_id, mobile_no, gst_No, address, - - total_builtup_area_sqmt, establishment_type, dwelling_units, avg_daily_footfall, totalEmployees, - - wet_waste, dry_waste, domestic_hazardous_waste, sanitary_waste, cd_waste, - - wasteAuditPath, - - wet_waste_processed, technology_used, other_technology, installed_capacity_kg, - installation_year, vendor_name, unit_functional_status, installedPhotoPath, - - longitude, latitude, - - dry_waste_recycler, recycler_name, recycler_authorization_no, - - residual_waste_quantity, collection_frequency, vehicle_type, - - update_by, - - requestId - ); - - return count > 0 ? "success" : "error"; - - } catch (Exception e) { - - e.printStackTrace(); - return "error"; - } - } - - - // ============================== - // Delete Details - // ============================== - - - public String deactivatebulkrequest(int requestId,Integer updateBy) { - - try { - - String sql = - "UPDATE bulk_waste_request " + - "SET is_active = 0, is_delete = 1,update_by=?,update_date=NOW() " + - "WHERE request_id = ?"; - - - int count = jdbcTemplate.update(sql, updateBy,requestId); - - if (count > 0) { - return "success"; - } else { - return "error"; - } - - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - - - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/APIController.java deleted file mode 100644 index 3cd62e5b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/APIController.java +++ /dev/null @@ -1,151 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -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.gccoffice.c_petition.service.Petition; -import in.gov.chennaicorporation.gccoffice.c_petition.service.PetitionMaster; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/c_petition") -@RestController("cpRest") // Mayor Petition Rest -public class APIController { - private PetitionMaster petitionMaster; - private Petition petition; - - @Autowired - public APIController(PetitionMaster petitionMaster,Petition petition) { - this.petitionMaster = petitionMaster; - this.petition = petition; - } - - @GetMapping(value="/getComplaintTypes") - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @GetMapping(value="/getOfficerList") - public List getOfficerList() { - return petitionMaster.getOfficerList(); - } - - @GetMapping(value="/getPetitionList") - public List getPetitionList() { - return petition.getPetitionList(); - } - - @GetMapping(value="/getUnmapPetitionList") - public List getUnmapPetitionList() { - return petition.getUnmapPetitionList(); - } - - @GetMapping(value="/getPetitionDetails") - public List getPetitionDetails(@RequestParam("petitionNo") String petitionNo) { - return petition.getPetitionDetails(petitionNo); - } - - @PostMapping(value="/savePetition") - public String savePetition( - @RequestParam("createdBy") String createdBy, - @RequestParam("petition_type") String petitionType, - @RequestParam("petitionerName") String petitionerName, - @RequestParam("petitionerMobile") String petitionerMobile, - @RequestParam("complaintType") String petitionerComplaint, - @RequestParam("san_page1") MultipartFile page1, - @RequestParam("san_page2") MultipartFile page2, - @RequestParam("san_page3") MultipartFile page3, - @RequestParam("san_page4") MultipartFile page4) { - - return petition.savePetition(petitionType,createdBy, petitionerName, petitionerMobile, petitionerComplaint, page1, page2, page3, page4); - } - - @PostMapping(value="/updatePetition") - public Boolean updatePetition( - @RequestParam("petitionType") String petitionType, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam("petitionerName") String petitionerName, - @RequestParam("petitionerMobile") String petitionerMobile, - @RequestParam("petitionerAddress") String petitionerAddress, - @RequestParam("petitionerPincode") String petitionerPincode, - @RequestParam("complaintType") String petitionerComplaint, - @RequestParam("complaintNature") String complaintNature) { - - return petition.updatePetition(petitionNo, petitionType, createdBy, petitionerName, petitionerMobile, petitionerAddress, petitionerPincode, petitionerComplaint, complaintNature); - } - - @PostMapping(value="/mapComplientToOfficer") - public Boolean updatePetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String mapOfficers) { - - String com_mapping = mapOfficers; - - // First before Mapping need to unmaps old list - petition.unmapComplient(petitionId, petitionNo); - - if(com_mapping!=null) { - String[] com_mapping_parts = com_mapping.split(","); - for (String values : com_mapping_parts) { - String[] com_mapping_val = values.split("_"); - if (com_mapping_val.length > 0) { - String complientId = com_mapping_val[0]; - String offcierId = com_mapping_val[1]; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - } - } - } - return true; - } - - - @GetMapping(value="/getComplaintMappingDetails") - public List getComplaintMappingDetails( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("complaintTypeId") String complaintTypeId) { - return petition.getComplaintMappingDetails(petitionNo,petitionId,complaintTypeId); - } - - @GetMapping(value="/getComplaintList") - public List getComplaintList() { - return petition.getComplaintList(); - } - - @GetMapping(value="/getComplaintListByPetitionId") - public List getComplaintList(@RequestParam("petitionId") String petitionId) { - return petition.getComplaintListByPetitionId(petitionId); - } - - @GetMapping(value="/getComplaintDetails") - public List getComplaintDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintDetails(mapId); - } - - @GetMapping(value="/getComplaintActionDetails") - public List getComplaintActionDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintActionDetails(mapId); - } - - @PostMapping(value="/saveComplanitStatus") - public String saveComplanitStatus( - @RequestParam("createdBy") String createdBy, - @RequestParam("mapId") String mapId, - @RequestParam("complaintStatus") String complaintStatus, - @RequestParam("complaintActionText") String complaintActionText, - @RequestParam("action_san_page1") MultipartFile actionPage1, - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo) { - - return petition.saveComplanitStatus(createdBy, mapId, complaintStatus, complaintActionText, actionPage1, petitionId, petitionNo); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/MainController.java deleted file mode 100644 index 222e3aee..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/MainController.java +++ /dev/null @@ -1,130 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.controller; - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/c_petition") -@Controller("CouncillorPetitionController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/c_petition/"; - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"index"; - } - - @GetMapping({"/new_petition"}) - public String newPetition(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_petition"; - } - - @GetMapping("/petition-ack/{petitionNo}") - public String petitionAck(Model model,@PathVariable("petitionNo") String petitionNo) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_ack"; - } - - @GetMapping("/petition-list") - public String petitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_list"; - } - - @GetMapping("/unmapped-petition-list") - public String unMappedPetitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_not_mapped_list"; - } - - @GetMapping("/update-petition") - public String petitionUpadte(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/view-petition") - public String petitionView(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view"; - } - - @GetMapping("/view-petition-modal") - public String petitionViewModal(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view_modal_page"; - } - - @GetMapping("/search-petition") - public String petitionSearch(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - //model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/complaint-list") - public String complaintList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"complaint_list"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/package-info.java deleted file mode 100644 index 689ef58f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/data/ComplaintType.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/data/ComplaintType.java deleted file mode 100644 index 6e805e91..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/data/ComplaintType.java +++ /dev/null @@ -1,21 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.data; - -import java.util.Map; - -public class ComplaintType { - private int complaintTypeId; - private String complaintType; - - public ComplaintType(Map map) { - this.complaintTypeId = (int) map.get("complaint_typeid"); - this.complaintType = (String) map.get("complaint_type"); - } - - public int getComplaintTypeId() { - return complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/data/package-info.java deleted file mode 100644 index 2360a8cc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/entity/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/entity/package-info.java deleted file mode 100644 index 289ae4d0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/entity/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.entity; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/package-info.java deleted file mode 100644 index 836e684e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ -/** - * - */ -package in.gov.chennaicorporation.gccoffice.c_petition; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/Petition.java deleted file mode 100644 index fd39086b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/Petition.java +++ /dev/null @@ -1,709 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.transaction.annotation.Transactional; -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.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.m_petition.data.ComplaintType; -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -@Service("cPetitionService") -public class Petition { - private JdbcTemplate jdbcTemplate; - private final Environment environment; - private PetitionMaster petitionMaster; - - @Autowired - public Petition(Environment environment,PetitionMaster petitionMaster) { - this.environment = environment; - this.petitionMaster = petitionMaster; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlCouncillorPetitionDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - /* - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - return complaintTypeMaps.stream() - .map(ComplaintType::new) - .collect(Collectors.toList()); - } - */ - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - List complaintTypes = new ArrayList<>(); - for (Map complaintTypeMap : complaintTypeMaps) { - complaintTypes.add(new ComplaintType(complaintTypeMap)); - } - return complaintTypes; - } - - @Transactional(readOnly = true) - // Method to map complaint type IDs to their respective complaint types - public static String mapComplaintTypes(List complaintTypes, String complaint) { - String[] complaintIds = complaint.split(","); - StringBuilder complaintTxtBuilder = new StringBuilder(); - - for (String complaintId : complaintIds) { - int id = Integer.parseInt(complaintId); - for (ComplaintType type : complaintTypes) { - if (type.getComplaintTypeId() == id) { - if (complaintTxtBuilder.length() > 0) { - complaintTxtBuilder.append(","); - } - complaintTxtBuilder.append(type.getComplaintType()); - break; - } - } - } - - return complaintTxtBuilder.toString(); - } - - @Transactional(readOnly = true) - public List> getPetitionList() { - try { - String sqlQuery = "SELECT * FROM petition WHERE (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcTemplate.queryForList(sqlQuery); - Base64Util.encodeBase64(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getUnmapPetitionList() { - try { - String sqlQuery = "SELECT " - + " p.* " - + "FROM " - + " `petition` p " - + "WHERE " - + " p.`isactive` = 1 AND p.`isdelete` = 0 " - + " AND NOT EXISTS (" - + " SELECT 1 " - + " FROM `petition_mapping` pm " - + " WHERE (p.`petition_id` = pm.`petition_id`) AND (pm.`isactive` = 1 AND pm.`isdelete` = 0 ) " - + " )"; - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - - @Transactional(readOnly = true) - public List> getPetitionDetails(String petitionNo) { - // String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - try { - String sqlQuery = "SELECT * FROM petition WHERE petition_no = ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String savePetition( - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerComplaint, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition` " - + "(`petition_type`,`created_by`, `petitioner_name`, `petitioner_mobile`, " - + "`petitioner_complaint`, `petitioner_complaint_txt`) " - + "VALUES (?, ?, ?, ?, ?, ?)"; - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, petitionType); - ps.setString(2, createdBy); - ps.setString(3, petitionerName); - ps.setString(4, petitionerMobile); - ps.setString(5, petitionerComplaint); - ps.setString(6, petitionerComplaint_txt); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - - // Get the value of cp_ackno from application.properties - String ackno = environment.getProperty("cp_ackno"); - String ackno_prefix = environment.getProperty("cp_ackno_prefix"); - - // Convert ackno to int if needed - int acknoInt = Integer.parseInt(ackno); - - // Calculate the petition number - int petitionNo = (int) (lastInsertId + acknoInt); - - // Construct the petition number string - String petitionNoString = ackno_prefix + petitionNo; - - // Update the petition number in the database - updatePetitionNumber(lastInsertId, petitionNoString); - - // Add Petition Scan File in the database - addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return petitionNoString; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionNumber(int petitionId,String petitionNoString) { - String sqlQuery = "UPDATE `petition` SET `petition_no`='"+petitionNoString+"' WHERE `petition_id`='"+petitionId+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String addPetitionFile(String createdBy, - int petitionId, - String petitionNoString, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - String fileName=""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - case 2: - file = page2; - fileName = "Scan2"; - break; - case 3: - file = page3; - fileName = "Scan3"; - break; - case 4: - file = page4; - fileName = "Scan4"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("cp_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = petitionId + "_" + fileName + "_" + petitionNoString + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"','"+petitionNoString+"','"+petitionId+"')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - @Transactional - public boolean updatePetition( - String petitionType, - String petitionNo, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerAddress, - String petitionerPincode, - String petitionerComplaint, - String complaintNature) { - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - /* - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type`='"+petitionType+"', `created_by`='"+createdBy+"', `petitioner_name`='"+petitionerName+"', `petitioner_mobile`='"+petitionerMobile+"', " - + "`petitioner_address`='"+petitionerAddress+"', `petitioner_pincode`='"+petitionerPincode+"'," - + "`petitioner_complaint`='"+petitionerComplaint+"', `petitioner_complaint_txt`='"+petitionerComplaint_txt+"', `complaint_nature`='"+complaintNature+"' " - + "WHERE (`petition_no`='"+petitionNo+"') LIMIT 1"; - - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(sqlQuery); - */ - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type` = ?, `created_by` = ?, `petitioner_name` = ?, `petitioner_mobile` = ?, " - + "`petitioner_address` = ?, `petitioner_pincode` = ?, `petitioner_complaint` = ?, " - + "`petitioner_complaint_txt` = ?, `complaint_nature` = ? " - + "WHERE `petition_no` = ? LIMIT 1"; - - int rowsUpdated = jdbcTemplate.update(sqlQuery, - petitionType, - createdBy, - petitionerName, - petitionerMobile, - petitionerAddress, - petitionerPincode, - petitionerComplaint, - petitionerComplaint_txt, // Safely includes single quotes - complaintNature, - petitionNo - ); - - // Add Petition Scan File in the database - //addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return true; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return false; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionStatus(String petitionId,String petitionNo) { - String status_value = "close"; - List> petitionMappingDetails = getPetitionMappingDetails(petitionNo, petitionId); - - for (Map mapping : petitionMappingDetails) { - // Access values from the map using keys - Object status = mapping.get("status"); - // Check if status is "close" - if (!"close".equals(status)) { - status_value = "partial"; - } - - } - - String sqlQuery = "UPDATE `petition` SET `status`='"+status_value+"' WHERE `petition_no`='"+petitionNo+"' AND `petition_id`='"+petitionId+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails(String petitionNo, String petitionId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public boolean unmapComplient(String petitionId, String petitionNo) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `petition_id`='"+petitionId+"' AND `petition_no`='"+petitionNo+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public boolean mapComplientToOfficer( - String createdBy, String petitionId, String petitionNo, String complaintId, String officerId) { - String sqlQuery = "INSERT INTO `petition_mapping`" - + "(`created_by`, `off_id`, `petition_no`, `complaint_typeid`, `petition_id`) " - + "VALUES (?, ?, ?, ?, ?)"; - jdbcTemplate.update(sqlQuery, createdBy, officerId, petitionNo, complaintId, petitionId); - return true; - } - - @Transactional - public boolean updateMapComplientStatus(String mapId,String status) { - String sqlQuery = "UPDATE `petition_mapping` SET `status`=? WHERE `mapid`=? LIMIT 1"; - jdbcTemplate.update(sqlQuery, status, mapId); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getComplaintMappingDetails(String petitionNo, String petitionId, String complaintTypeId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND `complaint_typeid`= ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo,complaintTypeId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintList() { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `petition` p, `petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintListByPetitionId(String petitionId) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, p.`status` petition_status, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status` complaint_status, pm.`cdate` mappedOn, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `mayor_petition`.`petition` p,`mayor_petition`.`petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`petition_id` = '"+petitionId+"' AND p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintDetails(String mapid) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm`, ctype.`complaint_type`, " - + " COALESCE(pf.`mtm_pet_file_id`, 'No file available') AS mtm_pet_file_id, " - + " COALESCE(pf.`cdate`, '') AS file_cdate, " - + " COALESCE(pf.`created_by`, 'N/A') AS file_created_by, " - + " COALESCE(pf.`file_name`, 'No file available') AS file_name, " - + " COALESCE(pf.`file_size`, 0) AS file_size, " - + " COALESCE(pf.`file_type`, 'Unknown') AS file_type, " - + " COALESCE(pf.`isactive`, 0) AS file_isactive, " - + " COALESCE(pf.`isdelete`, 0) AS file_isdelete " - + " FROM " - + " `petition` p " - + " JOIN `petition_mapping` pm ON p.`petition_id` = pm.`petition_id` " - + " JOIN `petition_master`.`officer_master` om ON om.`off_id` = pm.`off_id` " - + " JOIN `petition_master`.`complaint_types` ctype ON ctype.`complaint_typeid` = pm.`complaint_typeid` " - + " LEFT JOIN `pentition_files` pf ON p.`petition_id` = pf.`petition_id` " - + " WHERE " - + " pm.`mapid` = '" + mapid + "' " - + " AND p.`isactive` = 1 AND p.`isdelete` = 0 " - + " AND pm.`isactive` = 1 AND pm.`isdelete` = 0 " - + " AND om.`isactive` = 1 AND om.`isdelete` = 0 "; - - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintActionDetails(String mapId) { - try { - String sqlQuery = "SELECT * FROM `petition_action_taken` WHERE (`mapid`= ? AND `isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, mapId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String saveComplanitStatus( - String createdBy, - String mapId, - String complaintStatus, - String complaintActionText, - MultipartFile actionPage1, - String petitionId, - String petitionNo) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition_action_taken` " - + "(`created_by`, `off_id`, `mapid`, `status`, " - + "`comments`) " - + "VALUES (?, ?, ?, ?, ?)"; - - try { - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, createdBy); - ps.setString(3, mapId); - ps.setString(4, complaintStatus); - ps.setString(5, complaintActionText); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int)keyHolder.getKey().longValue(); - String actionID = "error"; - if(lastInsertId>0) { - // Update Complaint Status - updateMapComplientStatus(mapId,"close"); - // Update Petition Status - updatePetitionStatus(petitionId,petitionNo); - // Add Action Scan File in the database - addActionFile(mapId,lastInsertId, actionPage1); - actionID = ""+lastInsertId; - } - - return actionID; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public String addActionFile( String mapId, int solmapid, - MultipartFile page1) { - - MultipartFile file = page1; - String fileName = "Scan1_"+solmapid; - - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("cp_foldername"); - String serviceActionFolderName = environment.getProperty("cp_action_Foldername"); - - uploadDirectory = uploadDirectory + serviceFolderName +"/"+ serviceActionFolderName; - - // File name - fileName = mapId + "_" + fileName + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "UPDATE `petition_action_taken` SET " - + "`file_name`='"+fileName+"', " - + "`file_size`='"+fileSize+"', " - + "`file_type`='"+fileType+"' " - + "WHERE `solmapid`='"+solmapid+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - return "success"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/PetitionMaster.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/PetitionMaster.java deleted file mode 100644 index d73b545a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/PetitionMaster.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("CPetitionMaster") -public class PetitionMaster { - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPetitionMasterDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getComplaintType(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `complaint_types` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getOfficerList(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `officer_master` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getPetitionTypes(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `petition_types` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby` ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/package-info.java deleted file mode 100644 index 971b5182..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.c_petition.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentAssignAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentAssignAPIController.java deleted file mode 100644 index 9f3ade55..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentAssignAPIController.java +++ /dev/null @@ -1,112 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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 in.gov.chennaicorporation.gccoffice.callcenter.service.AgentAssignService; - - -@RequestMapping("/gcc/api/callcenter/admin") -@RestController("callcentercontroller") -public class AgentAssignAPIController -{ - private AgentAssignService campaignmaster; - - @Autowired - public AgentAssignAPIController(AgentAssignService campaignmaster) { - this.campaignmaster = campaignmaster; - } - - @GetMapping("/getcategory") - public List> getcategory() - { - return campaignmaster.getcategory(); - } - - @GetMapping("/getcampaignbycategory") - public List> getcampaignbycategory(@RequestParam int id) - { - return campaignmaster.getcampaignbycategory(id); - } - -// @GetMapping("/getcampaignbyid") -// public List> getcampaignbyid(@RequestParam int id) -// { -// return campaignmaster.getcampaignbyid(id); -// } - - @GetMapping("/getagentsfortask") - public List> getagentsfortask(@RequestParam int id) - { - return campaignmaster.getagentsfortask(id); - } - - @PostMapping("/addagentsfortask") - public ResponseEntity>> addagentsfortask(@RequestBody List> requestList) { - //System.out.println("Received POST request with data: " + requestList); - - List> insertedAgents = new ArrayList<>(); // To store successfully inserted agents - - try { - for (Map request : requestList) { - int agentId = (int) request.get("agentId"); - int categoryId = (int) request.get("categoryId"); - int campaignId = (int) request.get("campaignId"); - - // Call the service method to insert the agent details - int rowsAffected = campaignmaster.addagentsfortask(agentId, categoryId, campaignId); - - if (rowsAffected > 0) { - // If the insert was successful, add the agent data to the response list - Map insertedAgent = new HashMap<>(); - insertedAgent.put("categoryId", categoryId); - insertedAgent.put("campaignId", campaignId); - insertedAgent.put("agentId", agentId); - - insertedAgents.add(insertedAgent); // Add the successfully inserted agent to the list - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonList(Collections.singletonMap("error", "Failed to add agent for campaignId: " + campaignId))); - } - } - - // Return the list of successfully inserted agents - return ResponseEntity.status(HttpStatus.CREATED).body(insertedAgents); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(Collections.singletonList(Collections.singletonMap("error", "Invalid request data: " + e.getMessage()))); - } - } - - @GetMapping("/getassignedcampaign") - public List> checkcampaigninassignedtable(@RequestParam int id) - { - return campaignmaster.checkcampaigninassignedtable(id); - } - - @GetMapping("/deleteassignedbyid") - public int editagentsfortask(@RequestParam int id) - { - return campaignmaster.editagentsfortask(id); - } - - @GetMapping("/getcampaignbyid") - public List> getcampaignquestionbyid(@RequestParam int id){ - return campaignmaster.getcampaignquestionbyid(id); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentsAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentsAPIController.java deleted file mode 100644 index c6e5cff3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentsAPIController.java +++ /dev/null @@ -1,320 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenter.service.AgentsService; - -@RequestMapping("/gcc/api/agents") -@RestController -public class AgentsAPIController { - - @Autowired - private AgentsService agentsService; - - @GetMapping("/excel") - public List> fetchDataFromExcel(@RequestParam int categoryId,@RequestParam Long campaignId) { - try { - return agentsService.fetchDataFromExcel(categoryId,campaignId); - } catch (IOException e) { - e.printStackTrace(); - return null; // Handle the exception as needed - } - } - - - @PostMapping("/saveExcelData") - public String saveExcelData( @RequestParam int categoryId,@RequestParam Long campaignId,@RequestParam String filePath) { - - try { - // Fetch data from Excel - List> excelData = agentsService.getExcelData(categoryId,campaignId, filePath); - // Save data into the database - agentsService.saveExcelData(excelData); - return "Data saved successfully"; - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save data"; - } - } - - @GetMapping("/getdataByIds") - public List> getdataByIds(@RequestParam List ids) { - return agentsService.getdataByIds(ids); - } - - @GetMapping("/getPendingDataByIds") - public List> getPendingDataByIds(@RequestParam List ids) { - return agentsService.getPendingDataByIds(ids); - } - - - -// @PostMapping("/updatecall") -// public ResponseEntity updatecall(@RequestBody Map callData) -// { -// String call_status = (String) callData.get("call_status"); -// int data_id = (int) callData.get("data_id"); -// int agent_id=(int) callData.get("agent_id"); -// int campaign_id=(int) callData.get("campaign_id"); -// -// if (call_status == null || call_status.isEmpty()) { -// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Call status is required."); -// } -// -// agentsService.saveInLogsTable(campaign_id, agent_id, data_id,call_status); -// -// return ResponseEntity.ok("Data Inserted successfully."); -// } - - @GetMapping("/getAgentNames") - public List> getAgentsNameById(@RequestParam List agentIds){ - return agentsService.getAgentsNameById(agentIds); - } - - @GetMapping("/getDataFields") - public List> getDataDetailsById( - @RequestParam String originalDataIds) throws JsonProcessingException { - - // Parse originalDataIds from JSON string - ObjectMapper objectMapper = new ObjectMapper(); - List> originalDataIdsList = objectMapper.readValue(originalDataIds, new TypeReference>>() {}); - - // Prepare a list to hold the results for each sub-array - List> groupedResults = new ArrayList<>(); - - // Iterate through each sub-array of originalDataIds - for (List dataIds : originalDataIdsList) { - List> results = agentsService.getDataDetailsById(dataIds); - // Group results according to your business logic - Map combinedResult = new HashMap<>(); - for (Map result : results) { - combinedResult.putAll(result); - } - groupedResults.add(combinedResult); - } - - return groupedResults; - } - - - @GetMapping("/getCompletedDataFields") - public Map getCompletedDataDetailsById( - @RequestParam String originalCDataIds) throws JsonProcessingException { - - // Parse originalDataIds from JSON string - ObjectMapper objectMapper = new ObjectMapper(); - List originalCDataIdsList = objectMapper.readValue(originalCDataIds, new TypeReference>() {}); - - // Prepare a list to hold the results for each sub-array - //List> groupedCompletedResults = new ArrayList<>(); - List completedDataIds = new ArrayList<>(); // List to hold data_ids with Complete_count > 0 - - // Iterate through each sub-array of originalDataIds - - List> results = agentsService.getCompletedDataDetailsById(originalCDataIdsList); - // Group results according to your business logic - //Map CompletedcombinedResult = new HashMap<>(); - for (Map result : results) { - - if (result.get("Complete_count") != null && ((Number) result.get("Complete_count")).intValue() > 0) { - completedDataIds.add((Integer) result.get("data_id")); - } - //groupedCompletedResults.add(result); - } - - - - // Prepare the final response containing grouped results and completed dataIds - Map response = new HashMap<>(); - //response.put("groupedCompletedResults", groupedCompletedResults); - response.put("completedDataIds", completedDataIds); - return response; - } - - @GetMapping("/getCompletedDataById") - public List> getCompletedDataById(@RequestParam List completedDataIds){ - return agentsService.getCompletedDataById(completedDataIds); - } - - - @PostMapping("/furtherAssignedAgents") - public ResponseEntity> updateAgentAssigndata( - @RequestBody Map requestData) { - - String campaign_id = (String) requestData.get("campaign_id"); - String category_id = (String) requestData.get("category_id"); - String call_per_agent = (String) requestData.get("call_per_agent"); - - - - - - // Correct key name for selected agents - List selectedAgentsList = (List) requestData.get("selected_agents"); - - //System.out.println("campaign_id=" + campaign_id); - //System.out.println("category_id=" + category_id); - //System.out.println("call_per_agent=" + call_per_agent); - //System.out.println("selectedAgentsList=" + selectedAgentsList); - - int campaignId = Integer.parseInt(campaign_id); - int categoryId = Integer.parseInt(category_id); - int callperagent = Integer.parseInt(call_per_agent); - - agentsService.resetAgentAssignmentForNextDay(categoryId,campaignId); - - int calls_assign = callperagent * selectedAgentsList.size(); - //System.out.println("calls_assign== " + calls_assign); - - List DataIds=agentsService.getDataIdForFurtherAssign(categoryId, campaignId); - //System.out.println("dataids=== " + DataIds); - - if (!DataIds.isEmpty()) { - int dataIndex = 0; // Initialize data index pointer - - for (String agentId : selectedAgentsList) { - int selectedAgentId = Integer.parseInt(agentId); - - agentsService.addAgentsForCampaign(selectedAgentId, categoryId, campaignId); - - // Iterate for noOfCalls times and assign data IDs to the current agent - for (int i = 0; i < callperagent && dataIndex < DataIds.size(); i++, dataIndex++) { - int DataId = DataIds.get(dataIndex); - - agentsService.updateAgentForCampaign( - selectedAgentId, - categoryId, - campaignId, - DataId - ); - } - } - - } - else { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(Map.of("status", "error", "message", "No data available for Further assign.")); - } - - return ResponseEntity.ok(Map.of("status", "success", "message", "Campaign details saved successfully")); - } - - - - ////////////////////Ajith code////////////////////// - - @GetMapping("/Campaignview") - public ResponseEntity getCampaignview(@RequestParam int categoryId, @RequestParam int agentId, @RequestParam int dataId) { - try { - List> response = agentsService.getFilteredFields(categoryId, agentId, dataId); - - if (response.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No matching data found."); - } - - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage()); - } - } - - - - @GetMapping("/questions") - public List> getCampaignQuestions( - @RequestParam int categoryId, - @RequestParam int campaignId) { - - return agentsService.getCampaignQuestions(categoryId, campaignId); - } - - @GetMapping("/fetchAnswer") - public List> fetchAnswer( - @RequestParam int campaignId, - @RequestParam int agentId, - @RequestParam int questionId, - @RequestParam int dataId) { - - return agentsService.FetchAnswer(campaignId,agentId,questionId,dataId); - } - - - @PostMapping("/submitAnswers") - public ResponseEntity submitAnswers(@RequestBody Map>> requestData) { - List> answers = requestData.get("answers"); - - if (answers == null || answers.isEmpty()) { - return ResponseEntity.badRequest().body("No answers provided."); - } - - agentsService.saveAnswers(answers); - return ResponseEntity.ok("Answers submitted successfully"); - } - - - @GetMapping("/callstatus") - public List> getCallStatus() { - //System.out.println("dropdown"); - return agentsService.getCallStatus(); - } - - @GetMapping("/checkCounts") - public List> checkCounts( - @RequestParam int campaignId, - @RequestParam int dataId) { - - return agentsService.checkCounts(campaignId,dataId); - } - - @PostMapping("/savecall") - public ResponseEntity savecall(@RequestBody Map callData) { - String call_status = (String) callData.get("call_status"); - String remarks = (String) callData.get("remarks"); - int data_id = Integer.parseInt(callData.get("data_id").toString()); - int agent_id = Integer.parseInt(callData.get("agent_id").toString()); - int campaign_id = Integer.parseInt(callData.get("campaign_id").toString()); - - // System.out.println("controler"); - //System.out.println(call_status); - - // Add a debug statement to check the received values - // System.out.println("Received call_status: " + call_status); - - if (call_status == null || call_status.isEmpty()) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Call status is required."); - } - - - agentsService.saveCallLogs(call_status, remarks,data_id,agent_id); - - agentsService.saveInLogsTable(campaign_id, agent_id, data_id,call_status,remarks); - - return ResponseEntity.ok("Data Inserted successfully."); - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AttendanceAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AttendanceAPIController.java deleted file mode 100644 index a0d8bcad..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AttendanceAPIController.java +++ /dev/null @@ -1,36 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("/gcc/api/attendance") -@RestController -public class AttendanceAPIController { - - private AppConfig appConfig; - private final RestTemplate restTemplate; - - @Autowired - public AttendanceAPIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - - - @GetMapping("/getAttendancedetails") - public String getAttendancedetails(@RequestParam String fromDate,@RequestParam String toDate){ - String apiUrl = appConfig.attendanceReport + "/callcenter/api/attendance/getattendancereport"+"?fromDate="+ fromDate + "&toDate="+ toDate; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java deleted file mode 100644 index b58c5a22..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java +++ /dev/null @@ -1,643 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import org.apache.poi.ss.usermodel.*; - - -import org.springframework.web.multipart.MultipartFile; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import org.springframework.jdbc.core.JdbcTemplate; - -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.RequestPart; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.callcenter.service.AddcategoryServices; -import in.gov.chennaicorporation.gccoffice.callcenter.service.AgentAssignService; -import in.gov.chennaicorporation.gccoffice.callcenter.service.CampaignService; - -@RestController("callcenterapicontroller") -@RequestMapping("gcc/api/campaign") -public class CampaignAPIController { - - @Autowired - private CampaignService campaignService; - - @Autowired - private AddcategoryServices addCategoryServices; // Injecting the service - - @Autowired - private AgentAssignService agentsAssignService; - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private Environment environment; - - @GetMapping("/getCampaignDetails") - public ResponseEntity> getCampaignDetails() { - Map response = new HashMap<>(); - List> data = campaignService.getCampaignDetails(); - - response.put("data", data); - return ResponseEntity.ok(response); - } - - - // Endpoint to get campaign details by ID - @GetMapping("/getCampaignDetailsById") - public @ResponseBody List> getCampaignDetailsById(@RequestParam("campaign_id") Long campaignId) { - return campaignService.getCampaignDetailsById(campaignId); - } - - - @PostMapping("/updateCampaign") - public ResponseEntity updateCampaign( - @RequestBody Map requestData) { - - Long campaign_id = ((Number) requestData.get("campaign_id")).longValue(); - String end_date = (String) requestData.get("end_date"); - List> questionsData = - (List>) requestData.get("questionsData"); - - if (campaign_id == null) { - return ResponseEntity.badRequest().body("Campaign ID is required."); - } - - try { - // Update campaign details - campaignService.updateCampaign(campaign_id, end_date); - - // Save questions and answers - for (Map questionMap : questionsData) { - String category = (String) questionMap.get("category"); - String question = (String) questionMap.get("question"); - String answerType = (String) questionMap.get("answerType"); - List answers = (List) questionMap.get("answers"); - - if (category != null && question != null && answerType != null) { - campaignService.saveQuestionsAndAnswers( - category, - String.valueOf(campaign_id), // Corrected data type - question, - answerType, - answers - ); - } - } - - return ResponseEntity.ok("Campaign updated successfully."); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error updating campaign: " + e.getMessage()); - } - } - - - - //save question and ansewers for campaign - @PostMapping("/saveQuestionsAndAnswers") - public ResponseEntity saveQuestions(@RequestBody List> requestData) { - String response = campaignService.saveQuestionsAnswers(requestData); - return ResponseEntity.ok(response); - } - - //save file and get path - private String saveFile(MultipartFile file) throws IOException { - - String uploadDirectory = environment.getProperty("file.upload.directory"); - - String folderName = environment.getProperty("campaign.foldername"); - - String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + "_" + file.getOriginalFilename(); - - String folderPath = uploadDirectory + "/" + folderName + "/excel/"; - - - Path dirPath = Paths.get(folderPath); - if (!Files.exists(dirPath)) { - Files.createDirectories(dirPath); - } - - Path filePath = dirPath.resolve(fileName); - - Files.write(filePath, file.getBytes()); - - return filePath.toAbsolutePath().toString(); - } - - - //read uploaded excel data and make condition for each category uploading same excel columns are other some other? - private List> readExcelData(InputStream inputStream, List categoryColumns) throws IOException { - List> dataList = new ArrayList<>(); - - try (Workbook workbook = new XSSFWorkbook(inputStream)) { - Sheet sheet = workbook.getSheetAt(0); - FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - // Read header row from Excel - Row headerRow = sheet.getRow(0); - List excelHeaders = new ArrayList<>(); - for (Cell cell : headerRow) { - excelHeaders.add(cell.getStringCellValue().trim()); - } - - // Compare Excel headers with category columns - if (!excelHeaders.containsAll(categoryColumns)) { - // throw new IllegalArgumentException("Excel data does not match the category columns."); - - } - - // Proceed with reading data only if headers match - for (Row row : sheet) { - if (row.getRowNum() == 0) continue; // Skip header row - - Map dataMap = new HashMap<>(); - for (Cell cell : row) { - String cellValue = ""; - switch (formulaEvaluator.evaluateInCell(cell).getCellType()) { - case STRING: - cellValue = cell.getStringCellValue(); - break; - case NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue()); - } else { - // Check if value is an integer (whole number) - if (cell.getNumericCellValue() % 1 == 0) { - cellValue = String.valueOf((long) cell.getNumericCellValue()); // Format as integer - } else { - cellValue = String.valueOf(cell.getNumericCellValue()); // Keep decimal values as they are - } - } - break; - case BOOLEAN: - cellValue = String.valueOf(cell.getBooleanCellValue()); - break; - default: - cellValue = "Unknown"; - break; - } - // Map cell data to correct column name - dataMap.put(excelHeaders.get(cell.getColumnIndex()), cellValue); - } - - if (!dataMap.isEmpty()) { - dataList.add(dataMap); - } - } - } - - return dataList; - } - - - - - - - @GetMapping("/getExcelData") - public ResponseEntity>> getExcelData(@RequestParam("filePath") String filePath) { - try { - // Read data from the uploaded Excel file - List> excelData = readExcelData(new FileInputStream(filePath), null); - - // Return data as JSON - return ResponseEntity.ok(excelData); - - } catch (IOException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - } - - - @GetMapping("/getlastCampaignid") - public List> getLastRow() - { - return campaignService.getLastRow(); - } - - @GetMapping("/startcampaign") - public List> getDataforAgents(@RequestParam int campaign_id,@RequestParam int calls_per_agent) - { - return campaignService.getDataforAgents(campaign_id, calls_per_agent); - } - - @GetMapping("/viewcampaignstatus") - public List> viewcampaignstatus(@RequestParam int campaign_id) - { - return campaignService.viewcampaignstatus(campaign_id); - } - - @GetMapping("/viewcompletedby") - public List> viewcompletedby(@RequestParam int campaign_id,@RequestParam int agent_id) - { - return campaignService.viewcompletedby(campaign_id,agent_id); - } - - - - - - @PostMapping(value = "/savecampaign", consumes = {"multipart/form-data"}) - public ResponseEntity> saveCampaign( - @RequestParam String campaignId, - @RequestParam String categoryId, - @RequestParam String eventStartDate, - @RequestParam String eventEndDate, - @RequestParam int noOfCalls, - @RequestParam String description, - @RequestParam(required = false) String questionsData, // JSON as String - @RequestParam(required = false) String selectedAgents // JSON string - ) { - - - // Convert JSON strings to List objects - List> questionsDataList = new ArrayList<>(); - List selectedAgentsList = new ArrayList<>(); - - try { - if (questionsData != null) { - questionsDataList = new ObjectMapper().readValue(questionsData, new TypeReference>>() {}); - } - - if (selectedAgents != null) { - selectedAgentsList = new ObjectMapper().readValue(selectedAgents, new TypeReference>() {}); - } - } catch (JsonProcessingException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(Map.of("status", "error", "message", "Invalid JSON format in request data")); - } - - // Campaign Details Mapping - Map campaignDetails = new HashMap<>(); - campaignDetails.put("campaign_id", campaignId); - campaignDetails.put("category_id", categoryId); - campaignDetails.put("start_date", eventStartDate); - campaignDetails.put("end_date", eventEndDate); - campaignDetails.put("calls_per_agent", noOfCalls); - campaignDetails.put("description", description); - - try { - campaignService.saveCampaignDetails(campaignDetails); - - // Step 3: Assign Agents for the Campaign - if (!selectedAgentsList.isEmpty()) { - int parsedCampaignId = Integer.parseInt(campaignId); - int parsedCategoryId = Integer.parseInt(categoryId); - - System.out.println("selectedAgentsList====== " + selectedAgentsList); - - int calls_assign = noOfCalls * selectedAgentsList.size(); - System.out.println("calls_assign== " + calls_assign); - - List DataIds=agentsAssignService.getDataIdForInitialAssign(parsedCategoryId, parsedCampaignId); - - for (String agentId : selectedAgentsList) { - int selectedAgentId = Integer.parseInt(agentId); - - agentsAssignService.addAgentsForCampaign(selectedAgentId, parsedCategoryId, parsedCampaignId); - } - //System.out.println("dataids=== " + DataIds); - if (!DataIds.isEmpty()) { - int dataIndex = 0; // Initialize data index pointer - - for (String agentId : selectedAgentsList) { - int selectedAgentId = Integer.parseInt(agentId); - - // Iterate for noOfCalls times and assign data IDs to the current agent - for (int i = 0; i < noOfCalls && dataIndex < DataIds.size(); i++, dataIndex++) { - int DataId = DataIds.get(dataIndex); - - agentsAssignService.updateAgentForCampaign( - selectedAgentId, - parsedCategoryId, - parsedCampaignId, - DataId - ); - } - } - - // Update campaign status to 'ONGOING' after successful assignment - campaignService.updateCampaignStatus(parsedCampaignId, parsedCategoryId); - } - - else { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(Map.of("status", "error", "message", "No data available for initial assignment.")); - } - - } - - // Step 4: Save Questions and Answers - if (!questionsDataList.isEmpty()) { - for (Map questionMap : questionsDataList) { - String question = (String) questionMap.get("question"); - String answerType = (String) questionMap.get("answerType"); - List answers = (List) questionMap.get("answers"); - - if (question != null && answerType != null) { - campaignService.saveQuestionsAndAnswers( - categoryId, - campaignId, - question, - answerType, - answers - ); - } else { - System.out.println("Skipping invalid question data: " + questionMap); - } - } - } - - } - - - catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "error", "message", "Failed to save campaign details: " + e.getMessage())); - } - - return ResponseEntity.ok(Map.of("status", "success", "message", "Campaign details saved successfully")); - } - - - //save excel data separate method - - @PostMapping(value = "/saveexcelcampaign" ,consumes = {"multipart/form-data"}) - public Map saveExcelCampaign( - @RequestParam String name, - @RequestParam String category, - @RequestPart MultipartFile file) { - - //System.out.println("Received campaign data:"); - //System.out.println("Name: " + name); - //System.out.println("Category: " + category); - - //System.out.println("File Name: " + file.getOriginalFilename()); - - Map campaignDetails = new HashMap<>(); - campaignDetails.put("campaign_name", name); - campaignDetails.put("category_id", category); - - - try { - // Get category-specific columns - List> categoryColumns = addCategoryServices.getCategoryColumns(Integer.parseInt(category)); - /* - //System.out.println("categorycolmns: " + categoryColumns); - List expectedHeaders = categoryColumns.stream() - .map(column -> column.get("column_name").toString()) - .collect(Collectors.toList()); - */ - List expectedHeaders = new ArrayList(); - - for (Map column : categoryColumns) { - Object columnNameObj = column.get("column_name"); - if (columnNameObj != null) { - expectedHeaders.add(columnNameObj.toString()); - } - } - // Fetch field_ columns from upload_data table - List fieldColumns = campaignService.getUploadDataFieldColumns(); - //System.out.println("fieldColumns: " + fieldColumns); - - - // Read uploaded Excel data and extract headers - List> excelData = readExcelData(file.getInputStream(), expectedHeaders); - - // System.out.println("excedata: " + excelData ); - List uploadedHeaders = new ArrayList<>(excelData.get(0).keySet()); // Extract headers from first row - - //System.out.println("uploadeddata : " + uploadedHeaders); - - // Check column count mismatch with field_ columns - if (uploadedHeaders.size() > fieldColumns.size()) { - Map response = new HashMap<>(); - response.put("status", "column_mismatch"); // Changed status to differentiate - response.put("message", "Extend the columns in Database, Inform Admin."); - return response; - } - - // Validate headers - if (!new HashSet<>(expectedHeaders).equals(new HashSet<>(uploadedHeaders))) { - Map response = new HashMap<>(); - response.put("status", "header_mismatch"); // Changed status to differentiate - response.put("message", "Excel data does not match the category columns."); - return response; - } - - - String fileUrl = saveFile(file); - campaignDetails.put("excel_url", fileUrl); - - //System.out.println("Campaign Details: " + campaignDetails); - //System.out.println("Excel Data: " + excelData); - - campaignService.saveCampaignDetailsExcel(campaignDetails); - int lastId = campaignService.getLastInsertedCampaignId(); - - String excelUrl = campaignService.getExcelUrlByCampaignId(lastId); - //List> excelDatas = readExcelDataupdated(new FileInputStream(excelUrl)); - List> excelDatas = readExcelData(new FileInputStream(excelUrl), uploadedHeaders); - //System.out.println("excelDatas:" + excelDatas); - - for (Map row : excelDatas) { - campaignService.saveUploadData(category, lastId, row,expectedHeaders); - //System.out.println("exceldatas:" + excelDatas); - } - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("message", "Campaign and Excel saved successfully"); - return response; - - } - catch (IOException e) { - e.printStackTrace(); - Map response = new HashMap<>(); - response.put("status", "error"); - response.put("message", "Failed to save campaign details: "+ e.getMessage()); - return response; - } - } - - - - - - @GetMapping("/availableAgents") - public ResponseEntity>> getAvailableAgents() { - // Query 1: Fetch OUTBOUND agents - String outboundAgentsQuery = "SELECT agent_name, agent_id, calling_type " + - "FROM gcc_1913_qaqc.agents_list " + - "WHERE calling_type='OUTBOUND'"; - - List> outboundAgents = jdbcTemplate.queryForList(outboundAgentsQuery); - - //System.out.println("outboundagents" + outboundAgents); - // Query 2: Fetch agents from ongoing campaigns - String ongoingCampaignAgentsQuery = "SELECT ca.agent_id " + - "FROM gcc_1913_campaign.campaign_request cr " + - "JOIN gcc_1913_campaign.agent_assign ca " + - "ON ca.campaign_id = cr.campaign_id " + - "WHERE cr.campaign_status = 'ONGOING'"; - - List> ongoingAgents = jdbcTemplate.queryForList(ongoingCampaignAgentsQuery); - - //System.out.println("ongoingAgents" + ongoingAgents); - // Extract agent IDs from both lists - /* - Set ongoingAgentIds = ongoingAgents.stream() - .map(agent -> (Integer) agent.get("agent_id")) - .collect(Collectors.toSet()); - - // Filter OUTBOUND agents who are NOT in ongoing agents - List> availableAgents = outboundAgents.stream() - .filter(agent -> !ongoingAgentIds.contains(agent.get("agent_id"))) - .collect(Collectors.toList()); - - */ - Set ongoingAgentIds = new HashSet<>(); - - for (Map agent : ongoingAgents) { - Object idObj = agent.get("agent_id"); - if (idObj != null) { - ongoingAgentIds.add(Integer.parseInt(idObj.toString())); - } - } - - // Filter OUTBOUND agents who are NOT in ongoing agents - List> availableAgents = new ArrayList<>(); - - for (Map agent : outboundAgents) { - Object idObj = agent.get("agent_id"); - if (idObj != null) { - Integer agentId = Integer.parseInt(idObj.toString()); - if (!ongoingAgentIds.contains(agentId)) { - availableAgents.add(agent); - } - } - } - - return ResponseEntity.ok(availableAgents); - } - - - - private Object getCellValue(Cell cell) { - switch (cell.getCellType()) { - case STRING: - return cell.getStringCellValue().trim(); - case NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - return cell.getDateCellValue(); // Return Date for date-formatted cells - } - double numericValue = cell.getNumericCellValue(); - - // ✅ Convert numeric values that are likely mobile numbers to string - if (String.valueOf((long) numericValue).length() >= 10) { // Assuming mobile numbers are at least 10 digits - return String.valueOf((long) numericValue); - } - - // ✅ Convert to int if no decimal part, else keep as double - return (numericValue % 1 == 0) ? (int) numericValue : numericValue; - case BOOLEAN: - return cell.getBooleanCellValue(); - case FORMULA: - return cell.getCellFormula(); // Return formula as string - case BLANK: - return ""; - default: - return ""; - } - } - - - - //question and answers report page api - @GetMapping("/question-answers") - public ResponseEntity getQuestionAnswers(@RequestParam int campaignId) { - List> response = campaignService.getQuestionAnswers(campaignId); - return ResponseEntity.ok(response); - } - - - //dizo campaignlist apicontroller - // Query Parameter Approach - @GetMapping("/statistics") - public ResponseEntity> getCampaignStatisticsByQuery(@RequestParam int campaignId) { - Map statistics = campaignService.getCampaignStatistics(campaignId); - return ResponseEntity.ok(statistics); - } - - @GetMapping("/assignagentid") - public ResponseEntity>> getAllAgents() { - List> assignAgentId = campaignService.getAllAgents(); - return ResponseEntity.ok(assignAgentId); - } - - @PostMapping("/close") - public ResponseEntity closeCampaign(@RequestParam("campaignId") int campaignId) { - if (campaignId <= 0) { - return ResponseEntity.badRequest().body("Invalid Campaign ID"); - } - - System.out.println("Received request to close campaign ID: " + campaignId); // Debugging log - - int rowsUpdated = campaignService.closeCampaign(campaignId); - if (rowsUpdated > 0) { - return ResponseEntity.ok("Campaign closed successfully"); - } else { - return ResponseEntity.status(400).body("Failed to close campaign. Campaign ID " + campaignId + " may not exist."); - } - } - - @PostMapping("/auto-close") - public ResponseEntity autoCloseExpiredCampaigns() { - - int rowsUpdated = campaignService.autoCloseExpiredCampaigns(); - - if (rowsUpdated > 0) { - return ResponseEntity.ok(rowsUpdated + " expired campaigns closed successfully."); - } else { - return ResponseEntity.ok("No expired campaigns found."); - } - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignDropdownApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignDropdownApiController.java deleted file mode 100644 index ef060803..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignDropdownApiController.java +++ /dev/null @@ -1,29 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import java.util.List; -import java.util.Map; - - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.callcenter.service.CampaignDropdownApiService; - -@RequestMapping("gcc/api") -@RestController -public class CampaignDropdownApiController { - - - @Autowired - private CampaignDropdownApiService dropdownApiService; - - @GetMapping("/getAnswerTypes") - @ResponseBody - public List> getAnswerTypes() { - return dropdownApiService.getAnswerTypes(); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignReportAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignReportAPIController.java deleted file mode 100644 index 3e0f01f1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignReportAPIController.java +++ /dev/null @@ -1,100 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.callcenter.service.CampaignReportService; - -@RestController -@RequestMapping("gcc/api/campaignreport") -public class CampaignReportAPIController { - - @Autowired - private CampaignReportService campaignReportService; - - @GetMapping("/getcampaignData") - public List> getCampaignData( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - List> campaignData = campaignReportService.getCampaignData(startDate, endDate); - //System.out.println("Campaign Data: " + campaignData); // Debugging log - return campaignData; - } - - @GetMapping("/getagentdatacount") - public List> getAgentwiseData(@RequestParam String campaign_id) { - List> agentData = campaignReportService.getAgentwiseData(campaign_id); - //System.out.println("Agent Data: " + agentData); - return agentData; - } - - @GetMapping("/getReportCampaignid") - public ResponseEntity getAgentReportCampaignId(@RequestParam String campaign_id) { - - List> agentData = campaignReportService.getAgentReportCampaignId(campaign_id); - //System.out.println("Agent Data: " + agentData); - return ResponseEntity.ok(agentData); - } - - //question and answers report page api - @GetMapping("/question-answers") - public ResponseEntity getQuestionAnswers(@RequestParam int campaign_id) { - List> response = campaignReportService.getQuestionAnswers(campaign_id); - return ResponseEntity.ok(response); - } -// @GetMapping("/download-excel") -// public void downloadFilteredCSV( -// @RequestParam int categoryId, -// @RequestParam int campaignId, -// -// -// -// HttpServletResponse response) throws IOException { -// -// // Set response headers -// response.setContentType("text/csv"); -// response.setHeader("Content-Disposition", "attachment; filename=filtered_data.csv"); -// -// // Generate CSV and write to response -// PrintWriter writer = response.getWriter(); -// campaignReportService.generateCSV(categoryId, campaignId, writer); -// writer.flush(); -// writer.close(); -// } - - - @GetMapping("/download-excel") - public void downloadFilteredCSV( - @RequestParam int categoryId, - @RequestParam int campaignId, - HttpServletResponse response) throws IOException { - - String filename = campaignReportService.getCampaignName(campaignId); - // Format campaign name for file safety (remove spaces/special characters) - //String safeCampaignName = filename.replaceAll("[^a-zA-Z0-9]", "_"); - - // Set response headers - response.setContentType("text/csv"); - response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".csv"); - - // Generate CSV and write to response - PrintWriter writer = response.getWriter(); - campaignReportService.generateCSV(categoryId, campaignId, writer); - writer.flush(); - writer.close(); - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CategoryAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CategoryAPIController.java deleted file mode 100644 index 12a17047..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CategoryAPIController.java +++ /dev/null @@ -1,281 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import java.util.HashMap; -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -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 in.gov.chennaicorporation.gccoffice.callcenter.service.AddcategoryServices; - - -@RequestMapping("/gcc/api/category") -@RestController -public class CategoryAPIController { - - @Autowired - private AddcategoryServices addCategoryServices; // Injecting the service - - @PostMapping("/save") - public ResponseEntity saveCategoryDetails(@RequestBody Map payload) { - try { - addCategoryServices.saveCategoryDetails(payload); - return ResponseEntity.ok("Category and columns saved successfully."); - } catch (IllegalArgumentException e) { - return ResponseEntity.badRequest().body("Validation Error: " + e.getMessage()); - } catch (Exception e) { - return ResponseEntity.status(500).body("Internal Server Error: " + e.getMessage()); - } - } - - - // Endpoint to save category details -// @PostMapping("/save") -// public ResponseEntity saveCategoryDetails(@RequestBody Map payload) { -// try { -// addCategoryServices.saveCategoryDetails(payload); // Call the service method to save category details -// return ResponseEntity.ok("Category details saved successfully."); -// } catch (IllegalArgumentException e) { -// return ResponseEntity.badRequest().body("Error: " + e.getMessage()); -// } catch (Exception e) { -// return ResponseEntity.status(500).body("Error saving category details: " + e.getMessage()); -// } -// } - - // Endpoint to get all categories - @GetMapping("/list") - public List> getAllCategories() { - return addCategoryServices.getAllCategories(); - } - - @GetMapping("/showcategoryId") - public ResponseEntity getCategoryById(@RequestParam("category_id") int categoryId) { - Map category = addCategoryServices.showCategory(categoryId); - if (category.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found"); - } - return ResponseEntity.ok(category); - } - - @PostMapping("/deleteColumnById") - public ResponseEntity> deleteCategoryColumnById(@RequestParam("columnId") int columnId) { - boolean updated = addCategoryServices.removeColumnById(columnId); - - Map response = new HashMap<>(); - response.put("success", updated); - - return ResponseEntity.ok(response); - } - - @PostMapping("/updateCategoryColumns") - public ResponseEntity> updateCategoryColumnsById(@RequestBody Map requestData) { - try { - int categoryId = (int) requestData.get("categoryId"); - List> columns = (List>) requestData.get("columns"); - - - boolean allUpdated = true; - - for (Map column : columns) { - int columnId = (int) column.get("id"); - String columnName = (String) column.get("name"); - - - boolean updated = addCategoryServices.updateColumnById(categoryId,columnId, columnName); - - if (!updated) { - allUpdated = false; - } - } - - Map response = new HashMap<>(); - response.put("success", allUpdated); - return ResponseEntity.ok(response); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("error", "Invalid data format")); - } - } - - @PostMapping("/addNewColumns") - public ResponseEntity> addNewCategoryColumnsById(@RequestBody Map requestData) { - - try { - int categoryId = (int) requestData.get("categoryId"); - List> columns = (List>) requestData.get("columns"); - - - boolean allUpdated = true; - - for (Map column : columns) { - - String columnName = (String) column.get("name"); - - - boolean updated = addCategoryServices.addnewupdateColumn(categoryId, columnName); - - if (!updated) { - allUpdated = false; - } - } - - Map response = new HashMap<>(); - response.put("success", allUpdated); - return ResponseEntity.ok(response); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("error", "Invalid data format")); - } - } - - - - @PutMapping("/update/{categoryId}") - public ResponseEntity updateCategoryWithColumns( - @PathVariable("categoryId") int categoryId, - @RequestBody Map payload) { - - String categoryName = (String) payload.get("categoryName"); - List columns = (List) payload.get("columns"); - - try { - int rowsAffected = addCategoryServices.updateCategoryWithColumns(categoryId, categoryName, columns); - return rowsAffected > 0 - ? ResponseEntity.ok("Category and columns updated successfully") - : ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found or update failed"); - - } catch (IllegalArgumentException e) { - return ResponseEntity.badRequest().body("Validation Error: " + e.getMessage()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error updating category: " + e.getMessage()); - } - } - - -// // Endpoint to get a category by its ID -// @GetMapping("/showcategoryId") -// public ResponseEntity getCategoryById(@RequestParam("category_id") int categoryId) { -// Map category = addCategoryServices.showCategory(categoryId); -// -// if (category == null) { -// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found"); -// } -// -// return ResponseEntity.ok(category); -// } -// -// @PutMapping("/update/{categoryId}") -// public ResponseEntity updateCategoryWithColumns( -// @PathVariable("categoryId") int categoryId, -// @RequestBody Map payload) { -// -// String categoryName = (String) payload.get("categoryName"); -// List columns = (List) payload.get("columns"); -// -// try { -// int rowsAffected = addCategoryServices.updateCategoryWithColumns(categoryId, categoryName, columns); -// if (rowsAffected > 0) { -// return ResponseEntity.ok("Category and columns updated successfully"); -// } else { -// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found or update failed"); -// } -// } catch (IllegalArgumentException e) { -// return ResponseEntity.badRequest().body("Validation Error: " + e.getMessage()); -// } catch (Exception e) { -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) -// .body("Error updating category: " + e.getMessage()); -// } -// } - -// @GetMapping("/showcategoryId") -// public ResponseEntity showCategoryId(@RequestParam("category_id") int categoryId) { -// try { -// Map category = addCategoryServices.showCategory(categoryId); -// if (category != null && !category.isEmpty()) { -// return ResponseEntity.ok(category); -// } else { -// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found"); -// } -// } catch (Exception e) { -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) -// .body("Error retrieving category: " + e.getMessage()); -// } -// } - -// @PutMapping("/update/{categoryId}") -// public ResponseEntity updateCategory( -// @PathVariable("categoryId") int categoryId, -// @RequestParam String categoryName) { -// -// // Validate input -// if (categoryName == null || categoryName.trim().isEmpty()) { -// return ResponseEntity.badRequest().body("Category name cannot be empty"); -// } -// -// try { -// // Call the service method to update the category -// int rowsAffected = addCategoryServices.updateCategory(categoryId, categoryName); -// if (rowsAffected > 0) { -// return ResponseEntity.ok("Category updated successfully"); -// } else { -// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Category not found or update failed"); -// } -// } catch (Exception e) { -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) -// .body("Error updating category: " + e.getMessage()); -// } -// } - - - // Endpoint to delete a category by its ID - @DeleteMapping("/delete/{categoryId}") - public ResponseEntity deleteCategory( - @PathVariable("categoryId") int categoryId) { - - try { - // Call the service method to delete the category - addCategoryServices.deleteCategory(categoryId); - return ResponseEntity.ok("Category deleted successfully"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error deleting category: " + e.getMessage()); - } - } - - -//hari category api populate - - @GetMapping("/getcategory") - public List> getcategory(){ - return addCategoryServices.getcategory(); - } - - // Get category-specific columns based on category_id - @GetMapping("/getCategoryColumns") - public List> getCategoryColumns(@RequestParam int category_id) { - return addCategoryServices.getCategoryColumns(category_id); - } - - - @GetMapping("/getcampaignbycategory") - public List> getcampaignbycategory(@RequestParam int id) - { - return addCategoryServices.getcampaignbycategory(id); - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/MainController.java deleted file mode 100644 index 3e4be8d5..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/MainController.java +++ /dev/null @@ -1,219 +0,0 @@ - package in.gov.chennaicorporation.gccoffice.callcenter.controller; - - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -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.ResponseBody; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenter.service.AddcategoryServices; -import in.gov.chennaicorporation.gccoffice.callcenter.service.AgentsService; -import in.gov.chennaicorporation.gccoffice.callcenter.service.AttendanceService; -import in.gov.chennaicorporation.gccoffice.callcenter.service.AgentAssignService; -import in.gov.chennaicorporation.gccoffice.callcenter.service.CampaignService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - - -@RequestMapping("/gcc/callcenter") -@Controller("callCenterCampaignMainController") -public class MainController { - - - - @Autowired - private AgentAssignService campaignmaster; - - @Autowired - private CampaignService campaignService; - - @Autowired - private AddcategoryServices addCategoryServices; - - @Autowired - private AgentsService agentsService; - - @Autowired - private AttendanceService attendanceSerivce; - - private AppConfig appConfig; - private RestTemplate restTemplate; - - @Autowired - public MainController(AgentAssignService campaignmaster,AgentsService agentsService,CampaignService campaignService,AddcategoryServices addCategoryServices,RestTemplate restTemplate, AppConfig appConfig) - { - this.campaignmaster=campaignmaster; - this.campaignService=campaignService; - this.addCategoryServices=addCategoryServices; - this.agentsService=agentsService; - this.restTemplate = restTemplate; - this.appConfig = appConfig; - - } - - - @GetMapping("/admin/addcategory") - - public String addcategory(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - List> categories = addCategoryServices.getAllCategories(); - - //System.out.println(categories); - - model.addAttribute("categories", categories); - - return "modules/callcenter/addcategory"; - - } - - @GetMapping("/admin/createcampaign") - - public String createcampaign(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - /* - * List> campaigns = campaignService.getCampaignDetails(); - * - * - * System.out.println("campaignlist:"+campaigns); - * - * model.addAttribute("campaigns", campaigns); - */ - - return "modules/callcenter/createcampaign"; // Name of the Thymeleaf template (e.g., campaignList.html) - - } - - @GetMapping("/admin/campaignlist") - public String viewCampaignList(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - List> campaigns = campaignService.getDetailsForStart(); - - model.addAttribute("campaigns", campaigns); - - List> activeCampaigns =campaignService.getActiveCampaigns(); - model.addAttribute("activeCampaigns", activeCampaigns); - - return "modules/callcenter/campaignlist"; - } - - - @GetMapping("/agentscampaign") - public String targetPage(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - List> agentsCampaigns=agentsService.getAgentsALLCampaigns(userId); - - List> agentsCampaignsList=agentsService.getAgentsALLCampaignsList(userId); - - List> agentsCampaignsList1=agentsService.getAgentsALLCampaignsList1(userId); - - //List> CampActions=agentsService.getCallCategories(); - //model.addAttribute("CampActions", CampActions); - - model.addAttribute("agentsCampaignsList", agentsCampaignsList); - model.addAttribute("agentsCampaigns", agentsCampaigns); - model.addAttribute("agentsCampaignsList1", agentsCampaignsList1); - //System.out.println("Agents Campaigns List: " + agentsCampaignsList); - //System.out.println("Agents Campaigns : " + agentsCampaigns); - - return "modules/callcenter/agentscampaign"; - } - - - @GetMapping("/admin/campaignreport") - public String campaignreport(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/callcenter/campaignreport"; - } - - @GetMapping("/attendancereport") - public String AttendanceList( - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate, - Model model) { - List> attendanceData = Collections.emptyList(); - - if (fromDate != null && !fromDate.isEmpty() && toDate != null && !toDate.isEmpty()) { - String apiUrl = appConfig.attendanceReport + "/callcenter/api/attendance/getattendancereport?fromDate=" + fromDate + "&toDate=" + toDate; - - try { - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - String responseBody = responseEntity.getBody(); - - if (responseBody != null && !responseBody.isEmpty()) { - ObjectMapper objectMapper = new ObjectMapper(); - if (responseBody.trim().startsWith("{")) { - // Single object response - Map singleData = objectMapper.readValue(responseBody, new TypeReference<>() {}); - attendanceData = List.of(singleData); - } else { - // Array response - attendanceData = objectMapper.readValue(responseBody, new TypeReference<>() {}); - } - } - } catch (Exception e) { - System.err.println("Error fetching attendance data: " + e.getMessage()); - } - } - - model.addAttribute("attendanceData", attendanceData); - model.addAttribute("fromDate", fromDate); - model.addAttribute("toDate", toDate); - model.addAttribute("LoginUserId", LoginUserInfo.getLoginUserId()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - return "modules/callcenter/attendancereport"; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/WhatsappController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/WhatsappController.java deleted file mode 100644 index c4944855..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/WhatsappController.java +++ /dev/null @@ -1,26 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.callcenter.service.WhatsappMsgService; - -@RestController -@RequestMapping("/gcc/api/whatsapp") -public class WhatsappController { - - @Autowired - private WhatsappMsgService whatsappMsgService; - - @PostMapping("/send-whatsapp-message") - public ResponseEntity sendWhatsAppMessage(@RequestParam String msgUrl) { - String response = whatsappMsgService.sendMsg(msgUrl); - return ResponseEntity.ok(response); - } - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AddcategoryServices.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AddcategoryServices.java deleted file mode 100644 index 3271869f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AddcategoryServices.java +++ /dev/null @@ -1,303 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.sql.ResultSet; - -import java.sql.SQLException; -import java.util.Collections; -import java.util.List; -import java.util.Locale.Category; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import java.sql.PreparedStatement; -import java.sql.Statement; - - -@Service -public class AddcategoryServices { - -private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - -// public void saveCategoryDetails(Map categoryData) { -// String sql = "INSERT INTO category (category_name, isactive, isdelete, created_date) VALUES (?, 1, 0, CURRENT_TIMESTAMP)"; -// -// // Ensure that the key "categoryname" matches exactly what is being sent from the frontend -// String categoryName = (String) categoryData.get("categoryname"); -// -// // Check if categoryName is null or empty and handle it properly -// if (categoryName == null || categoryName.trim().isEmpty()) { -// throw new IllegalArgumentException("Category name cannot be null or empty"); -// } -// -// jdbcTemplate.update(sql, categoryName); -// } - - - @Transactional - public void saveCategoryDetails(Map categoryData) { - String categoryName = (String) categoryData.get("categoryname"); - List columns = (List) categoryData.get("columns"); - - if (categoryName == null || categoryName.trim().isEmpty()) { - throw new IllegalArgumentException("Category name cannot be null or empty"); - } - - if (columns == null || columns.isEmpty() || columns.contains("")) { - throw new IllegalArgumentException("At least one column name is required"); - } - - // Insert into category table and get the generated category_id - String categorySql = "INSERT INTO category (category_name, isactive, isdelete, created_date) VALUES (?, 1, 0, CURRENT_TIMESTAMP)"; - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(categorySql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, categoryName); - return ps; - }, keyHolder); - - Integer categoryId = keyHolder.getKey().intValue(); // Extract generated category_id - - // Insert columns into category_columns table - String columnSql = "INSERT INTO category_columns (category_id, column_name, isactive, isdelete, created_date) VALUES (?, ?, 1, 0, CURRENT_TIMESTAMP)"; - jdbcTemplate.batchUpdate(columnSql, columns, columns.size(), - (PreparedStatement ps, String column) -> { - ps.setInt(1, categoryId); - ps.setString(2, column); - }); - } - - - @Transactional - public List> getAllCategories() { - - String SqlQuery = "SELECT category_id,category_name FROM category where isactive=1 and isdelete=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - public Map showCategory(int categoryId) { - String categorySql = "SELECT category_id, category_name FROM category WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; - Map category; - try { - category = jdbcTemplate.queryForMap(categorySql, categoryId); - } catch (EmptyResultDataAccessException e) { - return Collections.emptyMap(); - } - - String columnsSql = "SELECT id,column_name FROM category_columns WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; - List> columns = jdbcTemplate.queryForList(columnsSql,categoryId); - category.put("columns", columns); - return category; - } - - @Transactional - public int updateCategoryWithColumns(int categoryId, String categoryName, List columns) { - if (categoryName == null || categoryName.trim().isEmpty()) { - throw new IllegalArgumentException("Category name cannot be empty"); - } - if (columns == null || columns.size() < 2 || columns.contains("")) { - throw new IllegalArgumentException("At least two column names are required"); - } - - String updateCategorySql = "UPDATE category SET category_name = ? WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; - int categoryUpdateCount = jdbcTemplate.update(updateCategorySql, categoryName, categoryId); - - if (categoryUpdateCount == 0) { - throw new IllegalArgumentException("Category not found or update failed."); - } - - String deleteColumnsSql = "DELETE FROM category_columns WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; - jdbcTemplate.update(deleteColumnsSql, categoryId); - - String insertColumnsSql = "INSERT INTO category_columns (category_id, column_name, isactive, isdelete, created_date) VALUES (?, ?, 1, 0, CURRENT_TIMESTAMP)"; - jdbcTemplate.batchUpdate(insertColumnsSql, columns, columns.size(), (PreparedStatement ps, String column) -> { - ps.setInt(1, categoryId); - ps.setString(2, column); - }); - - return categoryUpdateCount; - } - - -// @Transactional -// public int updateCategoryWithColumns(int categoryId, String categoryName, List columns) { -// if (categoryName == null || categoryName.trim().isEmpty()) { -// throw new IllegalArgumentException("Category name cannot be empty"); -// } -// if (columns == null || columns.isEmpty() || columns.contains("")) { -// throw new IllegalArgumentException("At least one column name is required"); -// } -// -// String updateCategorySql = "UPDATE category SET category_name = ? WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; -// int categoryUpdateCount = jdbcTemplate.update(updateCategorySql, categoryName, categoryId); -// -// if (categoryUpdateCount == 0) { -// throw new IllegalArgumentException("Category not found or update failed."); -// } -// -// String deleteColumnsSql = "DELETE FROM category_columns WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; -// jdbcTemplate.update(deleteColumnsSql, categoryId); -// -// String insertColumnsSql = "INSERT INTO category_columns (category_id, column_name, isactive, isdelete, created_date) VALUES (?, ?, 1, 0, CURRENT_TIMESTAMP)"; -// jdbcTemplate.batchUpdate(insertColumnsSql, columns, columns.size(), (PreparedStatement ps, String column) -> { -// ps.setInt(1, categoryId); -// ps.setString(2, column); -// }); -// -// return categoryUpdateCount; -// } - - - - -// // Method to show a category by its ID -// public Map showCategory(int categoryId) { -// // Fetch category details -// String categorySql = "SELECT category_id, category_name FROM category WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; -// Map category; -// try { -// category = jdbcTemplate.queryForMap(categorySql, categoryId); -// } catch (EmptyResultDataAccessException e) { -// return null; // If no category found -// } -// -// // Fetch category columns -// String columnsSql = "SELECT column_name FROM category_columns WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; -// List columns = jdbcTemplate.queryForList(columnsSql, String.class, categoryId); -// -// // Add columns to response -// category.put("columns", columns); -// return category; -// } -// -// - -// @Transactional -// public int updateCategoryWithColumns(int categoryId, String categoryName, List columns) { -// // Validate input -// if (categoryName == null || categoryName.trim().isEmpty()) { -// throw new IllegalArgumentException("Category name cannot be empty"); -// } -// if (columns == null || columns.isEmpty() || columns.contains("")) { -// throw new IllegalArgumentException("At least one column name is required"); -// } -// -// // Update category name -// String updateCategorySql = "UPDATE category SET category_name = ? WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; -// int categoryUpdateCount = jdbcTemplate.update(updateCategorySql, categoryName, categoryId); -// -// if (categoryUpdateCount == 0) { -// throw new IllegalArgumentException("Category not found or update failed."); -// } -// -// // Remove existing category columns before inserting new ones -// String deleteColumnsSql = "DELETE FROM category_columns WHERE category_id = ?"; -// jdbcTemplate.update(deleteColumnsSql, categoryId); -// -// // Insert updated columns -// String insertColumnsSql = "INSERT INTO category_columns (category_id, column_name, isactive, isdelete, created_date) VALUES (?, ?, 1, 0, CURRENT_TIMESTAMP)"; -// jdbcTemplate.batchUpdate(insertColumnsSql, columns, columns.size(), -// (PreparedStatement ps, String column) -> { -// ps.setInt(1, categoryId); -// ps.setString(2, column); -// }); -// -// return categoryUpdateCount; -// } - - -// // Method to update a category's name by its ID -// public int updateCategory(int categoryId, String categoryName) { -// String sql = "UPDATE category SET category_name = ? WHERE category_id = ? AND isactive = 1 AND isdelete = 0"; -// return jdbcTemplate.update(sql, categoryName, categoryId); -// } - - - - - // Method to delete a category by its name - public void deleteCategory(int categoryId) { - // String sql = "DELETE FROM category WHERE category_id = ?"; - - String sql = "UPDATE category SET isactive=0 , isdelete=1 WHERE category_id = ?"; - jdbcTemplate.update(sql, categoryId); - } - - - //hari populate category services - @Transactional - public List> getcategory() { - String sqlQuery = "SELECT category_id,category_name FROM category where isactive='1' and isdelete='0'"; - return jdbcTemplate.queryForList(sqlQuery); - } - - public List> getCategoryColumns(int categoryId) { - String sqlQuery = "SELECT column_name FROM category_columns WHERE category_id = ? AND isactive = 1"; - return jdbcTemplate.queryForList(sqlQuery, categoryId); - } - - // Fetch category with columns - public List> getCategoriesWithColumns() { - String sqlQuery = "SELECT c.category_id, c.category_name, cc.column " + - "FROM gcc_1913_campaign.category c " + - "INNER JOIN gcc_1913_campaign.category_columns cc ON c.category_id = cc.category_id " + - "WHERE c.isactive = 1 AND c.isdelete = 0 " + - "AND cc.isactive = 1 AND cc.isdelete = 0"; - return jdbcTemplate.queryForList(sqlQuery); - } - - @Transactional - - public List> getcampaignbycategory(int id) { - - String sqlQuery = "SELECT cr.campaign_id,cr.campaign_name FROM campaign_request cr JOIN category c ON cr.category_id=c.category_id where cr.category_id=? and cr.isactive='1'"; - - return jdbcTemplate.queryForList(sqlQuery,id); - - } - - - public boolean removeColumnById(int columnId) { - String sql = "UPDATE category_columns SET isactive = 0, isdelete = 1 WHERE id = ?"; - - int rowsAffected = jdbcTemplate.update(sql, columnId); - - return rowsAffected > 0; // Returns true if at least one row was updated, otherwise false - } - - public boolean updateColumnById(int categoryId,int columnId, String columnName) { - String sql = "UPDATE category_columns SET column_name = ? WHERE id = ? and category_id=?"; - int rowsAffected = jdbcTemplate.update(sql, columnName, columnId,categoryId); - return rowsAffected > 0; - } - - - public boolean addnewupdateColumn(int categoryId, String columnName) { - - //String sql = "UPDATE category_columns SET column_name = ? WHERE id = ? and category_id=?"; - String sql = "INSERT INTO category_columns (category_id, column_name) VALUES (?, ?)"; - - int rowsAffected = jdbcTemplate.update(sql, categoryId,columnName); - return rowsAffected > 0; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentAssignService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentAssignService.java deleted file mode 100644 index 10910af7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentAssignService.java +++ /dev/null @@ -1,214 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.util.ArrayList; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - - -@Service -public class AgentAssignService -{ - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public void setDataSource2(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - private JdbcTemplate jdbcTemplate2; - - - @Transactional - public List> getcategory() { - String sqlQuery = "SELECT category_id,category_name FROM gcc_1913_campaign.category where isactive='1' and isdelete='0'"; - return jdbcTemplate.queryForList(sqlQuery); - } - - @Transactional - public List> getcampaignbycategory(int id) { - String sqlQuery = "SELECT cr.campaign_id, cr.campaign_name " + - "FROM gcc_1913_campaign.campaign_request cr " + - "JOIN gcc_1913_campaign.category c ON cr.category_id = c.category_id " + - "WHERE cr.category_id = ? AND campaign_status='PENDING' " + - "AND cr.isactive = '1' "; - return jdbcTemplate.queryForList(sqlQuery,id); - } - - @Transactional - public List> getcampaignbyid(int id) { - String sqlQuery = "SELECT * FROM gcc_1913_campaign.campaign_request where isactive='1' and campaign_id=?"; - return jdbcTemplate.queryForList(sqlQuery,id); - } - - @Transactional - public List> getagentsfortask(int id) { - String sqlQuery = "SELECT al.agent_id,al.agent_name\r\n" - + "FROM gcc_1913_qaqc.agents_list al\r\n" - + "LEFT JOIN gcc_1913_campaign.agent_assign aa ON al.agent_id = aa.agent_id AND aa.isactive = '1' AND aa.campaign_id = ?\r\n" - + "WHERE aa.agent_id IS NULL AND al.calling_type='OUTBOUND'AND al.isactive='1' AND al.isdelete='0'"; - return jdbcTemplate.queryForList(sqlQuery,id); - } - - - @Transactional - public int addagentsfortask(int agent_id, int category_id, int campaign_id) { - String insertSql = "INSERT INTO gcc_1913_campaign.agent_assign (agent_id, category_id, campaign_id) VALUES (?, ?, ?)"; - int rowsInserted = jdbcTemplate.update(insertSql, agent_id, category_id, campaign_id); - - return rowsInserted; - } - - - @Transactional - public void addAgentsForCampaign(int selectedAgentId, int categoryId, int campaignId) { - String insertSql = "INSERT INTO gcc_1913_campaign.agent_assign (agent_id, category_id, campaign_id) VALUES (?, ?, ?)"; - - try { - - int rowsInserted = jdbcTemplate.update(insertSql, selectedAgentId, categoryId, campaignId); - - if (rowsInserted > 0) { - System.out.println("Successfully inserted agent ID in agent_assign== " + selectedAgentId + " into campaign ID " + campaignId); - } else { - System.out.println("No rows inserted for agent ID " + selectedAgentId); - } - - } catch (DataAccessException | NumberFormatException ex) { - System.err.println("Error inserting data: " + ex.getMessage()); - throw new RuntimeException("Failed to insert agents for campaign. Please try again.", ex); - } - } - - @Transactional - public void updateAgentForCampaign(int selectedAgentId, int categoryId, int campaignId,int DataId) { - String updateSql = "UPDATE gcc_1913_campaign.upload_data SET agent_id = ? WHERE campaign_id = ? AND category_id = ? AND data_id=?"; - - try { - - int rowsUpdated = jdbcTemplate.update(updateSql, selectedAgentId,campaignId,categoryId,DataId); - -/* if (rowsUpdated > 0) { - System.out.println("Successfully updated agent ID in upload_data== " + selectedAgentId + " for campaign ID " + campaignId); - } else { - System.out.println("No rows updated for agent ID " + selectedAgentId); - }*/ - - } catch (DataAccessException | NumberFormatException ex) { - System.err.println("Error updating data: " + ex.getMessage()); - throw new RuntimeException("Failed to update agents for campaign. Please try again.", ex); - } - } - - @Transactional - public List getDataIdForInitialAssign(int categoryId, int campaignId) { - - String sql = "SELECT data_id FROM gcc_1913_campaign.upload_data " - + "WHERE category_id = ? AND campaign_id = ? " - + "AND agent_id IS NULL AND is_processed = 0 ORDER BY data_id"; - - // Correctly specify the return type for jdbcTemplate.queryForList - return jdbcTemplate.queryForList(sql, Integer.class, categoryId, campaignId); - } - - - - - @Transactional - public List> checkcampaigninassignedtable(int id) - { - String sqlQuery = "SELECT al.agent_id,al.agent_name,aa.assigned_id\r\n" - + "FROM gcc_1913_qaqc.agents_list al\r\n" - + "JOIN gcc_1913_campaign.agent_assign aa ON al.agent_id = aa.agent_id\r\n" - + "JOIN gcc_1913_campaign.campaign_request c ON aa.campaign_id=c.campaign_id\r\n" - + "WHERE aa.campaign_id = ? AND aa.isactive = '1' AND al.calling_type='OUTBOUND'AND al.isactive='1' AND al.isdelete='0'"; - return jdbcTemplate.queryForList(sqlQuery,id); - } - - @Transactional - public int editagentsfortask(int assigned_id) { - String updateSql = "UPDATE gcc_1913_campaign.agent_assign SET isactive='0', isdelete='1',status='NOT_ASSIGNED' WHERE assigned_id=?"; - int rowsInserted = jdbcTemplate.update(updateSql,assigned_id); - - return rowsInserted; - } - - - - @Transactional - public List> getcampaignquestionbyid(int id) { - String sqlQuery = " SELECT " + - " cr.campaign_id, " + - " cr.campaign_name, " + - " cr.category_id, " + - " cr.start_date, " + - " cr.end_date, " + - " cr.no_of_agents, " + - " cr.calls_per_agent, " + - " cr.description, " + - " cr.created_date, " + - " cr.excel_url, " + - " cr.isactive, " + - " cr.campaign_status, " + - " cq.questions, " + - " cq.question_id, " + - " cq.answer_type_id, " + - " cat.type_name, " + - " ca.campaign_answer " + // Campaign Answer can be NULL - "FROM gcc_1913_campaign.campaign_request cr " + - "JOIN gcc_1913_campaign.campaign_questions cq " + - " ON cr.campaign_id = cq.campaign_id " + - "LEFT JOIN gcc_1913_campaign.campaign_answers ca " + // LEFT JOIN to include questions with no answers - " ON cq.question_id = ca.question_id " + - "JOIN gcc_1913_campaign.answer_type cat " + - " ON cat.answer_type_id = cq.answer_type_id " + - "WHERE cr.isactive = 1 AND cr.campaign_id = ?"; - - List> queryResult = jdbcTemplate.queryForList(sqlQuery, id); - - // Map to group answers by question_id - Map> groupedData = new LinkedHashMap(); - - for (Map row : queryResult) { - Integer questionId = (Integer) row.get("question_id"); - String campaignAnswer = (String) row.get("campaign_answer"); // Can be null - - // Check if this question_id already exists in the map - if (!groupedData.containsKey(questionId)) { - // Copy the row data (excluding campaign_answer) and initialize answers list - Map newRow = new LinkedHashMap<>(row); - newRow.remove("campaign_answer"); // Remove individual answer - newRow.put("campaign_answers", new ArrayList()); // Initialize answer list - - groupedData.put(questionId, newRow); - } - - // Only add answers if they are not null - if (campaignAnswer != null) { - ((List) groupedData.get(questionId).get("campaign_answers")).add(campaignAnswer); - } - } - - // Convert grouped data to a list - return new ArrayList<>(groupedData.values()); - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentsService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentsService.java deleted file mode 100644 index 068451b2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentsService.java +++ /dev/null @@ -1,665 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class AgentsService { - - private JdbcTemplate jdbcTemplate; - - - @Autowired - public void setDataSource(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public void setDataSource2(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - private JdbcTemplate jdbcTemplate2; - - - // Utility method to get cell value based on type - private String getCellValue(Cell cell) { - if (cell == null) { - return ""; - } - switch (cell.getCellType()) { - case STRING: - return cell.getStringCellValue(); - case NUMERIC: - // Check if the numeric cell contains a date - if (DateUtil.isCellDateFormatted(cell)) { - return new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue()); - } - return String.valueOf((long) cell.getNumericCellValue()); // Cast to long to avoid scientific notation - case BOOLEAN: - return String.valueOf(cell.getBooleanCellValue()); - case FORMULA: - return cell.getCellFormula(); - default: - return ""; - } - } - - // Parse integer values (for ID) - private Integer parseInteger(String value) { - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - return null; // return null if parsing fails - } - } - - // Parse long values (for Mobile number) - private Long parseLong(String value) { - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - return null; // return null if parsing fails - } - } - - // Example fetch method - public List> fetchDataFromExcel(int categoryId,Long campaignId) throws IOException { - String excelUrl = getExcelUrlByCampaignId(campaignId); - List>data=getExcelData(categoryId,campaignId, excelUrl); - return saveExcelData(data); - } - - public String getExcelUrlByCampaignId(Long campaignId) { - String sql = "SELECT excel_url\r\n" - + "FROM gcc_1913_campaign.campaign_request\r\n" - + "WHERE campaign_id = ?"; - return jdbcTemplate.queryForObject(sql, String.class, campaignId); - } - - public List> getExcelData(int categoryId,Long campaignId,String filePath) throws IOException { - List> data = new ArrayList<>(); - File file = new File(filePath); - - try (FileInputStream fis = new FileInputStream(file); - Workbook workbook = new XSSFWorkbook(fis)) { - - Sheet sheet = workbook.getSheetAt(0); - for (Row row : sheet) { - if (row.getRowNum() == 0) continue; // skip header row - - Map rowData = new HashMap<>(); - - // Add the campaign_id and category_id to each row - - rowData.put("category_id", categoryId); - - rowData.put("campaign_id", campaignId); - - // Convert ID to Integer - rowData.put("ID", getCellValue(row.getCell(0))); - - // Name remains String - rowData.put("Name", getCellValue(row.getCell(1))); - - // Address remains String - rowData.put("Address", getCellValue(row.getCell(2))); - - // Dues remains String (you can convert if necessary) - rowData.put("Balance amount", parseLong(getCellValue(row.getCell(3)))); - - // Convert Mobile number to Long - rowData.put("Mobile number", parseLong(getCellValue(row.getCell(4)))); - - rowData.put("Tiny url", getCellValue(row.getCell(5))); - - data.add(rowData); - } - } - return data; - } - - public List> saveExcelData(List> data) { - - // Prepare SQL query for inserting the specified columns - String sql = "INSERT INTO gcc_1913_campaign.upload_data (category_id, campaign_id, field_1, field_2, field_3, field_4, field_5,field_6) " + - "VALUES (?, ?, ?, ?, ?, ?, ?,?)"; - - // Loop through the data list and insert each row into the database - for (Map row : data) { - jdbcTemplate.update(sql, - row.get("category_id"), // Category ID - row.get("campaign_id"), // Campaign ID - row.get("ID"), // ID (String) - row.get("Name"), // Name (String) - row.get("Address"), // Address (String) - row.get("Balance amount"), // Dues if any (String) - row.get("Mobile number"), // Mobile number (Long) - row.get("Tiny url") - ); - } - - // Return the inserted data (if needed) - return data; // Optionally return the inserted data or change the return type as per your use case - } - - - - //For Assigned tasks -// @Transactional -// public List> getAgentsALLCampaigns(int agent_id) { -// String SqlQuery = "SELECT \r\n" -// + " c.category_name,\r\n" -// + " cr.campaign_name,\r\n" -// + " cr.calls_per_agent,\r\n" -// + " aa.campaign_id,\r\n" -// + " aa.agent_id,\r\n" -// + " (SELECT COUNT(data_id) \r\n" -// + " FROM gcc_1913_campaign.upload_data up \r\n" -// + " WHERE up.agent_id = aa.agent_id \r\n" -// + " AND up.campaign_id = cr.campaign_id\r\n" -// + " ) AS calls_assigned,\r\n" -// + " (SELECT COUNT(CASE WHEN up.field_14 IS NULL THEN 1 END) \r\n" -// + " FROM gcc_1913_campaign.upload_data up \r\n" -// + " WHERE up.agent_id = aa.agent_id \r\n" -// + " AND up.campaign_id = cr.campaign_id\r\n" -// + " ) AS pending_count,\r\n" -// + " (SELECT COUNT(CASE WHEN up.field_14 IS NOT NULL THEN 1 END) \r\n" -// + " FROM gcc_1913_campaign.upload_data up \r\n" -// + " WHERE up.agent_id = aa.agent_id \r\n" -// + " AND up.campaign_id = cr.campaign_id\r\n" -// + " ) AS complete_count,\r\n" -// + " (SELECT COUNT(CASE WHEN up.field_14 ='CALL_BACK_LATER' OR up.field_14 = 'UNATTENDED' THEN 1 END) \r\n" -// + " FROM gcc_1913_campaign.upload_data up \r\n" -// + " WHERE up.agent_id = aa.agent_id \r\n" -// + " AND up.campaign_id = cr.campaign_id\r\n" -// + " ) AS followup_count\r\n" -// + " \r\n" -// + "FROM \r\n" -// + " gcc_1913_campaign.agent_assign aa\r\n" -// + "JOIN \r\n" -// + " gcc_1913_qaqc.agents_list al ON aa.agent_id = al.agent_id\r\n" -// + "JOIN \r\n" -// + " gcc_1913_campaign.campaign_request cr ON cr.campaign_id = aa.campaign_id\r\n" -// + "JOIN \r\n" -// + " gcc_1913_campaign.category c ON cr.category_id = c.category_id\r\n" -// + "WHERE \r\n" -// + " aa.agent_id = ? \r\n" -// + " AND aa.isactive = '1'\r\n" -// + " AND cr.isactive = '0'"; -// -// return jdbcTemplate.queryForList(SqlQuery,agent_id); -// } - - - - - - @Transactional - public List> getdataByIds(List ids) { - // Construct the SQL query with placeholders for the number of IDs - String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); - String SqlQuery = "SELECT data_id, field_1 as id, field_2 as name, field_3 as address, field_4 as dues, field_5 as cellnumber,field_6 as viewdetails,field_14 as call_status,field_15 as remarks " + - "FROM gcc_1913_campaign.upload_data " + - "WHERE data_id IN (" + inSql + ")"; - - // Convert the list of ids to an Object array - return jdbcTemplate.queryForList(SqlQuery, ids.toArray()); - } - - @Transactional - public void saveCallLogs(String call_status,String remarks ,int data_id,int agent_id) - { - String SqlQuery = "UPDATE gcc_1913_campaign.upload_data SET call_status = ?, remarks=?, updated_date = NOW() ,updated_agent_id=?, is_processed=1 WHERE (data_id = ? )"; - - jdbcTemplate.update(SqlQuery,call_status, remarks,agent_id,data_id); - } - - @Transactional - public int saveInLogsTable(int campaignId, int agentId, int dataId, String call_status,String remarks) { - String sqlQuery = "INSERT INTO gcc_1913_campaign.call_logs (campaign_id,agent_id,data_id,call_status,remarks) VALUES (?, ?, ?,?,?)"; - int rowsAffected = 0; - try { - rowsAffected = jdbcTemplate.update(sqlQuery, campaignId, agentId, dataId,call_status,remarks); - //System.out.println("Inserted into call_logs successfully. Rows affected: " + rowsAffected); - } catch (Exception e) { - System.err.println("Error inserting into call_logs: " + e.getMessage()); - // Log the exception or rethrow it based on your error-handling strategy - } - return rowsAffected; - } - - @Transactional - public List> getPendingDataByIds(List ids) { - // Construct the SQL query with placeholders for the number of IDs - String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); - String SqlQuery = "SELECT data_id, field_1 as id, field_2 as name, field_3 as address, field_4 as dues, field_5 as cellnumber,field_6 as viewdetails,field_14 as call_status,field_15 as remarks " + - "FROM gcc_1913_campaign.upload_data " + - "WHERE data_id IN (" + inSql + ") " + - "AND field_14 IN ('UNATTENDED', 'CALL_BACK_LATER')"; - - // Convert the list of ids to an Object array - return jdbcTemplate.queryForList(SqlQuery, ids.toArray()); - } - - @Transactional - public List> getAgentsNameById(List agentIds) - { - String inSql = String.join(",", Collections.nCopies(agentIds.size(), "?")); - String SqlQuery ="select agent_name,agent_id from gcc_1913_qaqc.agents_list where agent_id IN (" + inSql + ")"; - - return jdbcTemplate.queryForList(SqlQuery, agentIds.toArray()); - - } - //agents performance - @Transactional - public List> getDataDetailsById(List dataIds) - { - if (dataIds.isEmpty()) { - // Handle the case where dataIds is empty to avoid SQL syntax error. - throw new IllegalArgumentException("The dataIds list is empty, cannot execute query."); - } - - String inSql = String.join(",", Collections.nCopies(dataIds.size(), "?")); - String SqlQuery ="SELECT\r\n" - + " COUNT(*) AS Assigned_count,\r\n" - + " COUNT(CASE WHEN field_14 IS NOT NULL THEN 1 END) AS Complete_count,\r\n" - + " COUNT(CASE WHEN field_14 IS NULL THEN 1 END) AS Pending_count ,\r\n" - + " COUNT(CASE WHEN field_14 = 'INFORMATION_GIVEN' THEN 1 END) AS Information_Given_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'UNATTENDED' THEN 1 END) AS Unattended_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'CALL_BACK_LATER' THEN 1 END) AS Call_back_later_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'SWITCH_OFF' THEN 1 END) AS Switch_off_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'WRONG_NUMBER' THEN 1 END) AS Wrong_number_count,\r\n" - + " CASE WHEN COUNT(*) = 0 THEN 0 ELSE ROUND((COUNT(CASE WHEN field_14 IS NOT NULL THEN 1 END) * 100.0 / COUNT(*)), 0)END AS Percentage\r\n" - + "FROM gcc_1913_campaign.upload_data\r\n" - + "WHERE data_id IN (" + inSql + ")"; - - - - List> results = jdbcTemplate.queryForList(SqlQuery, dataIds.toArray()); - return results; - } - - @Transactional - public List> getCompletedDataDetailsById(List CdataIds) - { - if (CdataIds.isEmpty()) { - // Handle the case where dataIds is empty to avoid SQL syntax error. - throw new IllegalArgumentException("The CdataIds list is empty, cannot execute query."); - } - - String inSql = String.join(",", Collections.nCopies(CdataIds.size(), "?")); - String SqlQuery ="SELECT\r\n" - + " data_id,\r\n" // Add data_id to the result - + " COUNT(*) AS Assigned_count,\r\n" - + " COUNT(CASE WHEN field_14 IS NOT NULL THEN 1 END) AS Complete_count,\r\n" - + " COUNT(CASE WHEN field_14 IS NULL THEN 1 END) AS Pending_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'INFORMATION_GIVEN' THEN 1 END) AS Information_Given_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'UNATTENDED' THEN 1 END) AS Unattended_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'CALL_BACK_LATER' THEN 1 END) AS Call_back_later_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'SWITCH_OFF' THEN 1 END) AS Switch_off_count,\r\n" - + " COUNT(CASE WHEN field_14 = 'WRONG_NUMBER' THEN 1 END) AS Wrong_number_count,\r\n" - + " CASE WHEN COUNT(*) = 0 THEN 0 ELSE ROUND((COUNT(CASE WHEN field_14 IS NOT NULL THEN 1 END) * 100.0 / COUNT(*)), 0) END AS Percentage\r\n" - + "FROM gcc_1913_campaign.upload_data\r\n" - + "WHERE data_id IN (" + inSql + ")\r\n" - + "GROUP BY data_id"; // Group by data_id - - return jdbcTemplate.queryForList(SqlQuery, CdataIds.toArray()); - } - - @Transactional - public List> getCompletedDataById(List completedDataIds) - { - if (completedDataIds.isEmpty()) { - // Handle the case where dataIds is empty to avoid SQL syntax error. - throw new IllegalArgumentException("The completedDataIds list is empty, cannot execute query."); - } - - String inSql = String.join(",", Collections.nCopies(completedDataIds.size(), "?")); - String SqlQuery = "SELECT field_1 as id, field_2 as name, field_3 as address, " + - "field_5 as cellnumber, field_14 as call_status, updated_date as updated_date,field_15 as remarks, " + - "(SELECT COUNT(data_id) FROM call_logs WHERE data_id = upload_data.data_id) as call_count " + - "FROM gcc_1913_campaign.upload_data " + - "WHERE data_id IN (" + inSql + ")"; - - - return jdbcTemplate.queryForList(SqlQuery, completedDataIds.toArray()); - - } - - - @Transactional - public void addAgentsForCampaign(int selectedAgentId, int categoryId, int campaignId) { - String checkSql = "SELECT COUNT(*) FROM gcc_1913_campaign.agent_assign " - + "WHERE agent_id = ? AND category_id = ? AND campaign_id = ?"; - - String insertSql = "INSERT INTO gcc_1913_campaign.agent_assign (agent_id, category_id, campaign_id) VALUES (?, ?, ?)"; - - try { - // Check if the record already exists - int count = jdbcTemplate.queryForObject(checkSql, Integer.class, selectedAgentId, categoryId, campaignId); - - if (count == 0) { - // Insert only if no existing record found - int rowsInserted = jdbcTemplate.update(insertSql, selectedAgentId, categoryId, campaignId); - - if (rowsInserted > 0) { - System.out.println("Successfully inserted agent ID " + selectedAgentId + " into campaign ID " + campaignId); - } else { - System.out.println("No rows inserted for agent ID " + selectedAgentId); - } - } else { - System.out.println("Agent ID " + selectedAgentId + " is already assigned to campaign ID " + campaignId); - } - - } catch (DataAccessException | NumberFormatException ex) { - System.err.println("Error inserting data: " + ex.getMessage()); - throw new RuntimeException("Failed to insert agents for campaign. Please try again.", ex); - } - } - - - @Transactional - public void updateAgentForCampaign(int selectedAgentId, int categoryId, int campaignId,int DataId) { - String updateSql = "UPDATE gcc_1913_campaign.upload_data SET agent_id = ? WHERE campaign_id = ? AND category_id = ? AND data_id=?"; - - try { - - int rowsUpdated = jdbcTemplate.update(updateSql, selectedAgentId,campaignId,categoryId,DataId); - -/* if (rowsUpdated > 0) { - System.out.println("Successfully updated agent ID in upload_data== " + selectedAgentId + " for campaign ID " + campaignId); - } else { - System.out.println("No rows updated for agent ID " + selectedAgentId); - }*/ - - } catch (DataAccessException | NumberFormatException ex) { - System.err.println("Error updating data: " + ex.getMessage()); - throw new RuntimeException("Failed to update agents for campaign. Please try again.", ex); - } - } - - @Transactional - public List getDataIdForFurtherAssign(int categoryId, int campaignId) { - - String sql = "SELECT data_id FROM gcc_1913_campaign.upload_data " - + "WHERE category_id = ? " - + "AND campaign_id = ? " - + "AND is_processed = 0 " - + "ORDER BY data_id"; - - return jdbcTemplate.queryForList(sql, Integer.class, categoryId, campaignId); - } - - @Transactional - public void resetAgentAssignmentForNextDay(int categoryId, int campaignId) { - String sql = "UPDATE gcc_1913_campaign.upload_data " - + "SET agent_id = NULL, " - + " call_status = NULL, " - + " remarks = NULL, " - + " updated_agent_id = NULL, " - + " updated_date = NULL, " - + " is_processed = 0 " - + "WHERE category_id = ? " - + " AND campaign_id = ? " - + " AND call_status IN ('CALL BACK LATER', 'UNATTENDED')"; - - jdbcTemplate.update(sql, categoryId, campaignId); - - } - - - - //////////////////////Ajith code/////////////////// - - @Transactional - public List> getFilteredFields(int categoryId, int agentId, int dataId) { - List> resultList = new ArrayList<>(); - - // Fetch ordered field column names - String fetchColumnsSQL = "SELECT COLUMN_NAME " + - "FROM INFORMATION_SCHEMA.COLUMNS " + - "WHERE TABLE_SCHEMA = 'gcc_1913_campaign' " + - "AND TABLE_NAME = 'upload_data' " + - "AND COLUMN_NAME LIKE 'field_%' " + - "ORDER BY CAST(SUBSTRING(COLUMN_NAME, 7) AS UNSIGNED)"; - - List fieldColumns = jdbcTemplate.queryForList(fetchColumnsSQL, String.class); - - if (fieldColumns.isEmpty()) { - throw new RuntimeException("No matching columns found"); - } - - // Fetch ordered fields data - String query1 = "SELECT " + String.join(", ", fieldColumns) + " FROM gcc_1913_campaign.upload_data WHERE data_id = ?"; - List> orderedFieldsList = jdbcTemplate.queryForList(query1, dataId); - - if (orderedFieldsList.isEmpty()) { - throw new RuntimeException("No data found for data_id: " + dataId); - } - - Map orderedFields = orderedFieldsList.get(0); - - // Fetch category columns - String query2 = "SELECT column_name FROM gcc_1913_campaign.category_columns WHERE category_id = ? and isactive=1 "; - List categoryColumns = new ArrayList<>(jdbcTemplate.queryForList(query2, String.class, categoryId)); - //System.out.println("service===="+categoryColumns); - - if (categoryColumns.isEmpty()) { - throw new RuntimeException("No category columns found for category_id: " + categoryId); - } - - int categoryCount = categoryColumns.size(); - - // Collect first 'categoryCount' non-null values from orderedFields - List nonNullValues = new ArrayList<>(); - for (String field : fieldColumns) { - Object value = orderedFields.get(field); - if (value != null) { - nonNullValues.add(value); - if (nonNullValues.size() == categoryCount) { - break; // Stop after collecting required count - } - } - } - - if (nonNullValues.size() < categoryCount) { - throw new RuntimeException("Not enough non-null values to match category columns"); - } - - // Map category columns to non-null ordered field values - Map finalMapping = new HashMap<>(); - for (int i = 0; i < categoryCount; i++) { - finalMapping.put(categoryColumns.get(i), nonNullValues.get(i)); - } - - resultList.add(finalMapping); - return resultList; - } - - - @Transactional - public List> getCampaignQuestions(int categoryId, int campaignId) { - // Fetch questions along with answer type -// String questionQuery = "SELECT cq.*, at.type_name " + -// "FROM gcc_1913_campaign.campaign_questions cq " + -// "JOIN gcc_1913_campaign.answer_type at " + -// "ON cq.answer_type_id = at.answer_type_id " + -// -// "WHERE cq.category_id = ? AND cq.campaign_id = ? "; - - String questionQuery="SELECT cq.questions AS questions, \r\n" - + " MIN(cq.question_id) AS question_id, \r\n" - + " MIN(cq.category_id) AS category_id, \r\n" - + " MIN(cq.campaign_id) AS campaign_id, \r\n" - + " MIN(cq.answer_type_id) AS answer_type_id, \r\n" - + " MIN(cat.type_name) AS type_name \r\n" - + "FROM gcc_1913_campaign.campaign_questions cq \r\n" - + "JOIN gcc_1913_campaign.answer_type cat \r\n" - + " ON cq.answer_type_id = cat.answer_type_id \r\n" - + "WHERE cq.category_id = ? \r\n" - + "AND cq.campaign_id = ? \r\n" - + "AND cq.isactive = 1\r\n" - + "GROUP BY cq.questions\r\n" - + "ORDER BY MIN(cq.question_id)"; - - List> questions = jdbcTemplate.queryForList(questionQuery, categoryId, campaignId); - - // Iterate over each question and fetch answers - for (Map question : questions) { - int questionId = (int) question.get("question_id"); - -// String answerQuery = "SELECT campaign_answer FROM gcc_1913_campaign.campaign_answers " + -// "WHERE question_id = ?"; - - String answerQuery="SELECT distinct(question_id) as qid, campaign_answer, created_date FROM gcc_1913_campaign.campaign_answers\r\n" - + "WHERE question_id = ?"; - - List> answers = jdbcTemplate.queryForList(answerQuery, questionId); -/* - // Extract answer values and add to the question map - List answerList = answers.stream() - .map(a -> (String) a.get("campaign_answer")) - .collect(Collectors.toList()); -*/ - List answerList = new ArrayList(); - - for (Map a : answers) { - Object ansObj = a.get("campaign_answer"); - if (ansObj != null) { - answerList.add(ansObj.toString()); - } - } - - question.put("answers", answerList); - } - - return questions; - } - - @Transactional - public List> FetchAnswer(int campaignId,int agentId,int questionId,int dataId) { - String sqlQuery = "SELECT distinct(campaign_answer) FROM gcc_1913_campaign.questions_answers where campaign_id=? and agent_id=? and question_id=? and data_id=?; "; - //System.out.println("dropdown l"); - return jdbcTemplate.queryForList(sqlQuery,campaignId,agentId,questionId,dataId); - } - - @Transactional - public void saveAnswers(List> answers) { - String sql = "INSERT INTO gcc_1913_campaign.questions_answers " + - "(campaign_id, data_id, agent_id, question_id, campaign_answer, created_date) " + - "VALUES (?, ?, ?, ?, ?, NOW())"; - - for (Map answer : answers) { - jdbcTemplate.update(sql, - answer.get("campaign_id"), - answer.get("data_id"), - answer.get("agent_id"), - answer.get("question_id"), - answer.get("campaign_answer") - ); - } - } - - @Transactional - public List> getCallStatus() { - String sqlQuery = "SELECT * FROM gcc_1913_campaign.calls_status "; - //System.out.println("dropdown l"); - return jdbcTemplate.queryForList(sqlQuery); - } - - @Transactional - public List> checkCounts(int campaignId, int dataId) { - // Query to get the count of answered questions for a given dataId - String answersCountQuery = "SELECT COUNT(distinct(question_id)) AS answersCount FROM gcc_1913_campaign.questions_answers WHERE data_id = ?"; - - // Query to get the count of required questions for a given campaignId - String questionsCountQuery = "SELECT COUNT(distinct(questions)) AS questionsCount FROM gcc_1913_campaign.campaign_questions WHERE campaign_id = ?"; - - // Execute queries - int answersCount = jdbcTemplate.queryForObject(answersCountQuery, Integer.class, dataId); - int questionsCount = jdbcTemplate.queryForObject(questionsCountQuery, Integer.class, campaignId); - - // Construct response as a list of maps - return List.of(Map.of( - "answersCount", answersCount, - "questionsCount", questionsCount - )); - } - - @Transactional - public List> getAgentsALLCampaignsList(int agent_id) { - String SqlQuery = "SELECT * FROM gcc_1913_campaign.upload_data ud inner join gcc_1913_campaign.campaign_request cr on ud.campaign_id=cr.campaign_id where cr.campaign_status='ONGOING'"+ - " and ud.agent_id = ? and ud.is_processed=0 "; - //System.out.println("text"); - return jdbcTemplate.queryForList(SqlQuery,agent_id); - } - - @Transactional - public List> getAgentsALLCampaignsList1(int agent_id) { - String SqlQuery = "SELECT * FROM gcc_1913_campaign.upload_data ud inner join gcc_1913_campaign.campaign_request cr on ud.campaign_id=cr.campaign_id where cr.campaign_status='ONGOING'"+ - " and ud.agent_id = ? and ud.is_processed=1"; - // System.out.println("text"); - return jdbcTemplate.queryForList(SqlQuery,agent_id); - } - - - - @Transactional - public List> getAgentsALLCampaigns(int agent_id) { - String SqlQuery = "SELECT c.category_name,cr.*,\r\n" - + "(SELECT COUNT(data_id)\r\n" - + "FROM gcc_1913_campaign.upload_data up\r\n" - + "WHERE up.agent_id = aa.agent_id \r\n" - + "AND up.campaign_id = cr.campaign_id\r\n" - + ") AS calls_assigned,\r\n" - + "(SELECT COUNT(CASE WHEN up.call_status IS NOT NULL THEN 1 END) \r\n" - + "FROM gcc_1913_campaign.upload_data up \r\n" - + "WHERE up.agent_id = aa.agent_id \r\n" - + "AND up.campaign_id = cr.campaign_id\r\n" - + ") AS complete_count,\r\n" - + "(SELECT COUNT(CASE WHEN up.call_status IS NULL THEN 1 END) \r\n" - + "FROM gcc_1913_campaign.upload_data up \r\n" - + "WHERE up.agent_id = aa.agent_id \r\n" - + "AND up.campaign_id = cr.campaign_id\r\n" - + ") AS pending_count\r\n" - + "FROM gcc_1913_campaign.agent_assign aa\r\n" - + "JOIN gcc_1913_campaign.campaign_request cr ON cr.campaign_id=aa.campaign_id\r\n" - + "JOIN gcc_1913_campaign.category c ON c.category_id=cr.category_id\r\n" - + "WHERE cr.campaign_status='ONGOING' AND aa.isactive=1 AND cr.isactive=1 AND aa.agent_id=?"; - - return jdbcTemplate.queryForList(SqlQuery,agent_id); - } - -// public List> getCallCategories() -// { -// String query = "SELECT id,call_status FROM gcc_1913_campaign.calls_status WHERE isactive=1 AND isdelete=0"; -// return jdbcTemplate.queryForList(query); -// } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AttendanceService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AttendanceService.java deleted file mode 100644 index 91de8899..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AttendanceService.java +++ /dev/null @@ -1,116 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class AttendanceService { - - -// private JdbcTemplate jdbcTemplate; -// -// -// @Autowired -// public void setDataSource(@Qualifier("BiometricDataSource") DataSource dataSource) { -// this.jdbcTemplate = new JdbcTemplate(dataSource); -// } -// -// -// public List> getAttendanceReport(String fromDate, String toDate) { -// String reportQuery; -// -// if (fromDate != null && toDate != null) { -// // Query with date filter if dates are provided -// reportQuery = "SELECT d.zone, d.division, b.user_id, b.user_name, f.departmentname, e.designation, " + -// "c.device_name, CAST(a.officepunch AS DATE) AS punch_date, MIN(a.OFFICEPUNCH) AS PUNCHIN, " + -// "CASE WHEN MAX(a.OFFICEPUNCH) = MIN(a.OFFICEPUNCH) THEN NULL ELSE MAX(a.OFFICEPUNCH) END AS PUNCHOUT " + -// "FROM machinerawpunch a, tbl_realtime_userinfo b, tbl_fkdevice_status c, zone_div_mast d, " + -// "tblemployee e, tbldepartment f " + -// "WHERE a.paycode = b.user_id AND a.deviceid = c.device_id AND c.device_name = d.devname " + -// "AND a.paycode = e.paycode AND e.departmentcode = f.departmentcode " + -// "AND CAST(a.officepunch AS DATE) BETWEEN ? AND ? " + -// "AND a.paycode LIKE '%19130%' " + -// "GROUP BY d.zone, d.division, b.user_id, b.user_name, f.departmentname, e.designation, " + -// "c.device_name, CAST(a.officepunch AS DATE) " + -// "ORDER BY d.zone, d.division, b.user_id, CAST(a.officepunch AS DATE)"; -// -// // Execute query with date parameters -// return jdbcTemplate.queryForList(reportQuery, fromDate, toDate); -// -// } else { -// // Query without date filter -// reportQuery = "SELECT d.zone, d.division, b.user_id, b.user_name, f.departmentname, e.designation, " + -// "c.device_name, CAST(a.officepunch AS DATE) AS punch_date, MIN(a.OFFICEPUNCH) AS PUNCHIN, " + -// "CASE WHEN MAX(a.OFFICEPUNCH) = MIN(a.OFFICEPUNCH) THEN NULL ELSE MAX(a.OFFICEPUNCH) END AS PUNCHOUT " + -// "FROM machinerawpunch a, tbl_realtime_userinfo b, tbl_fkdevice_status c, zone_div_mast d, " + -// "tblemployee e, tbldepartment f " + -// "WHERE a.paycode = b.user_id AND a.deviceid = c.device_id AND c.device_name = d.devname " + -// "AND a.paycode = e.paycode AND e.departmentcode = f.departmentcode " + -// "AND a.paycode LIKE '%19130%' " + -// "GROUP BY d.zone, d.division, b.user_id, b.user_name, f.departmentname, e.designation, " + -// "c.device_name, CAST(a.officepunch AS DATE) " + -// "ORDER BY d.zone, d.division, b.user_id, CAST(a.officepunch AS DATE)"; -// -// // Execute query without date parameters -// return jdbcTemplate.queryForList(reportQuery); -// } -// } -// -// -// -//// public List> getAttendanceReport(String fromDate, String toDate) { -//// System.out.println("Service Layer: Generating attendance report"); -//// -//// String reportQuery = "SELECT d.zone, d.division, b.user_id, b.user_name, f.departmentname, e.designation, c.device_name, " + -//// "CAST(a.officepunch AS DATE) AS punch_date, MIN(a.OFFICEPUNCH) AS PUNCHIN, " + -//// "CASE WHEN MAX(a.OFFICEPUNCH) = MIN(a.OFFICEPUNCH) THEN NULL ELSE MAX(a.OFFICEPUNCH) END AS PUNCHOUT " + -//// "FROM machinerawpunch a, tbl_realtime_userinfo b, tbl_fkdevice_status c, zone_div_mast d, " + -//// "tblemployee e, tbldepartment f " + -//// "WHERE a.paycode = b.user_id AND a.deviceid = c.device_id AND c.device_name = d.devname " + -//// "AND a.paycode = e.paycode AND e.departmentcode = f.departmentcode "; -//// -//// // Dynamic date filter -//// if (fromDate != null && toDate != null) { -//// reportQuery += "AND CAST(a.officepunch AS DATE) BETWEEN ? AND ? "; -//// } else if (fromDate != null) { -//// reportQuery += "AND CAST(a.officepunch AS DATE) = ? "; -//// } else { -//// throw new IllegalArgumentException("fromDate or toDate must be provided"); -//// } -//// -//// reportQuery += "AND a.paycode LIKE '%19130%' " + -//// "GROUP BY d.zone, d.division, b.user_id, b.user_name, f.departmentname, e.designation, c.device_name, " + -//// "CAST(a.officepunch AS DATE) " + -//// "ORDER BY d.zone, d.division, b.user_id, CAST(a.officepunch AS DATE)"; -//// -//// // Execute query based on dates -//// if (fromDate != null && toDate != null) { -//// return jdbcTemplate.queryForList(reportQuery, fromDate, toDate); -//// } else { -//// return jdbcTemplate.queryForList(reportQuery, fromDate); -//// } -//// } -// -//// public List> getAttendanceReport() { -//// System.out.println("check 2"); -//// String reportQuery ="SELECT d.zone,d.division,b.user_id,b.user_name,f.departmentname,e.designation,c.device_name,CAST(a.officepunch AS DATE) as punch_date,MIN(a.OFFICEPUNCH) AS PUNCHIN,\r\n" -//// + "CASE WHEN MAX(a.OFFICEPUNCH) = MIN(a.OFFICEPUNCH) THEN NULL ELSE MAX(a.OFFICEPUNCH) END AS PUNCHOUT FROM machinerawpunch a,tbl_realtime_userinfo b,tbl_fkdevice_status c,\r\n" -//// + "zone_div_mast d,tblemployee e,tbldepartment f WHERE a.paycode = b.user_id AND a.deviceid = c.device_id AND c.device_name = d.devname AND a.paycode = e.paycode AND \r\n" -//// + "e.departmentcode = f.departmentcode AND CAST(officepunch AS DATE) BETWEEN '2024-10-01' AND '2024-10-10'\r\n" -//// + "AND a.paycode LIKE '%19130%' \r\n" -//// + "GROUP BY d.zone,d.division,b.user_id,b.user_name,f.departmentname,e.designation,c.device_name,CAST(a.officepunch AS DATE)\r\n" -//// + "ORDER BY d.zone,d.division,b.user_id,CAST(a.officepunch AS DATE)"; -//// System.out.println("check 3"); -//// List> reports = jdbcTemplate.queryForList(reportQuery); -//// System.out.println("check 4"); -//// return reports; -//// } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignDropdownApiService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignDropdownApiService.java deleted file mode 100644 index 7b8c7b28..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignDropdownApiService.java +++ /dev/null @@ -1,29 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class CampaignDropdownApiService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> getAnswerTypes(){ - String sql = "SELECT answer_type_id,type_name FROM answer_type"; - return jdbcTemplate.queryForList(sql); - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignReportService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignReportService.java deleted file mode 100644 index c257d659..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignReportService.java +++ /dev/null @@ -1,533 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class CampaignReportService { - - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public void setDataSource2(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - public List> getCampaignData(String startDate, String endDate) { - StringBuilder query = new StringBuilder( - "SELECT " + - " cr.campaign_id, " + - " cr.category_id, " + - " cr.campaign_name, " + - " cc.category_name, " + - " cr.start_date, " + - " cr.end_date, " + - " COUNT(ud.campaign_id) AS total_count, " + - " COUNT(ud.agent_id) AS assigned_count, " + - " COUNT(ud.campaign_id) - COUNT(ud.agent_id) AS not_assigned_count, " + - " COUNT(CASE WHEN ud.call_status = 'INFORMATION GIVEN' THEN 1 ELSE NULL END) AS informationgiven_count, " + - " COUNT(CASE WHEN ud.call_status = 'CALL BACK LATER' THEN 1 ELSE NULL END) AS callback_count, " + - " COUNT(CASE WHEN ud.call_status = 'UNATTENDED' THEN 1 ELSE NULL END) AS unattended_count, " + - " COUNT(CASE WHEN ud.call_status = 'SWITCH OFF' THEN 1 ELSE NULL END) AS switchoff_count, " + - " COUNT(CASE WHEN ud.call_status = 'WRONG NUMBER' THEN 1 ELSE NULL END) AS wrongnumber_count " + - "FROM gcc_1913_campaign.campaign_request cr " + - "JOIN gcc_1913_campaign.upload_data ud ON cr.campaign_id = ud.campaign_id " + - "JOIN gcc_1913_campaign.category cc ON cr.category_id = cc.category_id " + - "WHERE cr.campaign_status IN ('ONGOING', 'CLOSED') " + - "AND ud.agent_id IS NOT NULL " - ); - - // Apply date filter dynamically if dates are provided - if (startDate != null && endDate != null) { - query.append("AND DATE(cr.created_date) BETWEEN ? AND ? "); - } - - query.append("GROUP BY cr.campaign_id "); - query.append("ORDER BY cr.campaign_id DESC"); - - // Execute query with or without parameters - if (startDate != null && endDate != null) { - return jdbcTemplate.queryForList(query.toString(), startDate, endDate); - } else { - return jdbcTemplate.queryForList(query.toString()); - } - } - - public List> getAgentwiseData(String campaignId) { - String query = "SELECT aa.agent_id, al.agent_name, \r\n" - + " COUNT(ud.agent_id) AS assigned_count, \r\n" - + " COUNT(CASE WHEN ud.is_processed = 1 THEN 1 ELSE NULL END) AS completed_count, \r\n" - + " COUNT(ud.agent_id) - COUNT(CASE WHEN ud.is_processed = 1 THEN 1 ELSE NULL END) AS pending_count, \r\n" - + " COUNT(CASE WHEN ud.call_status = 'INFORMATION GIVEN' THEN 1 ELSE NULL END) AS informationgiven_count, \r\n" - + " COUNT(CASE WHEN ud.call_status = 'CALL BACK LATER' THEN 1 ELSE NULL END) AS callback_count, \r\n" - + " COUNT(CASE WHEN ud.call_status = 'UNATTENDED' THEN 1 ELSE NULL END) AS unattended_count, \r\n" - + " COUNT(CASE WHEN ud.call_status = 'SWITCH OFF' THEN 1 ELSE NULL END) AS switchoff_count, \r\n" - + " COUNT(CASE WHEN ud.call_status = 'WRONG NUMBER' THEN 1 ELSE NULL END) AS wrongnumber_count, \r\n" - + " CASE \r\n" - + " WHEN COUNT(ud.agent_id) = 0 THEN 0 \r\n" - + " ELSE FLOOR((COUNT(CASE WHEN ud.is_processed = 1 THEN 1 ELSE NULL END) * 100) / COUNT(ud.agent_id))\r\n" - + " END AS completed_percentage\r\n" - + "FROM gcc_1913_campaign.agent_assign aa \r\n" - + "JOIN gcc_1913_qaqc.agents_list al ON al.agent_id = aa.agent_id \r\n" - + "JOIN gcc_1913_campaign.upload_data ud ON ud.agent_id = aa.agent_id AND ud.campaign_id = aa.campaign_id\r\n" - + "WHERE aa.campaign_id = ? AND aa.isactive = 1 AND aa.isdelete = 0 AND ud.agent_id IS NOT NULL \r\n" - + "GROUP BY aa.agent_id, al.agent_name \r\n" - + "ORDER BY aa.agent_id"; - - return jdbcTemplate.queryForList(query, campaignId); - } - - //report for campaign details - public List> getAgentReportCampaignId(String campaignId) { - String query = "SELECT cr.category_id,cr.campaign_id, cc.category_name, \r\n" - + " cr.start_date, cr.end_date, \r\n" - + " cr.description, date (cr.created_date) as created_date \r\n" - + " FROM gcc_1913_campaign.category cc \r\n" - + " join gcc_1913_campaign.campaign_request cr on cr.category_id = cc.category_id \r\n" - + " where cr.campaign_id = ?;"; - - return jdbcTemplate.queryForList(query, campaignId); - } - - - - //get campaignname - public String getCampaignName(int campaignId) { - String query = "SELECT campaign_name FROM gcc_1913_campaign.campaign_request WHERE campaign_id = ?"; - - return jdbcTemplate.queryForObject(query, String.class, campaignId); - } - - - - //question and answers counts with percentage in report page method - - public List> getQuestionAnswers(int campaignId) { - String sql = "SELECT cq.question_id, cq.questions, ca.campaign_answer," - + " COUNT(qa.campaign_answer) AS answer_count," - + " FLOOR(" - + " IFNULL((COUNT(qa.campaign_answer) / NULLIF(total_info.total_information_given, 0)) * 100, 0)" - + " ) AS answer_percentage" - + " FROM " - + " gcc_1913_campaign.campaign_questions cq" - + " JOIN " - + " gcc_1913_campaign.campaign_answers ca " - + " ON cq.question_id = ca.question_id AND cq.campaign_id = ca.campaign_id" - + " LEFT JOIN " - + " gcc_1913_campaign.questions_answers qa " - + " ON cq.question_id = qa.question_id " - + " AND ca.campaign_answer = qa.campaign_answer " - + " AND cq.campaign_id = qa.campaign_id" - + " LEFT JOIN (" - + " SELECT campaign_id, COUNT(*) AS total_information_given" - + " FROM gcc_1913_campaign.upload_data " - + " WHERE call_status = 'INFORMATION GIVEN'" - + " GROUP BY campaign_id" - + " ) AS total_info ON total_info.campaign_id = cq.campaign_id" - + " WHERE " - + " cq.campaign_id = ? " - + " AND cq.isactive = 1 " - + " AND cq.isdelete = 0" - + " GROUP BY " - + " cq.question_id, cq.questions, ca.campaign_answer, total_info.total_information_given" - + " ORDER BY " - + " cq.question_id"; - - List> result = jdbcTemplate.queryForList(sql, campaignId); - Map> responseMap = new LinkedHashMap<>(); - - for (Map row : result) { - int questionId = (int) row.get("question_id"); - if (!responseMap.containsKey(questionId)) { - Map questionData = new HashMap<>(); - questionData.put("question_id", questionId); - questionData.put("questions", row.get("questions")); - questionData.put("answers", new ArrayList<>()); - responseMap.put(questionId, questionData); - } - - Map answerData = new HashMap<>(); - answerData.put("campaign_answer", row.get("campaign_answer")); - answerData.put("answer_count", row.get("answer_count")); - answerData.put("answer_percentage", row.get("answer_percentage")); - - ((List>) responseMap.get(questionId).get("answers")).add(answerData); - } - - return new ArrayList<>(responseMap.values()); - } - - // - - - - -// public void generateCSV(int categoryId, int campaignId, PrintWriter writer) { -// List> resultList = new ArrayList<>(); -// -// // Fetch ordered field column names -// String fetchColumnsSQL = "SELECT COLUMN_NAME " + -// "FROM INFORMATION_SCHEMA.COLUMNS " + -// "WHERE TABLE_SCHEMA = 'gcc_1913_campaign' " + -// "AND TABLE_NAME = 'upload_data' " + -// "AND COLUMN_NAME LIKE 'field_%' " + -// "ORDER BY CAST(SUBSTRING(COLUMN_NAME, 7) AS UNSIGNED)"; -// -// List fieldColumns = jdbcTemplate.queryForList(fetchColumnsSQL, String.class); -// -// if (fieldColumns.isEmpty()) { -// writer.println("No matching columns found"); -// return; -// } -// -// // Fetch ordered fields data based on campaign_id, including data_id, agent_id, and call_status -// String query1 = "SELECT data_id, " + String.join(", ", fieldColumns) + ", agent_id, call_status,remarks " + -// "FROM gcc_1913_campaign.upload_data WHERE campaign_id = ?"; -// -// List> orderedFieldsList = jdbcTemplate.queryForList(query1, campaignId); -// -// if (orderedFieldsList.isEmpty()) { -// writer.println("No data found for campaign_id: " + campaignId); -// return; -// } -// -// // Fetch category columns -// String query2 = "SELECT column_name FROM gcc_1913_campaign.category_columns WHERE category_id = ? AND isactive=1"; -// List categoryColumns = jdbcTemplate.queryForList(query2, String.class, categoryId); -// -// if (categoryColumns.isEmpty()) { -// writer.println("No category columns found for category_id: " + categoryId); -// return; -// } -// -// int categoryCount = categoryColumns.size(); -// -// // Fetch Agent Names from agent_id -// String fetchAgentSQL = "SELECT agent_id, agent_name FROM gcc_1913_qaqc.agents_list"; -// Map agentMap = jdbcTemplate.query(fetchAgentSQL, rs -> { -// Map map = new HashMap<>(); -// while (rs.next()) { -// map.put(rs.getInt("agent_id"), rs.getString("agent_name")); -// } -// return map; -// }); -// -// // Fetch Questions for given campaign_id -// String fetchQuestionsQuery = "SELECT question_id, questions FROM gcc_1913_campaign.campaign_questions WHERE campaign_id = ?"; -// Map questionsMap = jdbcTemplate.query(fetchQuestionsQuery, rs -> { -// Map map = new LinkedHashMap<>(); -// while (rs.next()) { -// map.put(rs.getInt("question_id"), rs.getString("questions")); -// } -// return map; -// }, campaignId); -// -// // Fetch Answers mapped to questions and grouped by data_id -// String fetchAnswersQuery = "SELECT data_id, question_id, campaign_answer FROM gcc_1913_campaign.questions_answers " + -// "WHERE campaign_id = ?"; -// Map> answersMap = jdbcTemplate.query(fetchAnswersQuery, rs -> { -// Map> map = new HashMap<>(); -// while (rs.next()) { -// int dataId = rs.getInt("data_id"); -// int questionId = rs.getInt("question_id"); -// String answer = rs.getString("campaign_answer"); -// -// map.computeIfAbsent(dataId, k -> new HashMap<>()).put(questionId, answer); -// } -// return map; -// }, campaignId); -// -// // Process each row and collect data -// for (Map orderedFields : orderedFieldsList) { -// List nonNullValues = new ArrayList<>(); -// for (String field : fieldColumns) { -// Object value = orderedFields.get(field); -// if (value != null) { -// nonNullValues.add(value); -// if (nonNullValues.size() == categoryCount) { -// break; // Stop after collecting required count -// } -// } -// } -// -// if (nonNullValues.size() < categoryCount) { -// continue; // Skip if not enough non-null values -// } -// -// Integer dataId = orderedFields.get("data_id") != null ? ((Number) orderedFields.get("data_id")).intValue() : null; -// -// // Map category columns to non-null ordered field values -// Map finalMapping = new LinkedHashMap<>(); -// -// // Add category columns -// for (int i = 0; i < categoryCount; i++) { -// finalMapping.put(categoryColumns.get(i), nonNullValues.get(i)); -// } -// -// // Add Questions and Corresponding Answers for this specific data_id -// Map currentAnswers = answersMap.getOrDefault(dataId, new HashMap<>()); -// for (Map.Entry entry : questionsMap.entrySet()) { -// Integer questionId = entry.getKey(); -// String questionText = entry.getValue(); -// String answer = currentAnswers.getOrDefault(questionId, "-"); // Default to "-" -// -// finalMapping.put(questionText, answer); -// } -// -// //Integer agentId = ((Number) orderedFields.get("agent_id")).intValue(); -// -// Integer agentId = orderedFields.get("agent_id") != null ? ((Number) orderedFields.get("agent_id")).intValue() : null; -// String agentName = agentMap.getOrDefault(agentId, "Not Assigned"); -// finalMapping.put("Agent Name", agentName); -// -// String callstatus = orderedFields.get("call_status") != null ? orderedFields.get("call_status").toString() : "-"; -// finalMapping.put("Call Status", callstatus); -// -// // Add Remarks -// String remarks = orderedFields.get("remarks") != null ? orderedFields.get("remarks").toString() : "-"; -// -// finalMapping.put("Remarks", remarks); -// -// resultList.add(finalMapping); -// } -// -// // Write CSV data -// if (resultList.isEmpty()) { -// writer.println("No Data Available"); -// return; -// } -// -// // Extract headers from the first row -// String headers = String.join(",", resultList.get(0).keySet()); -// writer.println(headers); -// -// // Write data rows -// for (Map rowData : resultList) { -// List values = rowData.values().stream() -// .map(value -> value != null ? value.toString() : "") -// .collect(Collectors.toList()); -// writer.println(String.join(",", values)); -// } -// } - - - // Method to escape CSV values - private String escapeCsvValue(String value) { - if (value == null) return ""; - - // If the value contains commas, double quotes, or newlines, wrap it in quotes and escape inner quotes - if (value.contains(",") || value.contains("\"") || value.contains("\n")) { - value = "\"" + value.replace("\"", "\"\"") + "\""; - } - return value; - } - - public void generateCSV(int categoryId, int campaignId, PrintWriter writer) { - List> resultList = new ArrayList<>(); - - // Fetch ordered field column names - String fetchColumnsSQL = "SELECT COLUMN_NAME " + - "FROM INFORMATION_SCHEMA.COLUMNS " + - "WHERE TABLE_SCHEMA = 'gcc_1913_campaign' " + - "AND TABLE_NAME = 'upload_data' " + - "AND COLUMN_NAME LIKE 'field_%' " + - "ORDER BY CAST(SUBSTRING(COLUMN_NAME, 7) AS UNSIGNED)"; - - List fieldColumns = jdbcTemplate.queryForList(fetchColumnsSQL, String.class); - - if (fieldColumns.isEmpty()) { - writer.println("No matching columns found"); - return; - } - - // Fetch ordered fields data based on campaign_id, including data_id, agent_id, and call_status - String query1 = "SELECT data_id, " + String.join(", ", fieldColumns) + ", agent_id, call_status,remarks,DATE(updated_date) as updated_date " + - "FROM gcc_1913_campaign.upload_data WHERE campaign_id = ?"; - - List> orderedFieldsList = jdbcTemplate.queryForList(query1, campaignId); - - if (orderedFieldsList.isEmpty()) { - writer.println("No data found for campaign_id: " + campaignId); - return; - } - - // Fetch category columns - String query2 = "SELECT column_name FROM gcc_1913_campaign.category_columns WHERE category_id = ? AND isactive=1"; - List categoryColumns = jdbcTemplate.queryForList(query2, String.class, categoryId); - - if (categoryColumns.isEmpty()) { - writer.println("No category columns found for category_id: " + categoryId); - return; - } - - int categoryCount = categoryColumns.size(); - - // Fetch Agent Names from agent_id - String fetchAgentSQL = "SELECT agent_id, agent_name FROM gcc_1913_qaqc.agents_list"; - Map agentMap = jdbcTemplate.query(fetchAgentSQL, rs -> { - Map map = new HashMap<>(); - while (rs.next()) { - map.put(rs.getInt("agent_id"), rs.getString("agent_name")); - } - return map; - }); - - // Fetch Questions for given campaign_id - String fetchQuestionsQuery = "SELECT question_id, questions FROM gcc_1913_campaign.campaign_questions WHERE campaign_id = ?"; - Map questionsMap = jdbcTemplate.query(fetchQuestionsQuery, rs -> { - Map map = new LinkedHashMap<>(); - while (rs.next()) { - map.put(rs.getInt("question_id"), rs.getString("questions")); - } - return map; - }, campaignId); - - // Fetch Answers mapped to questions and grouped by data_id - String fetchAnswersQuery = "SELECT data_id, question_id, campaign_answer FROM gcc_1913_campaign.questions_answers " + - "WHERE campaign_id = ?"; - Map> answersMap = jdbcTemplate.query(fetchAnswersQuery, rs -> { - Map> map = new HashMap<>(); - while (rs.next()) { - int dataId = rs.getInt("data_id"); - int questionId = rs.getInt("question_id"); - String answer = rs.getString("campaign_answer"); - - map.computeIfAbsent(dataId, k -> new HashMap<>()).put(questionId, answer); - } - return map; - }, campaignId); - - // Process each row and collect data - for (Map orderedFields : orderedFieldsList) { - List nonNullValues = new ArrayList<>(); - for (String field : fieldColumns) { - Object value = orderedFields.get(field); - if (value != null) { - nonNullValues.add(value); - if (nonNullValues.size() == categoryCount) { - break; // Stop after collecting required count - } - } - } - - if (nonNullValues.size() < categoryCount) { - continue; // Skip if not enough non-null values - } - - Integer dataId = orderedFields.get("data_id") != null ? ((Number) orderedFields.get("data_id")).intValue() : null; - - // Map category columns to non-null ordered field values - Map finalMapping = new LinkedHashMap<>(); - - // Add category columns - for (int i = 0; i < categoryCount; i++) { - finalMapping.put(categoryColumns.get(i), nonNullValues.get(i)); - } - - // Add Questions and Corresponding Answers for this specific data_id - Map currentAnswers = answersMap.getOrDefault(dataId, new HashMap<>()); - for (Map.Entry entry : questionsMap.entrySet()) { - Integer questionId = entry.getKey(); - String questionText = entry.getValue(); - String answer = currentAnswers.getOrDefault(questionId, "-"); // Default to "-" - - finalMapping.put(questionText, answer); - } - - Integer agentId = orderedFields.get("agent_id") != null ? ((Number) orderedFields.get("agent_id")).intValue() : null; - String agentName = agentMap.getOrDefault(agentId, "Not Assigned"); - finalMapping.put("Agent Name", agentName); - - String callstatus = orderedFields.get("call_status") != null ? orderedFields.get("call_status").toString() : "-"; - finalMapping.put("Call Status", callstatus); - - // Add Remarks - String remarks = orderedFields.get("remarks") != null ? orderedFields.get("remarks").toString() : "-"; - finalMapping.put("Remarks", remarks); - - String up_date = orderedFields.get("updated_date") != null ? orderedFields.get("updated_date").toString() : "-"; - finalMapping.put("Updated_Date", up_date); - - resultList.add(finalMapping); - } - - // Write CSV data - if (resultList.isEmpty()) { - writer.println("No Data Available"); - return; - } -/* - // Extract headers from the first row and escape them - String headers = resultList.get(0).keySet().stream() - .map(this::escapeCsvValue) // Escape each header value - .collect(Collectors.joining(",")); - writer.println(headers); - - // Write data rows - for (Map rowData : resultList) { - List values = rowData.values().stream() - .map(value -> escapeCsvValue(value != null ? value.toString() : "")) - .collect(Collectors.toList()); - writer.println(String.join(",", values)); - } - */ - // Extract headers from the first row and escape them - Map firstRow = resultList.get(0); - - StringBuilder headerBuilder = new StringBuilder(); - int headerIndex = 0; - - for (String key : firstRow.keySet()) { - if (headerIndex > 0) { - headerBuilder.append(","); - } - headerBuilder.append(escapeCsvValue(key)); - headerIndex++; - } - - writer.println(headerBuilder.toString()); - - // Write data rows - for (Map rowData : resultList) { - - StringBuilder rowBuilder = new StringBuilder(); - int valueIndex = 0; - - for (Object value : rowData.values()) { - if (valueIndex > 0) { - rowBuilder.append(","); - } - rowBuilder.append( - escapeCsvValue(value != null ? value.toString() : "") - ); - valueIndex++; - } - - writer.println(rowBuilder.toString()); - } - - } - - -} - - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignService.java deleted file mode 100644 index 31f83f30..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignService.java +++ /dev/null @@ -1,715 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.io.File; -import java.io.IOException; -import java.sql.Date; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.jdbc.core.simple.SimpleJdbcInsert; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Service -public class CampaignService { - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public void setDataSource2(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - private JdbcTemplate jdbcTemplate2; - - - //Method to save file and return its URL - public String saveFile(MultipartFile file) { - String fileName = file.getOriginalFilename(); - String filePath = "/uploads/" + fileName; // Path to save the file - try { - File destinationFile = new File(filePath); - file.transferTo(destinationFile); // Save the file locally - } catch (IOException e) { - throw new RuntimeException("Failed to store file " + fileName, e); - } - return filePath; // Return the file path (URL) for saving to the database - } - - - //Method to save campaign details into the database - public void saveCampaignDetails(Map campaignDetails) { - String sql = "UPDATE gcc_1913_campaign.campaign_request " + - "SET start_date = :start_date, " + - "end_date = :end_date, " + - "calls_per_agent = :calls_per_agent, " + - "description = :description " + - "WHERE campaign_id = :campaign_id"; - - // Using NamedParameterJdbcTemplate for mapping campaignDetails into query - NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate); - namedJdbcTemplate.update(sql, campaignDetails); - } - - - // Method to save campaign details into the database - public String saveCampaignDetailsExcel(Map campaignDetailsExcel) { - - campaignDetailsExcel.putIfAbsent("campaign_status", "PENDING"); - - String sql = "INSERT INTO gcc_1913_campaign.campaign_request (campaign_name, category_id, excel_url,campaign_status) " + - "VALUES (:campaign_name, :category_id, :excel_url ,:campaign_status)"; - - // Using NamedParameterJdbcTemplate for mapping campaignDetails into query - NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate); - namedJdbcTemplate.update(sql, campaignDetailsExcel); - - // Return the category to use in the next step - return campaignDetailsExcel.get("category_id").toString(); - - } - - - // campaign_status change as ongoing in campaign_request table - @Transactional - public void updateCampaignStatus(int campaignId, int categoryId) { - String checkSql = "SELECT COUNT(*) FROM gcc_1913_campaign.agent_assign " - + "WHERE campaign_id = ? AND category_id = ? AND status = 'ASSIGNED'"; - - int assignedCount = jdbcTemplate.queryForObject(checkSql, Integer.class, campaignId, categoryId); - - if (assignedCount > 0) { - String updateSql = "UPDATE gcc_1913_campaign.campaign_request " - + "SET campaign_status = 'ONGOING' WHERE campaign_id = ? AND category_id = ?"; - jdbcTemplate.update(updateSql, campaignId, categoryId); - - System.out.println("Campaign status updated to ONGOING for campaign ID: " + campaignId); - } else { - System.out.println("No agents assigned yet. Campaign status remains PENDING."); - } - } - - - //Validated uploaded excel column count with field column in our DB - public List getUploadDataFieldColumns() { - String query = "SELECT column_name FROM information_schema.columns " - + "WHERE table_schema = 'gcc_1913_campaign' " - + "AND table_name = 'upload_data' " - + "AND column_name LIKE 'field_%'"; - return jdbcTemplate.queryForList(query, String.class); - } - - - - - public String saveQuestionsAnswers(List> questionsData) { - for (Map question : questionsData) { - String questionText = (String) question.get("question"); - String answerType = (String) question.get("answerType"); - - // Validate and parse categoryId and campaignId - Integer categoryId = Integer.parseInt(question.get("categoryId").toString()); - Integer campaignId = Integer.parseInt(question.get("campaignId").toString()); - - List answers = (List) question.get("answers"); - - // Insert question and get generated question_id - String questionInsertQuery = "INSERT INTO gcc_1913_campaign.campaign_questions (category_id, campaign_id, questions, answer_type_id) VALUES (?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(questionInsertQuery, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, categoryId); - ps.setInt(2, campaignId); - ps.setString(3, questionText); - ps.setString(4, answerType); - return ps; - }, keyHolder); - - Integer questionId = keyHolder.getKey().intValue(); - - // Insert answers if available - if (answers != null && !answers.isEmpty()) { - String answerInsertQuery = "INSERT INTO gcc_1913_campaign.campaign_answers (category_id, campaign_id, question_id, campaign_answer) VALUES (?, ?, ?, ?)"; - for (String answer : answers) { - jdbcTemplate.update(answerInsertQuery, categoryId, campaignId, questionId, answer); - } - } - } - return "Questions and Answers saved successfully!"; - } - - - - - public void saveQuestionsAndAnswers(String category, String campaignId, String question, String answerType, List answers) { - // Convert category and answerType to integers once to avoid redundant parsing - int categoryId = Integer.parseInt(category); - int answerTypeId = Integer.parseInt(answerType); - int campaignIdd = Integer.parseInt(campaignId); - - // Query to insert question into campaign_questions and retrieve generated question_id - String query1 = "INSERT INTO gcc_1913_campaign.campaign_questions (category_id, campaign_id, questions, answer_type_id) VALUES (?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(query1, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, categoryId); - ps.setInt(2, campaignIdd); - ps.setString(3, question); - ps.setInt(4, answerTypeId); - return ps; - }, keyHolder); - - int questionId = keyHolder.getKey().intValue(); - - // If answerType is NOT "Text" (ID = 1), save answers - if (answerTypeId != 1 && answers != null && !answers.isEmpty()) { - String query2 = "INSERT INTO gcc_1913_campaign.campaign_answers (category_id, campaign_id, question_id, campaign_answer) VALUES (?, ?, ?, ?)"; - - for (String answer : answers) { - jdbcTemplate.update(query2, categoryId, campaignId, questionId, answer); - } - } - - System.out.println("Inserted Question ID: " + questionId + " with Answers: " + (answers != null ? answers : "None")); - } - - - - - -// -// public Map getCampaignDetailsById(Long campaign_id) { -// String sql = "SELECT * FROM gcc_1913_campaign.campaign_request WHERE campaign_id = ?"; -// return jdbcTemplate.queryForMap(sql, campaign_id); -// } - - - - - public void updateCampaign(Long campaign_id, String end_date) { - String sql = "UPDATE gcc_1913_campaign.campaign_request SET end_date = ? WHERE campaign_id = ?"; - jdbcTemplate.update(sql, end_date,campaign_id); - } - - - - public List> getCampaignDetails() { - String sql = "SELECT campaign_id, " + - " campaign_name, " + - " CONCAT(" + - " DATE_FORMAT(start_date, '%d/%m/%Y'), " + - " ' to ', " + - " DATE_FORMAT(end_date, '%d/%m/%Y')" + - " ) AS event_dates, " + - " no_of_agents, " + - " calls_per_agent, " + - " (no_of_agents)*(calls_per_agent) as total_calls, " + - " description " + - "FROM gcc_1913_campaign.campaign_request;"; - - List> campaigns = jdbcTemplate.queryForList(sql); - - - return campaigns; - } - - public List> getLastRow() - { - String sqlQuery ="SELECT campaign_id\r\n" - + "FROM gcc_1913_campaign.campaign_request\r\n" - + "ORDER BY campaign_id DESC\r\n" - + "LIMIT 1"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - - - - public String getLastInsertedCategoryId() { - String sqlQuery = "SELECT category_id " + - "FROM gcc_1913_campaign.campaign_request " + - "ORDER BY campaign_id DESC " + - "LIMIT 1"; - - return jdbcTemplate.queryForObject(sqlQuery, String.class); - } - - - public Integer getLastInsertedCampaignId() - { - String sqlQuery ="SELECT campaign_id\r\n" - + "FROM gcc_1913_campaign.campaign_request\r\n" - + "ORDER BY campaign_id DESC\r\n" - + "LIMIT 1"; - - return jdbcTemplate.queryForObject(sqlQuery,Integer.class); - } - - public List> getDetailsForStart() - { - String sqlQuery ="SELECT cr.campaign_id,cr.category_id,ca.category_name,cr.campaign_name,start_date\r\n" - + "FROM gcc_1913_campaign.campaign_request cr \r\n" - + "join gcc_1913_campaign.category ca ON cr.category_id = ca.category_id \r\n" - + "where cr.campaign_status='ONGOING' AND cr.isactive='1' and cr.isdelete='0' \r\n" - + "order by cr.campaign_id desc"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - public List> getDataforAgents(int campaign_id, int calls_per_agent) - { - List> assignedAgent_list =getAssignedAgentId(campaign_id); - List> data_list =getDataId(campaign_id); - - List> task = getTask(assignedAgent_list,data_list,calls_per_agent,campaign_id); - - // Perform the update query here - if (task != null && !task.isEmpty()) { - assignAgentIds(task); - updateAgentStatus(campaign_id); - } - - - return task; - } - - //Method to update agent_id for each data_id in upload_data table - public void assignAgentIds(List> taskList) { - String updateQuery = "UPDATE gcc_1913_campaign.upload_data SET agent_id = ? WHERE data_id = ? AND campaign_id = ?"; - - // Loop through each agent's task list - for (Map task : taskList) { - Integer agentId = (Integer) task.get("agent_id"); - Integer campaignId = (Integer) task.get("campaign_id"); - List dataIds = (List) task.get("data_ids"); - - // Update each data_id with the respective agent_id - for (Integer dataId : dataIds) { - jdbcTemplate.update(updateQuery, agentId, dataId, campaignId); - } - } - } - - //Example update method - private void updateAgentStatus(int campaign_id) { - String updateQuery = "UPDATE gcc_1913_campaign.campaign_request SET isactive = '0', isdelete='1' WHERE campaign_id = ?"; - jdbcTemplate.update(updateQuery, campaign_id); - } - - - private List> getTask(List> assignedAgent_list, List> data_list, - int calls_per_agent,int campaign_id) { - - List> result = new ArrayList<>(); - int dataIndex = 0; - - // Loop through each assigned ID - for (Map assigned : assignedAgent_list) { - // Create a map to store the assigned_id and corresponding data_ids - Map assignedTaskMap = new HashMap<>(); - List assignedDataIds = new ArrayList<>(); - - // Get assigned_id - Integer agent_id = (Integer) assigned.get("agent_id"); - - // Loop to assign the appropriate number of data IDs (calls_per_agent) - for (int i = 0; i < calls_per_agent; i++) { - if (dataIndex >= data_list.size()) { - // Exit if we run out of data IDs - break; - } - Map data = data_list.get(dataIndex); - Integer data_id = (Integer) data.get("data_id"); - assignedDataIds.add(data_id); - dataIndex++; - } - - // Put the agent_id and the corresponding data_ids in the map - assignedTaskMap.put("agent_id", agent_id); - assignedTaskMap.put("data_ids", assignedDataIds); - assignedTaskMap.put("campaign_id", campaign_id); - - // Add the map to the result list - result.add(assignedTaskMap); - } - - return result; - } - - - private List> getDataId(int campaign_id) { - - String sqlQuery ="SELECT data_id\r\n" - + "from gcc_1913_campaign.upload_data\r\n" - + "where campaign_id=?"; - - return jdbcTemplate.queryForList(sqlQuery, new Object[]{campaign_id}); - } - - - private List> getAssignedAgentId(int campaign_id) { - - String sqlQuery ="SELECT agent_id\r\n" - + "FROM gcc_1913_campaign.agent_assign \r\n" - + "where campaign_id=? and isactive='1'"; - - return jdbcTemplate.queryForList(sqlQuery, new Object[]{campaign_id}); - } - - public List> getActiveCampaigns() - { - String sqlQuery ="SELECT cr.campaign_id,cr.calls_per_agent,cr.category_id,cr.campaign_name,c.category_name,cr.start_date,cr.end_date,cr.description,cr.campaign_status\r\n" - + "FROM gcc_1913_campaign.campaign_request cr\r\n" - + "JOIN gcc_1913_campaign.category c ON cr.category_id=c.category_id\r\n" - + "where cr.isactive='1' and cr.campaign_status IN ('ONGOING', 'CLOSED') Order by cr.campaign_id desc"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - - public List> viewcampaignstatus(int campaign_id) { - - String sqlQuery ="SELECT \r\n" - + "aa.campaign_id as campaign_id,\r\n" - + " al.agent_id as agent_id,\r\n" - + " al.agent_name as agent_name,\r\n" - + " COUNT(up.agent_id) AS Assigned_count,\r\n" - + " COUNT(CASE WHEN up.field_14 IS NOT NULL THEN 1 END) AS Complete_count,\r\n" - + " COUNT(CASE WHEN up.field_14 IS NULL THEN 1 END) AS Pending_count,\r\n" - + " ROUND(\r\n" - + " (COUNT(CASE WHEN up.field_14 IS NOT NULL THEN 1 END) * 100) / \r\n" - + " COUNT(up.agent_id)\r\n" - + " ) as Percentage,\r\n" - + " COUNT(CASE WHEN up.field_14 = 'INFORMATION_GIVEN' THEN 1 END) AS Information_Given_count,\r\n" - + " COUNT(CASE WHEN up.field_14 = 'UNATTENDED' THEN 1 END) AS Unattended_count,\r\n" - + " COUNT(CASE WHEN up.field_14 = 'CALL_BACK_LATER' THEN 1 END) AS Call_back_later_count,\r\n" - + " COUNT(CASE WHEN up.field_14 = 'SWITCH_OFF' THEN 1 END) AS Switch_off_count,\r\n" - + " COUNT(CASE WHEN up.field_14 = 'WRONG_NUMBER' THEN 1 END) AS Wrong_number_count\r\n" - + "FROM gcc_1913_campaign.agent_assign aa\r\n" - + "JOIN gcc_1913_qaqc.agents_list al ON al.agent_id = aa.agent_id\r\n" - + "JOIN gcc_1913_campaign.upload_data up ON up.agent_id = al.agent_id AND up.campaign_id = ?\r\n" - + "WHERE aa.campaign_id = ? AND aa.isactive = '1'\r\n" - + "GROUP BY aa.campaign_id,al.agent_id, al.agent_name"; - - return jdbcTemplate.queryForList(sqlQuery,campaign_id,campaign_id); - } - - public List> viewcompletedby(int campaign_id, int agent_id) { - - String sqlQuery ="SELECT \r\n" - + "up.data_id as data_id,up.field_1 as id, up.field_2 as name, up.field_3 as address,field_5 as cellnumber, field_14 as call_status, \r\n" - + "count(cl.data_id) as call_count,updated_date as updated_date,field_15 as remarks\r\n" - + "FROM gcc_1913_campaign.agent_assign aa\r\n" - + "JOIN gcc_1913_campaign.upload_data up ON up.agent_id = aa.agent_id AND up.campaign_id = ?\r\n" - + "JOIN gcc_1913_campaign.call_logs cl ON cl.data_id=up.data_id\r\n" - + "WHERE aa.campaign_id = ? AND aa.isactive = '1' AND aa.agent_id=? AND up.field_14 IS NOT NULL\r\n" - + "group by up.data_id,up.field_1, up.field_2"; - - return jdbcTemplate.queryForList(sqlQuery,campaign_id,campaign_id,agent_id); - } - - public String getExcelUrlByCampaignId(int lastId) { - String sqlQuery = "SELECT excel_url FROM gcc_1913_campaign.campaign_request WHERE campaign_id = ?"; - return jdbcTemplate.queryForObject(sqlQuery, String.class, lastId); - } - - - - public void saveUploadData(String category, int campaignId, Map rowData, List expectedHeaders) { - int fieldCount = rowData.size(); - - List columnNames = new ArrayList<>(); - for (int i = 1; i <= fieldCount; i++) { - columnNames.add("field_" + i); - } - - String columnNamesString = String.join(", ", columnNames); - //String placeholders = columnNames.stream().map(col -> "?").collect(Collectors.joining(", ")); - - StringBuilder placeholdersBuilder = new StringBuilder(); - - for (int i = 0; i < columnNames.size(); i++) { - if (i > 0) { - placeholdersBuilder.append(", "); - } - placeholdersBuilder.append("?"); - } - - String placeholders = placeholdersBuilder.toString(); - - String sql = "INSERT INTO gcc_1913_campaign.upload_data (category_id, campaign_id, " + columnNamesString + ") VALUES (?, ?, " + placeholders + ")"; - - //System.out.println("SQL Query========= " + sql); - - List values = new ArrayList<>(); - values.add(category); - values.add(campaignId); - - // Ensure rowData values are ordered based on expected headers - for (String header : expectedHeaders) { - values.add(rowData.getOrDefault(header, "")); // Ensures the correct mapping - } - - final Logger logger = LoggerFactory.getLogger(CampaignService.class); - try { - jdbcTemplate.update(sql, values.toArray()); - } catch (Exception e) { - logger.error("Error inserting upload data for campaign {}: {}", campaignId, e.getMessage()); - } - } - - -// public void saveUploadData(String category, int campaignId, Map rowData) { -// // Get total number of fields in the row -// int fieldCount = rowData.size(); -// -// // Generate dynamic column names as field_1, field_2, ..., field_N -// List columnNames = new ArrayList<>(); -// for (int i = 1; i <= fieldCount; i++) { -// columnNames.add("field_" + i); -// } -// -// // Build dynamic SQL query -// String columnNamesString = String.join(", ", columnNames); -// String placeholders = columnNames.stream().map(col -> "?").collect(Collectors.joining(", ")); -// -// String sql = "INSERT INTO upload_data (category_id, campaign_id, " + columnNamesString + ") VALUES (?, ?, " + placeholders + ")"; -// -// System.out.println("SQL Query========= " + sql); -// -// // Prepare values list -// List values = new ArrayList<>(); -// values.add(category); -// values.add(campaignId); -// values.addAll(rowData.values()); // Add row data values dynamically -// -// -// -// final Logger logger = LoggerFactory.getLogger(CampaignService.class); -// try { -// jdbcTemplate.update(sql, values.toArray()); -// } catch (Exception e) { -// logger.error("Error inserting upload data for campaign {}: {}", campaignId, e.getMessage()); -// } -// } - - - - - - //Agent List - public List> getAllAgents() { - String sql = "SELECT agent_id, agent_name FROM gcc_1913_qaqc.agents_list WHERE calling_type = 'OUTBOUND' AND isactive = '1'"; - return jdbcTemplate.queryForList(sql); - } - - //count based on total, completed and pending - public Map getCampaignStatistics(int campaignId) { - Map result = new HashMap<>(); - - // Total Count - String totalQuery = "SELECT COUNT(*) AS total FROM gcc_1913_campaign.upload_data WHERE campaign_id = ?"; - int totalCount = jdbcTemplate.queryForObject(totalQuery, Integer.class, campaignId); - result.put("totalCount", totalCount); - - // Completed Count (agent_id is not null and call_status is null) - String completedQuery = "SELECT COUNT(*) AS completed FROM gcc_1913_campaign.upload_data ud\r\n" - + "JOIN gcc_1913_campaign.campaign_request cr ON ud.campaign_id = cr.campaign_id\r\n" - + "WHERE ud.campaign_id = ? AND cr.campaign_status = 'ONGOING' AND ud.agent_id IS NOT NULL AND\r\n" - + "( ud.call_status NOT IN ('CALL BACK LATER','UNATTENDED'))"; - int completedCount = jdbcTemplate.queryForObject(completedQuery, Integer.class, campaignId); - result.put("completedCount", completedCount); - - // Pending Count (agent_id is not null and call_status is not null) - String pendingQuery = "SELECT COUNT(*) AS pending FROM gcc_1913_campaign.upload_data ud\r\n" - + "JOIN gcc_1913_campaign.campaign_request cr ON ud.campaign_id = cr.campaign_id\r\n" - + "WHERE ud.campaign_id = ? AND ud.agent_id IS NOT NULL \r\n" - + "AND (ud.call_status IS NULL OR ud.call_status IN ('CALL BACK LATER','UNATTENDED'))"; - int pendingCount = jdbcTemplate.queryForObject(pendingQuery, Integer.class, campaignId); - result.put("pendingCount", pendingCount); - - return result; - } - - - - public List> getCampaignDetailsById(Long campaign_id) { - String sql = "SELECT \r\n" - + " cr.campaign_id, \r\n" - + " cr.campaign_name, \r\n" - + " cr.category_id, \r\n" - + " cr.start_date, \r\n" - + " cr.end_date, \r\n" - + " cr.calls_per_agent, \r\n" - + " cr.description, \r\n" - + " cr.created_date, \r\n" - + " cr.excel_url, \r\n" - + " cr.isactive, \r\n" - + " cr.isdelete, \r\n" - + " cr.campaign_status, \r\n" - + " cq.question_id, \r\n" - + " cq.questions, \r\n" - + " cq.answer_type_id, \r\n" - + " at.type_name, \r\n" - + " ca.id AS answer_id, \r\n" - + " ca.campaign_answer\r\n" - + "FROM gcc_1913_campaign.campaign_request cr\r\n" - + "JOIN gcc_1913_campaign.campaign_questions cq \r\n" - + " ON cr.campaign_id = cq.campaign_id\r\n" - + "LEFT JOIN gcc_1913_campaign.answer_type at\r\n" - + " ON cq.answer_type_id = at.answer_type_id \r\n" - + "LEFT JOIN gcc_1913_campaign.campaign_answers ca\r\n" - + " ON cq.question_id = ca.question_id\r\n" - + "WHERE cr.campaign_id = ?"; - - List> results = jdbcTemplate.queryForList(sql, campaign_id); - - // Group answers by question_id - Map> groupedData = new LinkedHashMap(); - - for (Map row : results) { - Object questionIdObj = row.get("question_id"); - Long questionId = null; - - // Convert Integer to Long if needed - if (questionIdObj instanceof Integer) { - questionId = ((Integer) questionIdObj).longValue(); - } else if (questionIdObj instanceof Long) { - questionId = (Long) questionIdObj; - } - - if (questionId == null) continue; - - if (!groupedData.containsKey(questionId)) { - // Ensure `campaign_answer` is initialized correctly - List answers = new ArrayList<>(); - if (row.get("campaign_answer") != null) { - answers.add(row.get("campaign_answer").toString()); - } - row.put("campaign_answer", answers); - groupedData.put(questionId, row); - } else { - // Append the answer to the existing question - List answers = (List) groupedData.get(questionId).get("campaign_answer"); - if (row.get("campaign_answer") != null) { - answers.add(row.get("campaign_answer").toString()); - } - } - } - - return new ArrayList<>(groupedData.values()); - } - - - - - //question and answers counts with percentage in report page method - public List> getQuestionAnswers(int campaignId) { - String sql = "SELECT cq.question_id, cq.questions, ca.campaign_answer, " + - "COUNT(qa.campaign_answer) AS answer_count, " + - "FLOOR(IFNULL((COUNT(qa.campaign_answer) / " + - "(SELECT COUNT(*) FROM gcc_1913_campaign.upload_data " + - "WHERE campaign_id = cq.campaign_id AND call_status = 'INFORMATION GIVEN') * 100), 0)) AS answer_percentage " + - "FROM campaign_questions cq " + - "JOIN campaign_answers ca ON cq.question_id = ca.question_id AND cq.campaign_id = ca.campaign_id " + - "LEFT JOIN questions_answers qa ON cq.question_id = qa.question_id AND ca.campaign_answer = qa.campaign_answer AND cq.campaign_id = qa.campaign_id " + - "WHERE cq.campaign_id = ? AND cq.isactive = 1 AND cq.isdelete = 0 " + - "GROUP BY cq.question_id, cq.questions, ca.campaign_answer " + - "ORDER BY cq.question_id;"; - - List> result = jdbcTemplate.queryForList(sql, campaignId); - Map> responseMap = new LinkedHashMap<>(); - - for (Map row : result) { - int questionId = (int) row.get("question_id"); - if (!responseMap.containsKey(questionId)) { - Map questionData = new HashMap<>(); - questionData.put("question_id", questionId); - questionData.put("questions", row.get("questions")); - questionData.put("answers", new ArrayList<>()); - responseMap.put(questionId, questionData); - } - - Map answerData = new HashMap<>(); - answerData.put("campaign_answer", row.get("campaign_answer")); - answerData.put("answer_count", row.get("answer_count")); - answerData.put("answer_percentage", row.get("answer_percentage")); - - ((List>) responseMap.get(questionId).get("answers")).add(answerData); - } - - return new ArrayList<>(responseMap.values()); - } - - - //////////////dizo////////////// - - public int closeCampaign(int campaignId) { - String sql = "UPDATE gcc_1913_campaign.campaign_request SET campaign_status = 'CLOSED' WHERE campaign_id = ?"; - int rowsAffected = jdbcTemplate.update(sql, campaignId); - - if (rowsAffected == 0) { - System.out.println("Failed to update. Check if campaignId exists: " + campaignId); - } else { - System.out.println("Campaign ID " + campaignId + " successfully updated to CLOSED."); - } - - return rowsAffected; - } - - public int autoCloseExpiredCampaigns() { - String sql = "UPDATE gcc_1913_campaign.campaign_request " + - "SET campaign_status = 'CLOSED' " + - "WHERE campaign_status = 'ONGOING' AND end_date < CURRENT_DATE"; - - int rowsAffected = jdbcTemplate.update(sql); - - if (rowsAffected == 0) { - System.out.println("No expired campaigns found to close."); - } else { - System.out.println(rowsAffected + " campaigns successfully updated to CLOSED."); - } - - return rowsAffected; - } - - // Scheduled job to run daily at midnight - /* - * @Scheduled(cron = "0 0 0 * * ?") public void scheduledAutoClose() { - * System.out.println("Running scheduled auto-close for expired campaigns..."); - * autoCloseExpiredCampaigns(); } - */ - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/WhatsappMsgService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/WhatsappMsgService.java deleted file mode 100644 index 8daa3ecc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/WhatsappMsgService.java +++ /dev/null @@ -1,40 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.service; - -import java.net.HttpURLConnection; -import java.net.URL; - -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class WhatsappMsgService { - - - public String sendMsg(String msgUrl) { - - String response =""; - try{ - HttpURLConnection connection =null; - - URL url = new URL(msgUrl); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response=responseCode+""; - System.out.println("Response Code: " + responseCode); - - }catch (Exception e){ - e.printStackTrace(); - } - - return response; - } - - - public String sendSMS(String SMS_Url) { - RestTemplate restTemplate = new RestTemplate(); - String response =restTemplate.getForObject(SMS_Url,String.class); - return response; - } - } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/.DS_Store deleted file mode 100644 index 0f072536..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceApiController.java deleted file mode 100644 index 6e3998ae..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceApiController.java +++ /dev/null @@ -1,36 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - - -@RequestMapping("/gcc/api/callenter/attendance") -@RestController -public class AttendanceApiController { - - private AppConfig appConfig; - private final RestTemplate restTemplate; - - @Autowired - public AttendanceApiController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - - - @GetMapping("/getAttendancedetails") - public String getAttendancedetails(@RequestParam String fromDate,@RequestParam String toDate){ - String apiUrl = appConfig.attendanceReport + "/callcenter/api/attendance/getattendancereport"+"?fromDate="+ fromDate + "&toDate="+ toDate; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceMainController.java deleted file mode 100644 index 49e509c4..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceMainController.java +++ /dev/null @@ -1,71 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/callcenterattendance") -@Controller("callCenterAttendanceController") -public class AttendanceMainController { - - @Autowired - private AppConfig appConfig; - - @Autowired - private RestTemplate restTemplate; - - @GetMapping("/attendancereport") - public String AttendanceList( - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate, - Model model) { - List> attendanceData = Collections.emptyList(); - - if (fromDate != null && !fromDate.isEmpty() && toDate != null && !toDate.isEmpty()) { - String apiUrl = appConfig.attendanceReport + "/callcenter/api/attendance/getattendancereport?fromDate=" + fromDate + "&toDate=" + toDate; - - try { - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - String responseBody = responseEntity.getBody(); - - if (responseBody != null && !responseBody.isEmpty()) { - ObjectMapper objectMapper = new ObjectMapper(); - if (responseBody.trim().startsWith("{")) { - // Single object response - Map singleData = objectMapper.readValue(responseBody, new TypeReference<>() {}); - attendanceData = List.of(singleData); - } else { - // Array response - attendanceData = objectMapper.readValue(responseBody, new TypeReference<>() {}); - } - } - } catch (Exception e) { - System.err.println("Error fetching attendance data: " + e.getMessage()); - } - } - - model.addAttribute("attendanceData", attendanceData); - model.addAttribute("fromDate", fromDate); - model.addAttribute("toDate", toDate); - model.addAttribute("LoginUserId", LoginUserInfo.getLoginUserId()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - return "modules/callcenter/attendancereport"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintController.java deleted file mode 100644 index c2ad7029..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintController.java +++ /dev/null @@ -1,672 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; - -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.multipart.MultipartFile; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.ComplaintService; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.*; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -import org.springframework.http.*; - -import java.util.Base64; -import java.util.Collections; -import java.util.HashMap; -import org.springframework.web.multipart.MultipartFile; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import javax.imageio.ImageIO; -import java.util.Base64; - -@CrossOrigin -@RestController -@RequestMapping("gcc/api/callcenterqaqc/pgrcomplaint") -public class ComplaintController { - - private final RestTemplate restTemplate; - - public ComplaintController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @Autowired - private ComplaintService complaintService; - - @GetMapping("/getComplaintCategories") - public @ResponseBody String getComplaintCategories() { - return complaintService.fetchComplaintCategories(); - } - - @GetMapping("/getComplaintSubTypes") - public @ResponseBody String getComplaintSubTypes(@RequestParam String groupId) { - return complaintService.fetchComplaintSubTypes(groupId); - } - - @GetMapping("/getComplaintDetailsbyId") - public List> getComplaintDetailsById(@RequestParam String complaintid) { - return complaintService.fetchComplaintDetailsById(complaintid); - } - - @GetMapping("/getComplaintDetailsByMobile") - public List> getComplaintDetailsByMobile(@RequestParam String mobileNo) { - return complaintService.fetchComplaintDetailsByMobile(mobileNo); - } - - @PostMapping("/register") - public ResponseEntity registerComplaint( - @RequestParam(value = "ComplainantName", required = false) String complainantName, - @RequestParam(value = "ComplainantAddr", required = false) String complainantAddr, - @RequestParam(value = "MobileNo", required = false) String mobileNo, - @RequestParam(value = "Email", required = false) String email, - @RequestParam(value = "ComplaintType", required = false) String complaintType, - @RequestParam(value = "ComplaintTitle", required = false) String complaintTitle, - @RequestParam(value = "ComplaintDetails", required = false) String complaintDetails, - @RequestParam(value = "StreetId", required = false) String streetId, - @RequestParam(value = "Comp_Image", required = false) String compImage, - @RequestParam(value = "latitude", required = false) String latitude, - @RequestParam(value = "longtitude", required = false) String longtitude, - @RequestParam(value = "Landmark", required = false) String landmark, - @RequestParam(value = "gender", required = false) String gender) { - - String externalUrl = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice"; - - try { - // Create the URL object - URL url = new URL(externalUrl); - - // Create the HttpURLConnection object - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - conn.setDoOutput(true); - - // Create the parameters string, handling null values - String params = "serviceId=RegComplaint" + "&ComplainantName=" - + URLEncoder.encode(complainantName != null ? complainantName : "", "UTF-8") + "&ComplainantAddr=" - + URLEncoder.encode(complainantAddr != null ? complainantAddr : "", "UTF-8") + "&MobileNo=" - + URLEncoder.encode(mobileNo != null ? mobileNo : "", "UTF-8") + "&Email=" - + URLEncoder.encode(email != null ? email : "", "UTF-8") + "&ComplaintType=" - + URLEncoder.encode(complaintType != null ? complaintType : "", "UTF-8") + "&ComplaintTitle=" - + URLEncoder.encode(complaintTitle != null ? complaintTitle : "", "UTF-8") + "&ComplaintDetails=" - + URLEncoder.encode(complaintDetails != null ? complaintDetails : "", "UTF-8") + "&StreetId=" - + URLEncoder.encode(streetId != null ? streetId : "", "UTF-8") + "&Comp_Image=" - + URLEncoder.encode(compImage != null ? compImage : "", "UTF-8") + "&latitude=" - + URLEncoder.encode(latitude != null ? latitude : "", "UTF-8") + "&longtitude=" - + URLEncoder.encode(longtitude != null ? longtitude : "", "UTF-8") + "&Landmark=" - + URLEncoder.encode(landmark != null ? landmark : "", "UTF-8") + "&gender=" - + URLEncoder.encode(gender != null ? gender : "", "UTF-8") + "&compmode=2"; - // Write parameters to request body - try (OutputStream os = conn.getOutputStream()) { - byte[] input = params.getBytes("UTF-8"); - os.write(input, 0, input.length); - } - - // Read the response - int responseCode = conn.getResponseCode(); - BufferedReader reader; - if (responseCode == HttpURLConnection.HTTP_OK) { - reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - } else { - reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); - } - - StringBuilder response = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - response.append(line); - } - reader.close(); - - // Return the response from the external API - //return ResponseEntity.status(responseCode).body(response.toString()); - ObjectMapper mapper = new ObjectMapper(); - Map responseMap = mapper.readValue(response.toString(), Map.class); - - String complaintNo = responseMap.getOrDefault("Complaint Number", "N/A"); - //System.out.println("complaintNo===="+complaintNo); - - return ResponseEntity.ok() - .contentType(MediaType.APPLICATION_JSON) - .body(Map.of("complaintNumber", complaintNo)); - - } catch (IOException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("An error occurred while processing the request."); - } - } - - @PostMapping("/updateComplaint") - public ResponseEntity updateComplaint(@RequestParam("ComplaintId") String complaintId, - @RequestParam(value = "Message", required = false) String message, - @RequestParam(value = "Status") String status, - @RequestPart(value = "Comp_Image", required = false) MultipartFile compImage) { - - String userType = "Public"; - - //System.out.println("message:-" + message + "\n UserType:-" + userType + "\n Status:-" + status); - //System.out.println(compImage == null); - String externalUrl = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice"; - - try { - // Convert and compress the image to base64 if provided - String base64Image = null; - if (compImage != null && !compImage.isEmpty()) { - base64Image = compressAndEncodeToBase64(compImage); - //System.out.println("imageee" + base64Image); - } - - // Construct the POST body with parameters - String params = "serviceId=UpdateComplaint" + "&ComplaintId=" - + URLEncoder.encode(complaintId != null ? complaintId : "", "UTF-8") + "&Message=" - + URLEncoder.encode(message != null ? message : "", "UTF-8") + "&UserType=" - + URLEncoder.encode(userType, "UTF-8") + "&Status=" - + URLEncoder.encode(status != null ? status : "", "UTF-8") + "&Comp_Image=" - + URLEncoder.encode(compImage != null ? base64Image : "", "UTF-8") - + "&Token=718333469976265947044293"; - // Open connection and send POST request - URL url = new URL(externalUrl); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setDoOutput(true); - conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - - // Send parameters - OutputStream os = conn.getOutputStream(); - os.write(params.getBytes()); - os.flush(); - os.close(); - - // Handle the response - int responseCode = conn.getResponseCode(); - BufferedReader reader; - if (responseCode == HttpURLConnection.HTTP_OK) { - reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - } else { - reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); - } - - StringBuilder response = new StringBuilder(); - String line; - while ((line = reader.readLine()) != null) { - response.append(line); - } - reader.close(); - - return ResponseEntity.status(responseCode).body(response.toString()); - - } catch (IOException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("An error occurred while processing the request."); - } - } - - private String compressAndEncodeToBase64(MultipartFile file) throws IOException { - // Convert MultipartFile to BufferedImage - BufferedImage originalImage = ImageIO.read(file.getInputStream()); - - // Resize/Compress the image - int targetWidth = 800; // You can adjust the width as needed - int targetHeight = (int) (originalImage.getHeight() * (800.0 / originalImage.getWidth())); // Preserve aspect - // ratio - - BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB); - Graphics2D g = resizedImage.createGraphics(); - g.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null); - g.dispose(); - - // Compress the image by writing it to a ByteArrayOutputStream in JPEG format - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(resizedImage, "jpg", baos); // You can change the format to "png" or "jpg" - byte[] compressedBytes = baos.toByteArray(); - - // Convert the compressed image to base64 - return Base64.getEncoder().encodeToString(compressedBytes); - } - - ////////////////////////////////////// PGR Check ////////////////////////////////////////// - - -@GetMapping("/checktypeforduplicate") - public ResponseEntity getComplaintMatch( - @RequestParam("mobileNo") String mobileNo, - @RequestParam("complaintId") String complaintId, - @RequestParam("streetName") String streetName - ) { - try { - // 1. Map complaintId to complaint title - Map complaintIdToTitle = new HashMap<>(); - complaintIdToTitle.put("97", "Removal of Garbage"); - complaintIdToTitle.put("98", "Overflowing of Garbage Bin"); - complaintIdToTitle.put("99", "Removal of Debris"); - complaintIdToTitle.put("100", "Absenteeism of Sweepers"); - complaintIdToTitle.put("101", "Absenteeism of Door to door garbage Collector"); - complaintIdToTitle.put("102", "Improper Sweeping"); - complaintIdToTitle.put("103", "Provison of Garbage Bin"); - complaintIdToTitle.put("104", "Broken Bin"); - complaintIdToTitle.put("105", "Shifting of Garbage Bin"); - complaintIdToTitle.put("106", "Cleaning of Water Table"); - complaintIdToTitle.put("107", "Nuisance by Garbage Tractor/Truck"); - complaintIdToTitle.put("108", "Burning of Garbage"); - complaintIdToTitle.put("109", "Garbage Lorry without Net"); - complaintIdToTitle.put("110", "Spilling of Garbage from Lorry"); - complaintIdToTitle.put("111", "Burning of Garbage at Dumping Ground"); - complaintIdToTitle.put("112", "Pot hole fill up / Repairs to the damaged surface"); - complaintIdToTitle.put("113", "Relaying of Road"); - complaintIdToTitle.put("114", "Formation of New Road"); - complaintIdToTitle.put("115", "Repairs to existing Footpath"); - complaintIdToTitle.put("116", "Request to provide Footpath"); - complaintIdToTitle.put("117", "Removal of Shops in the Footpath"); - complaintIdToTitle.put("118", "Mosquito Menace"); - complaintIdToTitle.put("119", "Street Dogs"); - complaintIdToTitle.put("120", "Stray Cattle"); - complaintIdToTitle.put("121", "Stray Pigs"); - complaintIdToTitle.put("122", "Death of Stray Animals"); - complaintIdToTitle.put("123", "Public Health / Dengue / Malaria / Gastro Enteritis"); - complaintIdToTitle.put("124", "Transfer Station Smell"); - complaintIdToTitle.put("125", "Flies Menace from Dumping Ground"); - complaintIdToTitle.put("126", "Open Defecation"); - complaintIdToTitle.put("127", "Illegal Draining of Sewage to SWD / Open Site"); - complaintIdToTitle.put("128", "Complaints regarding unhygenic Restaurants"); - complaintIdToTitle.put("129", "Complaints regarding quality of food in hotels"); - complaintIdToTitle.put("130", "Road Side Eateries"); - complaintIdToTitle.put("131", "Slaughter House related complaints"); - complaintIdToTitle.put("132", "Unauthorized Sale of Meat and Meat products"); - complaintIdToTitle.put("133", "Illegal Slaughtering"); - complaintIdToTitle.put("134", "Unhygenic and Improper Transport of Meat and Livestock"); - complaintIdToTitle.put("135", "Biomedical waste / Health hazard waste removal"); - complaintIdToTitle.put("136", "Complaints regarding Corporation Hospitals"); - complaintIdToTitle.put("137", "Complaints regarding CDH"); - complaintIdToTitle.put("138", "Stagnation of Water"); - complaintIdToTitle.put("139", "Obstruction of Water Flow"); - complaintIdToTitle.put("140", "Desilting of Drain"); - complaintIdToTitle.put("141", "Desilting of Canal"); - complaintIdToTitle.put("142", "Repairs to Storm Water Drain"); - complaintIdToTitle.put("143", "Covering Manholes of Storm Water Drain"); - complaintIdToTitle.put("144", "New Drain Construction"); - complaintIdToTitle.put("145", "Disposal of Removed Silt on the Road"); - complaintIdToTitle.put("146", "Non burning of Street lights"); - complaintIdToTitle.put("147", "Electric shock due to street light"); - complaintIdToTitle.put("148", "Damage to the Electric pole"); - complaintIdToTitle.put("149", "New Street lights"); - complaintIdToTitle.put("150", "Shifting of Street light pole"); - complaintIdToTitle.put("151", "Overhead cable wires running in a haphazard manner"); - complaintIdToTitle.put("152", "Removal of Fallen Trees"); - complaintIdToTitle.put("153", "Complaints regarding Park"); - complaintIdToTitle.put("154", "Complaints regarding Playground"); - complaintIdToTitle.put("155", "Complaints regarding Centre Median"); - complaintIdToTitle.put("156", "Complaints regarding Traffic Island"); - complaintIdToTitle.put("157", "Unauthorized Tree Cutting"); - complaintIdToTitle.put("158", "Obstruction of Trees"); - complaintIdToTitle.put("159", "Complaints regarding Public Toilets"); - complaintIdToTitle.put("160", "Complaints regarding Free Usage of Public Toilets"); - complaintIdToTitle.put("161", "Complaints regarding Cleanliness of Toilets in Theatre"); - complaintIdToTitle.put("162", "Complaints regarding Cleanliness of Toilets in Shopping Complex"); - complaintIdToTitle.put("163", "Building Plan Sanction"); - complaintIdToTitle.put("164", "Violation of DCR/Building By laws"); - complaintIdToTitle.put("165", "Unauthorized / Illegal Construction"); - complaintIdToTitle.put("166", "Complaints related to Property Tax"); - complaintIdToTitle.put("167", "Complaints related to Professional Tax"); - complaintIdToTitle.put("168", "Complaints related to Trade Licence"); - complaintIdToTitle.put("174", "Name Error (Spelling Related)"); - complaintIdToTitle.put("175", "Change of Address in Electoral Roll"); - complaintIdToTitle.put("176", "Issue of Voter ID"); - complaintIdToTitle.put("177", "Inclusion, Deletion, Correction in Voter List"); - complaintIdToTitle.put("178", "Complaints regarding Voter List"); - complaintIdToTitle.put("179", "Name not found in the Electoral Roll"); - complaintIdToTitle.put("180", "Issue of Birth and Death Certificate"); - complaintIdToTitle.put("181", "Encroachment on the Public Property"); - complaintIdToTitle.put("182", " Complaints related to Schools"); - complaintIdToTitle.put("183", "Sanction of Financial Assistance under Moovalaur Thirumana Thittam"); - complaintIdToTitle.put("184", "Complaints related to issue of all types of Registration Certificate"); - complaintIdToTitle.put("185", "Slow Progress of Work"); - complaintIdToTitle.put("186", "Poor Quality of Work"); - complaintIdToTitle.put("187", "Unauthorized Advertisement Boards"); - complaintIdToTitle.put("188", "Complaints regarding Bridges / Flyovers / Subways"); - complaintIdToTitle.put("189", "Complaints related Shopping Complex"); - complaintIdToTitle.put("190", "Complaints regarding Community Hall"); - complaintIdToTitle.put("191", "Complaints regarding Burial Ground"); - complaintIdToTitle.put("192", "Complaints regarding any other CoC building"); - complaintIdToTitle.put("193", "Parking Issue"); - complaintIdToTitle.put("195", "Complaints Regarding Plastics"); - complaintIdToTitle.put("196", "No electricity in public toilet"); - complaintIdToTitle.put("197", "No water supply in public toilet"); - complaintIdToTitle.put("198", "Public toilet blockage"); - complaintIdToTitle.put("199", "Public toilet cleaning"); - complaintIdToTitle.put("200", "Burning of street light in daytime"); - complaintIdToTitle.put("201", "Illegal Parking on foot path"); - complaintIdToTitle.put("202", "Complaints regarding non availability of Doctors"); - complaintIdToTitle.put("203", "Complaints regarding non availability of medicines"); - complaintIdToTitle.put("204", "Complaints regarding laboratory issues"); - complaintIdToTitle.put("205", "Issues regarding amma baby care kits (After Delivery)"); - complaintIdToTitle.put("206", "Issues regarding Amma nutrition kit for pregnant woman"); - complaintIdToTitle.put("207", "Issues regarding Muthulakshmi Reddy Maternity Benefit Scheme (MRMBS)"); - complaintIdToTitle.put("208", "Issues regarding janani suraksha yojana scheme (JSY)"); - complaintIdToTitle.put("209", "Travel pass related complaints"); - complaintIdToTitle.put("210", "Food related complaints"); - complaintIdToTitle.put("212", "Covid Health Related Queries"); - complaintIdToTitle.put("213", "Hospital and Covid care centre(CCC) Related Queries"); - complaintIdToTitle.put("214", "Medical Emergencies"); - complaintIdToTitle.put("215", "Essentials and Medicines"); - complaintIdToTitle.put("216", "PSYCHO-SOCIO support"); - complaintIdToTitle.put("218", "Quarantine and isolation Related Queries"); - complaintIdToTitle.put("219", "General Health Queries"); - complaintIdToTitle.put("220", "Disinfection request"); - complaintIdToTitle.put("221", "Non Covid Health Related Queries"); - complaintIdToTitle.put("222", "Milling/Scraping of Road before Relaying of Road"); - complaintIdToTitle.put("226", "Food Requirement"); - complaintIdToTitle.put("227", "Relief Center Requirement"); - complaintIdToTitle.put("228", "Covid19 Ambulance Service"); - complaintIdToTitle.put("229", "Air Quality"); - complaintIdToTitle.put("230", "Online Payment Issue"); - complaintIdToTitle.put("231", "General Revision Objection"); - complaintIdToTitle.put("232", "Water Mixed with Sewarage"); - complaintIdToTitle.put("233", "Sewerage Overflow"); - complaintIdToTitle.put("234", "Drinking water supply"); - complaintIdToTitle.put("235", "Electricity Shock"); - complaintIdToTitle.put("236", "Electricity Unavailability"); - complaintIdToTitle.put("237", "Insufficient Barricading"); - complaintIdToTitle.put("238", "Fallen poles/towers/hoardings/other infra"); - complaintIdToTitle.put("239", "Fallen EB cables"); - complaintIdToTitle.put("240", "Project information not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("241", "Project information not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("242", "Project information not provided (MC Road)"); - complaintIdToTitle.put("243", "Project information not provided (Washermenpet Metro)"); - complaintIdToTitle.put("244", "Project information not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("245", "Project information not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("246", "Advance information on consultation not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("247", "Advance information on consultation not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("248", "Advance information on consultation not provided (MC Road)"); - complaintIdToTitle.put("249", "Advance information on consultation not provided (Washermenpet Metro)"); - complaintIdToTitle.put("250", "Advance information on consultation not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("251", "Advance information on consultation not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("252", "Location and area of consultation not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("253", "Location and area of consultation not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("254", "Location and area of consultation not provided (MC Road)"); - complaintIdToTitle.put("255", "Location and area of consultation not provided (Washermenpet Metro)"); - complaintIdToTitle.put("256", "Location and area of consultation not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("257", "Location and area of consultation not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("258", "Information on detailed work plan not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("259", "Information on detailed work plan not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("260", "Information on detailed work plan not provided (MC Road)"); - complaintIdToTitle.put("261", "Information on detailed work plan not provided (Washermenpet Metro)"); - complaintIdToTitle.put("262", "Information on detailed work plan not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("263", "Information on detailed work plan not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("264", "Others (Thiruvotriyur High Road)"); - complaintIdToTitle.put("265", "Others (Arunachaleshwar Road)"); - complaintIdToTitle.put("266", "Others (MC Road)"); - complaintIdToTitle.put("267", "Others (Washermenpet Metro)"); - complaintIdToTitle.put("268", "Others (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("269", "Others (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("270", "No information in advance provided on the date and time of civil works (Thiruvotriyur High Road)"); - complaintIdToTitle.put("271", "No information in advance provided on the date and time of civil works (Arunachaleshwar Road)"); - complaintIdToTitle.put("272", "No information in advance provided on the date and time of civil works (MC Road)"); - complaintIdToTitle.put("273", "No information in advance provided on the date and time of civil works (Washermenpet Metro)"); - complaintIdToTitle.put("274", "No information in advance provided on the date and time of civil works (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("275", "No information in advance provided on the date and time of civil works (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("276", "No information provided on the nature and schedule of civil work (Thiruvotriyur High Road)"); - complaintIdToTitle.put("277", "No information provided on the nature and schedule of civil work (Arunachaleshwar Road)"); - complaintIdToTitle.put("278", "No information provided on the nature and schedule of civil work (MC Road)"); - complaintIdToTitle.put("279", "No information provided on the nature and schedule of civil work (Washermenpet Metro)"); - complaintIdToTitle.put("280", "No information provided on the nature and schedule of civil work (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("281", "No information provided on the nature and schedule of civil work (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("282", "No consultation carried out with the people affected by the civil works (Thiruvotriyur High Road)"); - complaintIdToTitle.put("283", "No consultation carried out with the people affected by the civil works (Arunachaleshwar Road)"); - complaintIdToTitle.put("284", "No consultation carried out with the people affected by the civil works (MC Road)"); - complaintIdToTitle.put("285", "No consultation carried out with the people affected by the civil works (Washermenpet Metro)"); - complaintIdToTitle.put("286", "No consultation carried out with the people affected by the civil works (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("287", "No consultation carried out with the people affected by the civil works (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("288", "No arrangement made for temporary displacement (Thiruvotriyur High Road)"); - complaintIdToTitle.put("289", "No arrangement made for temporary displacement (Arunachaleshwar Road)"); - complaintIdToTitle.put("290", "No arrangement made for temporary displacement (MC Road)"); - complaintIdToTitle.put("291", "No arrangement made for temporary displacement (Washermenpet Metro)"); - complaintIdToTitle.put("292", "No arrangement made for temporary displacement (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("293", "No arrangement made for temporary displacement (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("294", "No display board on the project installed at work site (Thiruvotriyur High Road)"); - complaintIdToTitle.put("295", "No display board on the project installed at work site (Arunachaleshwar Road)"); - complaintIdToTitle.put("296", "No display board on the project installed at work site (MC Road)"); - complaintIdToTitle.put("297", "No display board on the project installed at work site (Washermenpet Metro)"); - complaintIdToTitle.put("298", "No display board on the project installed at work site (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("299", "No display board on the project installed at work site (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("300", "Temporary access to structures not provided and or not adequate (Thiruvotriyur High Road)"); - complaintIdToTitle.put("301", "Temporary access to structures not provided and or not adequate (Arunachaleshwar Road)"); - complaintIdToTitle.put("302", "Temporary access to structures not provided and or not adequate (MC Road)"); - complaintIdToTitle.put("303", "Temporary access to structures not provided and or not adequate (Washermenpet Metro)"); - complaintIdToTitle.put("304", "Temporary access to structures not provided and or not adequate (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("305", "Temporary access to structures not provided and or not adequate (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("306", "No safety measures taken at worksite (Thiruvotriyur High Road)"); - complaintIdToTitle.put("307", "No safety measures taken at worksite (Arunachaleshwar Road)"); - complaintIdToTitle.put("308", "No safety measures taken at worksite (MC Road)"); - complaintIdToTitle.put("309", "No safety measures taken at worksite (Washermenpet Metro)"); - complaintIdToTitle.put("310", "No safety measures taken at worksite (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("311", "No safety measures taken at worksite (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("312", "Water supply disrupted and alternate arrangement not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("313", "Water supply disrupted and alternate arrangement not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("314", "Water supply disrupted and alternate arrangement not provided (MC Road)"); - complaintIdToTitle.put("315", "Water supply disrupted and alternate arrangement not provided (Washermenpet Metro)"); - complaintIdToTitle.put("316", "Water supply disrupted and alternate arrangement not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("317", "Water supply disrupted and alternate arrangement not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("318", "Electricity supply disrupted and alternate arrangement not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("319", "Electricity supply disrupted and alternate arrangement not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("320", "Electricity supply disrupted and alternate arrangement not provided (MC Road)"); - complaintIdToTitle.put("321", "Electricity supply disrupted and alternate arrangement not provided (Washermenpet Metro)"); - complaintIdToTitle.put("322", "Electricity supply disrupted and alternate arrangement not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("323", "Electricity supply disrupted and alternate arrangement not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("324", "Disposal of debris not appropriately managed (Thiruvotriyur High Road)"); - complaintIdToTitle.put("325", "Disposal of debris not appropriately managed (Arunachaleshwar Road)"); - complaintIdToTitle.put("326", "Disposal of debris not appropriately managed (MC Road)"); - complaintIdToTitle.put("327", "Disposal of debris not appropriately managed (Washermenpet Metro)"); - complaintIdToTitle.put("328", "Disposal of debris not appropriately managed (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("329", "Disposal of debris not appropriately managed (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("330", " Temporary arrangement for parking not provided (Thiruvotriyur High Road)"); - complaintIdToTitle.put("331", " Temporary arrangement for parking not provided (Arunachaleshwar Road)"); - complaintIdToTitle.put("332", " Temporary arrangement for parking not provided (MC Road)"); - complaintIdToTitle.put("333", " Temporary arrangement for parking not provided (Washermenpet Metro)"); - complaintIdToTitle.put("334", " Temporary arrangement for parking not provided (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("335", " Temporary arrangement for parking not provided (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("336", "GRM and helpline numbers not displayed at worksite (Thiruvotriyur High Road)"); - complaintIdToTitle.put("337", "GRM and helpline numbers not displayed at worksite (Arunachaleshwar Road)"); - complaintIdToTitle.put("338", "GRM and helpline numbers not displayed at worksite (MC Road)"); - complaintIdToTitle.put("339", "GRM and helpline numbers not displayed at worksite (Washermenpet Metro)"); - complaintIdToTitle.put("340", "GRM and helpline numbers not displayed at worksite (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("341", "GRM and helpline numbers not displayed at worksite (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("342", "Drinking water/ other basic needs for Labour not available at worksite (Thiruvotriyur High Road)"); - complaintIdToTitle.put("343", "Drinking water/ other basic needs for Labour not available at worksite (Arunachaleshwar Road)"); - complaintIdToTitle.put("344", "Drinking water/ other basic needs for Labour not available at worksite (MC Road)"); - complaintIdToTitle.put("345", "Drinking water/ other basic needs for Labour not available at worksite (Washermenpet Metro)"); - complaintIdToTitle.put("346", "Drinking water/ other basic needs for Labour not available at worksite (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("347", "Drinking water/ other basic needs for Labour not available at worksite (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("348", "Noise levels are very high (Thiruvotriyur High Road)"); - complaintIdToTitle.put("349", "Noise levels are very high (Arunachaleshwar Road)"); - complaintIdToTitle.put("350", "Noise levels are very high (MC Road)"); - complaintIdToTitle.put("351", "Noise levels are very high (Washermenpet Metro)"); - complaintIdToTitle.put("352", "Noise levels are very high (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("353", "Noise levels are very high (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("354", " Sprinkling of water at worksite not carried out (Thiruvotriyur High Road)"); - complaintIdToTitle.put("355", " Sprinkling of water at worksite not carried out (Arunachaleshwar Road)"); - complaintIdToTitle.put("356", " Sprinkling of water at worksite not carried out (MC Road)"); - complaintIdToTitle.put("357", " Sprinkling of water at worksite not carried out (Washermenpet Metro)"); - complaintIdToTitle.put("358", " Sprinkling of water at worksite not carried out (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("359", " Sprinkling of water at worksite not carried out (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("360", "The worksite is not barricaded; (Thiruvotriyur High Road)"); - complaintIdToTitle.put("361", "The worksite is not barricaded; (Arunachaleshwar Road)"); - complaintIdToTitle.put("362", "The worksite is not barricaded; (MC Road)"); - complaintIdToTitle.put("363", "The worksite is not barricaded; (Washermenpet Metro)"); - complaintIdToTitle.put("364", "The worksite is not barricaded; (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("365", "The worksite is not barricaded; (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("366", " No information on number of labour working at the site (Thiruvotriyur High Road)"); - complaintIdToTitle.put("367", " No information on number of labour working at the site (Arunachaleshwar Road)"); - complaintIdToTitle.put("368", " No information on number of labour working at the site (MC Road)"); - complaintIdToTitle.put("369", " No information on number of labour working at the site (Washermenpet Metro)"); - complaintIdToTitle.put("370", " No information on number of labour working at the site (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("371", " No information on number of labour working at the site (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("372", "Labourer not using the safety equipment (Thiruvotriyur High Road)"); - complaintIdToTitle.put("373", "Labourer not using the safety equipment (Arunachaleshwar Road)"); - complaintIdToTitle.put("374", "Labourer not using the safety equipment (MC Road)"); - complaintIdToTitle.put("375", "Labourer not using the safety equipment (Washermenpet Metro)"); - complaintIdToTitle.put("376", "Labourer not using the safety equipment (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("377", "Labourer not using the safety equipment (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("378", "Sewerage pipe is damaged (Thiruvotriyur High Road)"); - complaintIdToTitle.put("379", "Sewerage pipe is damaged (Arunachaleshwar Road)"); - complaintIdToTitle.put("380", "Sewerage pipe is damaged (MC Road)"); - complaintIdToTitle.put("381", "Sewerage pipe is damaged (Washermenpet Metro)"); - complaintIdToTitle.put("382", "Sewerage pipe is damaged (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("383", "Sewerage pipe is damaged (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("384", "Others (Thiruvotriyur High Road)"); - complaintIdToTitle.put("385", "Others (Arunachaleshwar Road)"); - complaintIdToTitle.put("386", "Others (MC Road)"); - complaintIdToTitle.put("387", "Others (Washermenpet Metro)"); - complaintIdToTitle.put("388", "Others (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("389", "Others (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("390", "Insufficient Barricading (Thiruvotriyur High Road)"); - complaintIdToTitle.put("391", "Insufficient Barricading (Arunachaleshwar Road)"); - complaintIdToTitle.put("392", "Insufficient Barricading (MC Road)"); - complaintIdToTitle.put("393", "Insufficient Barricading (Washermenpet Metro)"); - complaintIdToTitle.put("394", "Insufficient Barricading (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("395", "Insufficient Barricading (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("396", "Non Removal of Debris (Thiruvotriyur High Road)"); - complaintIdToTitle.put("397", "Non Removal of Debris (Arunachaleshwar Road)"); - complaintIdToTitle.put("398", "Non Removal of Debris (MC Road)"); - complaintIdToTitle.put("399", "Non Removal of Debris (Washermenpet Metro)"); - complaintIdToTitle.put("400", "Non Removal of Debris (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("401", "Non Removal of Debris (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("402", "Potholes fill up (Thiruvotriyur High Road)"); - complaintIdToTitle.put("403", "Potholes fill up (Arunachaleshwar Road)"); - complaintIdToTitle.put("404", "Potholes fill up (MC Road)"); - complaintIdToTitle.put("405", "Potholes fill up (Washermenpet Metro)"); - complaintIdToTitle.put("406", "Potholes fill up (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("407", "Potholes fill up (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("408", "Damage to utilities (TNEB, CMWSSB, BSNL) (Thiruvotriyur High Road)"); - complaintIdToTitle.put("409", "Damage to utilities (TNEB, CMWSSB, BSNL) (Arunachaleshwar Road)"); - complaintIdToTitle.put("410", "Damage to utilities (TNEB, CMWSSB, BSNL) (MC Road)"); - complaintIdToTitle.put("411", "Damage to utilities (TNEB, CMWSSB, BSNL) (Washermenpet Metro)"); - complaintIdToTitle.put("412", "Damage to utilities (TNEB, CMWSSB, BSNL) (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("413", "Damage to utilities (TNEB, CMWSSB, BSNL) (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("414", "Encroaching Public Space (Thiruvotriyur High Road)"); - complaintIdToTitle.put("415", "Encroaching Public Space (Arunachaleshwar Road)"); - complaintIdToTitle.put("416", "Encroaching Public Space (MC Road)"); - complaintIdToTitle.put("417", "Encroaching Public Space (Washermenpet Metro)"); - complaintIdToTitle.put("418", "Encroaching Public Space (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("419", "Encroaching Public Space (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("420", "Need Pathway ramp (Thiruvotriyur High Road)"); - complaintIdToTitle.put("421", "Need Pathway ramp (Arunachaleshwar Road)"); - complaintIdToTitle.put("422", "Need Pathway ramp (MC Road)"); - complaintIdToTitle.put("423", "Need Pathway ramp (Washermenpet Metro)"); - complaintIdToTitle.put("424", "Need Pathway ramp (Khadar Nawas Khan Road)"); - complaintIdToTitle.put("425", "Need Pathway ramp (Race Course road + Guindy MMI)"); - complaintIdToTitle.put("426", "Cleanliness in Parks"); - complaintIdToTitle.put("427", "Greenary in Parks"); - complaintIdToTitle.put("428", "Play Equipment"); - complaintIdToTitle.put("429", "Opening and closing hours"); - complaintIdToTitle.put("430", "Toilets in parks"); - complaintIdToTitle.put("431", "Non functional lights/ no lights in parks"); - complaintIdToTitle.put("432", "Safety in parks/playgrounds"); - complaintIdToTitle.put("433", "Women related safety issues in parks"); - complaintIdToTitle.put("434", "Availability or cleanliness of dustbins in public toilets"); - complaintIdToTitle.put("435", "Cleanliness/ water supply in toilets"); - complaintIdToTitle.put("436", "Broken sinks, toilets or urinals and doors"); - complaintIdToTitle.put("437", "Request for new toilet"); - complaintIdToTitle.put("438", "Illegal activities in toilet"); - complaintIdToTitle.put("439", "Toilets not in use/ closed"); - complaintIdToTitle.put("440", "Inadequate lighting in and around the toilet"); - complaintIdToTitle.put("441", "Safety in public toilets"); - complaintIdToTitle.put("442", "Cleanliness in footpath"); - complaintIdToTitle.put("443", "Electrical wires/obstruction on footpath"); - complaintIdToTitle.put("444", "Unsafe dark spots/ corners"); - complaintIdToTitle.put("445", "Public defecation/urination"); - complaintIdToTitle.put("446", "Women related safety issues"); - complaintIdToTitle.put("447", "Inadequate light in a particular location or spot/ dark spots"); - - String expectedType; - if (complaintIdToTitle.containsKey(complaintId)) { - expectedType = complaintIdToTitle.get(complaintId).trim().toLowerCase(); - } else { - // Fallback: Use sub-type text directly if not found in map (i.e. for "Others") - expectedType = complaintId.trim().toLowerCase(); - } - - // 2. Date range: last 7 days - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); - LocalDate today = LocalDate.now(); - String endDate = today.format(formatter); - String startDate = today.minusDays(7).format(formatter); - int repYear = today.getYear(); - - // 3. Construct external URL - String externalUrl = String.format( - "https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintListWithImg" + - "&From_date=%s&To_date=%s&jsonResp=Yes&UserType=Public&Token=&PageIndex=null&Status=null&repYear=%d&MobileNo=%s", - startDate, endDate, repYear, mobileNo - ); - - System.out.println("External API URL: " + externalUrl); - - // 4. Fetch and parse response - RestTemplate restTemplate = new RestTemplate(); - String json = restTemplate.getForObject(externalUrl, String.class); - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootArray = mapper.readTree(json); - - boolean found = false; - - if (rootArray.isArray() && rootArray.size() > 0) { - JsonNode complaintList = rootArray.get(0).path("ComplaintListHistory"); - - if (complaintList.isArray()) { - for (JsonNode item : complaintList) { - String type = item.path("complainttype").asText("").trim().toLowerCase(); - String street = item.path("Street").asText("").trim().toLowerCase(); - - if (type.equals(expectedType) && - street.equals(streetName.trim().toLowerCase())) { - found = true; - break; - } - } - } - } - - // 5. Return response - Map response = new HashMap<>(); - response.put("duplicate", found); - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to process the request")); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintStatusMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintStatusMainController.java deleted file mode 100644 index afa38758..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintStatusMainController.java +++ /dev/null @@ -1,31 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/callcenterqaqccomplaintstatus") -@Controller("callCenterQaQcComplaintStatusController") -public class ComplaintStatusMainController { - - @GetMapping("/complaintstatus") - public String viewstatuscheck(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - - return "modules/callcenterqaqc/complaintstatus"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/DomesticWasteApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/DomesticWasteApiController.java deleted file mode 100644 index 1cac4f93..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/DomesticWasteApiController.java +++ /dev/null @@ -1,278 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; -import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.core.type.TypeReference; - - - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.DomesticWasteService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RestController -@RequestMapping("/gcc/api/domestic_waste") -public class DomesticWasteApiController { - - @Autowired - private AppConfig appConfig; - - @Autowired - private RestTemplate restTemplate; - - @Autowired - private DomesticWasteService domesticWasteService; - - - - - @GetMapping("/getitems") - public ResponseEntity> getItemsList() { - String apiUrl = appConfig.domesticurl + "/get-all-masters"; - Map responseMap = new HashMap<>(); - - try { - String response = restTemplate.getForObject(apiUrl, String.class); - - responseMap.put("status", "success"); - responseMap.put("data", new ObjectMapper().readValue(response, Object.class)); // parse JSON array into list - return ResponseEntity.ok(responseMap); - - } catch (HttpClientErrorException | HttpServerErrorException ex) { - responseMap.put("status", "error"); - responseMap.put("code", ex.getStatusCode().value()); - responseMap.put("message", ex.getStatusText()); - responseMap.put("details", ex.getResponseBodyAsString()); - return ResponseEntity.status(ex.getStatusCode()).body(responseMap); - - } catch (ResourceAccessException ex) { - responseMap.put("status", "error"); - responseMap.put("code", HttpStatus.SERVICE_UNAVAILABLE.value()); - responseMap.put("message", "Service unavailable"); - responseMap.put("details", ex.getMessage()); - return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(responseMap); - - } catch (Exception ex) { - responseMap.put("status", "error"); - responseMap.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value()); - responseMap.put("message", "Unexpected error"); - responseMap.put("details", ex.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseMap); - } - } - - @PostMapping("/saverequest") - public ResponseEntity saveRequest( - @RequestParam String user_name, - @RequestParam String mobile, - @RequestParam String address, - @RequestParam String latitude, - @RequestParam String longitude, - @RequestParam String street_name, - @RequestParam String street_id, - @RequestParam String remarks, - @RequestParam("items") String itemsJson, - @RequestParam String userId,@RequestParam String zone,@RequestParam String ward) { - - try { - Map result = domesticWasteService.saveMultipleWasteRequests( - user_name, mobile, address, - latitude, longitude, - street_name, street_id, remarks, - itemsJson,userId,zone,ward - ); - - return ResponseEntity.ok(result); - - } catch (Exception e) { - return ResponseEntity.status(500).body(Map.of("status", false, "message", e.getMessage())); - } - } - - @GetMapping("/getalldomesticwastelist") - public Map getFilterReports( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate, - @RequestParam(required = false) String mobile, - @RequestParam(required = false) String requestId) { - Map response = new HashMap<>(); - - try { - System.out.println("startDate="+startDate); - System.out.println("endDate="+endDate); - System.out.println("mobile="+mobile); - System.out.println("requestId="+requestId); - - List> details =domesticWasteService.getAllComplaintsList(startDate,endDate,mobile,requestId) ; - System.out.println(details); - if (details == null || details.isEmpty()) { - response.put("status", "nodata"); - response.put("message", "No Data"); - } - else { - response.put("status", "success"); - response.put("details", details); - } - - } - catch (Exception e) { - response.put("status", "error"); - response.put("message", "An error occurred while fetching data."); - e.printStackTrace(); - } - - return response; - } - - - - @GetMapping("/checkstatusbymobile") - public Map getStatusByMobileNumber( - @RequestParam(required = false) String mobile) { - - Map response = new HashMap<>(); - try { - System.out.println("mobile=" + mobile); - - // Construct external API URL - String url = appConfig.domesticurl + "/get-user-bymobile?mobile=" + mobile; - - // Call the external API - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity apiResponse = restTemplate.getForEntity(url, String.class); - - if (apiResponse.getStatusCode().is2xxSuccessful() && apiResponse.getBody() != null) { - ObjectMapper mapper = new ObjectMapper(); - - // Convert JSON string to List of Maps - List> itemsList = mapper.readValue(apiResponse.getBody(), - new TypeReference>>() {}); - - if (itemsList.isEmpty()) { - response.put("status", "no data"); - response.put("data", Collections.emptyList()); - } else { - response.put("status", "success"); - response.put("data", itemsList); - } - } else { - response.put("status", "no data"); - response.put("data", Collections.emptyList()); - } - - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - - - @GetMapping("/getpendingcomplaints") - public Map getpendingcomplaints( - @RequestParam String startDate, - @RequestParam String endDate, - @RequestParam (required = false) String mobile) { - - Map response = new HashMap<>(); - try { - - List> list = domesticWasteService.getpendingcomplaints(startDate,endDate,mobile); - - if (!list.isEmpty()) { - - response.put("status", "success"); - response.put("data", list); - - } else { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } - - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - @GetMapping("/getDetailsByReqId") - public Map getDetailsByReqId( - @RequestParam String requestId) { - - Map response = new HashMap<>(); - try { - - List> list = domesticWasteService.getDetailsByReqId(requestId); - - if (!list.isEmpty()) { - - response.put("status", "success"); - response.put("data", list); - - } else { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } - - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - @PostMapping("/cancelbyagents") - public ResponseEntity> saveAnswer(@RequestParam String requestId,@RequestParam String remarks,@RequestParam String userId) { - Map response = new HashMap<>(); - - try { - boolean success = domesticWasteService.changeStatus(requestId,remarks,userId); - if (success) { - response.put("status", "success"); - response.put("message", "Complaint cancelled successfully!"); - return ResponseEntity.ok(response); - } else { - response.put("status", "error"); - response.put("message", "Fail to Update."); - return ResponseEntity.status(500).body(response); - } - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", "Exception: " + e.getMessage()); - return ResponseEntity.status(500).body(response); - } - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/DomesticWasteMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/DomesticWasteMainController.java deleted file mode 100644 index e31e7060..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/DomesticWasteMainController.java +++ /dev/null @@ -1,73 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAgentsService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/domestic_waste") -@Controller("callCenterDomesticWasteController") -public class DomesticWasteMainController { - - @Autowired - private QaqcAgentsService agentsService; - - @GetMapping("/registerpage") - public String viewDomesticWastepage(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId",userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - return "modules/callcenterqaqc/domesticwastecomplaints"; - } - - - @GetMapping("/checkstatus") - public String viewComplaintspage(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId",userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - return "modules/callcenterqaqc/domesticwastecheckstatus"; - } - - @GetMapping("/cancelpage") - public String viewpendingpage(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId",userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - return "modules/callcenterqaqc/domesticwastecancel"; - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java deleted file mode 100644 index d10381aa..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java +++ /dev/null @@ -1,85 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.FollowUpService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcCallsService; - -@RequestMapping("gcc/api/callcenterqaqc/agent/followupcalls") -@RestController -public class FollowUpController { - - @Autowired - RestTemplate restTemplate; - - @Autowired - private QaqcCallsService qaqcCallsService; - - @Autowired - private FollowUpService followService; - - @PostMapping("/update") - @ResponseBody - public ResponseEntity updateCallDetails(@RequestParam("complaintNumber") String complaintNumber, - @RequestParam("dataId") int dataId, - @RequestParam("userId") String userId, - @RequestParam("action") String action, - @RequestParam(value = "remainderDate", required = false,defaultValue = "-") String remainderDate, - @RequestParam("remarks") String remarks) { - try { -// System.out.println("Updating Complaint Number: " + complaintNumber); -// System.out.println("Updating Data ID: " + dataId); -// System.out.println("Action: " + action); -// System.out.println("Remarks: " + remarks); - int updated_agent = Integer.parseInt(userId); -// System.out.println("updated_agent: " + updated_agent); - - Map complaintDetails = qaqcCallsService.getComplaintDetails(dataId); - - Integer agentId = (Integer) complaintDetails.get("agent_id"); - Map erp_username=qaqcCallsService.getErpnameById(agentId); - String Erpname=(String) erp_username.get("erp_username"); - - if ("WRONG_ASSIGN".equals(action)) { - - boolean statusUpdated = qaqcCallsService.ChangeStatusInErp(complaintNumber, remarks, action, Erpname); - - if (!statusUpdated) { - return ResponseEntity.ok("error"); - } - } - - // Update complaint details - followService.updateFollowupComplaintDetails(complaintNumber, dataId, action, remarks,updated_agent); - followService.updateComplaintHistoryDetails(complaintNumber, dataId, action, remarks,updated_agent, remainderDate); - - Map logDetails = qaqcCallsService.getComplaintDetails(dataId); - // Upload to logs - followService.uploadComplaintDetailsInLogs(logDetails, action, complaintNumber,remainderDate); - - return ResponseEntity.ok("Success"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - } - - @GetMapping("/getoffsubmittedcalls") - public List> getFollowupSubmitDetails(@RequestParam int userId) - { - return followService.getFollowupSubmitDetails(userId); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/InprogresscallController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/InprogresscallController.java deleted file mode 100644 index 58a9373c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/InprogresscallController.java +++ /dev/null @@ -1,96 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.InprogresscallService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcCallsService; - -@RequestMapping("gcc/api/callcenterqaqc/agent/inprogresscalls") -@RestController - -public class InprogresscallController { - - @Autowired - InprogresscallService inprogresscallService; - - @Autowired - RestTemplate restTemplate; - - @Autowired - private QaqcCallsService qaqcCallsService; - - @PostMapping("/update") - @ResponseBody - public ResponseEntity updateCallDetails(@RequestParam("complaintNumber") String complaintNumber, - @RequestParam("dataId") int dataId, - @RequestParam("userId") String userId, - @RequestParam("action") String action, - @RequestParam(value = "remainderDate", required = false,defaultValue = "-") String remainderDate, - @RequestParam("remarks") String remarks) { - try { -// System.out.println("Updating Complaint Number: " + complaintNumber); -// System.out.println("Updating Data ID: " + dataId); -// System.out.println("Action: " + action); -// System.out.println("Remarks: " + remarks); - int updated_agent = Integer.parseInt(userId); -// System.out.println("updated_agent: " + updated_agent); - - //to insert incorrect office mobile number details in table - if (action.equals("MOBILE_NUM")) { - inprogresscallService.saveMobileNumDetails(complaintNumber, remarks); - } - - Map complaintDetails = qaqcCallsService.getComplaintDetails(dataId); - - Integer agentId = (Integer) complaintDetails.get("agent_id"); - Map erp_username=qaqcCallsService.getErpnameById(agentId); - String Erpname=(String) erp_username.get("erp_username"); - - if ("WRONG_ASSIGN".equals(action)) { - - boolean statusUpdated = qaqcCallsService.ChangeStatusInErp(complaintNumber, remarks, action, Erpname); - - if (!statusUpdated) { - return ResponseEntity.ok("error"); - } - } - - // Update complaint details - inprogresscallService.updateInprogressComplaintDetails(complaintNumber, dataId, action, remarks,updated_agent); - inprogresscallService.updateComplaintHistoryDetails(complaintNumber, dataId, action, remarks,updated_agent, remainderDate); - Map logDetails = qaqcCallsService.getComplaintDetails(dataId); - // Upload to logs - qaqcCallsService.uploadComplaintDetailsInLogs(logDetails, action, complaintNumber,remainderDate); - - return ResponseEntity.ok("Success"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - } - - @GetMapping("/getinprogresssubmittedcalls") - public List> getInprogressSubmitDetails(@RequestParam int userId) - { - return inprogresscallService.getInprogressSubmitDetails(userId); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java deleted file mode 100644 index 96cdfb0e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java +++ /dev/null @@ -1,370 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.time.LocalDate; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -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.ResponseBody; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.FollowUpService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.InprogresscallService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.PublicFollowUpService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAdminSettingService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAgentsService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcCallsService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcService; -import in.gov.chennaicorporation.gccoffice.entity.AppUserEntity; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - - -@RequestMapping("/gcc/callcenterqaqc") -@Controller("callCenterQaQcMainController") -public class MainController { - - @Autowired - private QaqcService qaqcService; - - @Autowired - private QaqcAgentsService agentsService; - - @Autowired - private QaqcAdminSettingService adminService; - - @Autowired - private InprogresscallService inprogresscallService; - - @Autowired - private QaqcCallsService qaqcCallsService; - - @Autowired - private FollowUpService followUpService; - - @Autowired - private PublicFollowUpService publicService; - - - @GetMapping("/admin/qaqcgrievancedashboard") - public String viewqaqcdashboard(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - List> previousday=agentsService.getPreviousDayDashboardCounts(); - model.addAttribute("previousday", previousday); - //System.out.println(previousday); - - List> agentcount=agentsService.getAgentPreviousDayCount(); - model.addAttribute("agentcount", agentcount); - - return "modules/callcenterqaqc/qaqcgrievancedashboard"; - } - - @GetMapping("/admin/qaqcassigntaskagents") - public String viewAgentAssign(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/callcenterqaqc/qaqctaskagentassign"; - } - - - @GetMapping("/admin/qaqcfollowuplist") - public String viewAdminFollowuplist(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/callcenterqaqc/qaqcfollowuplist"; - } - - - @GetMapping("/admin/unattendedcomplaints") - public String viewAdminUnattendedClose(Model model) { - - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId", userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - return "modules/callcenterqaqc/unattendedclosing"; - } - - - - - - @GetMapping("/agent/agentgrievancedashboard") - public String viewAgentGrievenceDashboardpage( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate, - Model model - ) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - - - // Default dates if not provided - if (startDate == null || endDate == null) { - LocalDate today = LocalDate.now(); - startDate = today.toString(); - endDate = today.toString(); - } - - List> details = agentsService.getAgentDashboard(userId, startDate, endDate); - model.addAttribute("details", details); - - List> details2 = agentsService.getAgentPerformanceData(userId, startDate, endDate); - model.addAttribute("details2", details2); - - List> tasks = agentsService.getAgentTaskDetails(userId, startDate, endDate); - model.addAttribute("tasks", tasks); - //System.out.println("tasks: "+tasks); - return "modules/callcenterqaqc/agentgrievancedashboard"; - } - - - - @PostMapping("/agent/agentgrievancedashboard") - public String viewAgentGrievenceDashboard( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate, - Model model - ) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - // Default dates if not provided - if (startDate == null || endDate == null) { - LocalDate today = LocalDate.now(); - startDate = today.toString(); - endDate = today.toString(); - } - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - -// System.out.println("startdate: "+startDate ); -// System.out.println("enddate:" + endDate); - - List> details = agentsService.getAgentDashboard(userId, startDate, endDate); - model.addAttribute("details", details); - - List> details2 = agentsService.getAgentPerformanceData(userId, startDate, endDate); - model.addAttribute("details2", details2); - - List> tasks = agentsService.getAgentTaskDetails(userId, startDate, endDate); - model.addAttribute("tasks", tasks); - - return "modules/callcenterqaqc/agentgrievancedashboard"; - - } - - @GetMapping("/agent/qaqccalls") - public String viewAgentQaqcCalls( @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate,Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("userId",userId); - model.addAttribute("LoginUserId",LoginUserId); - - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - // Default dates if not provided - if (startDate == null || endDate == null) { - LocalDate today = LocalDate.now(); - startDate = today.toString(); - endDate = today.toString(); - } - - List> details = agentsService.getAgentDashboard(userId, startDate, endDate); - model.addAttribute("details", details); - - List> qaqcCallslists=qaqcCallsService.getClosedComplaints(userId); - model.addAttribute("qaqcCallsLists",qaqcCallslists); - - List> qaqcCallsAction=qaqcCallsService.getCallCategories(); - model.addAttribute("qaqcCallsActioin",qaqcCallsAction); - - List> qaqcSubmitDetails=qaqcCallsService.getSubmitDetails(userId); - model.addAttribute("qaqcSubmitDetails",qaqcSubmitDetails); - - return "modules/callcenterqaqc/agentqaqccalls"; - } - - - - @GetMapping("agent/qaqcinprogresscall") - public String viewqaqcin_progress_call( @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate,Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("userId",userId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - // Default dates if not provided - if (startDate == null || endDate == null) { - LocalDate today = LocalDate.now(); - startDate = today.toString(); - endDate = today.toString(); - } - - List> details = agentsService.getAgentDashboard(userId, startDate, endDate); - model.addAttribute("details", details); - - List> inprogresslists=inprogresscallService.getInProgressCalls(userId); - model.addAttribute("inprogresslists", inprogresslists); - - List> qaqcactionlists=inprogresscallService.getActionsCatergory(); - model.addAttribute("qaqcactionlists", qaqcactionlists); - - List> inSubmitDetails=inprogresscallService.getInprogressSubmitDetails(userId); - model.addAttribute("inSubmitDetails",inSubmitDetails); - - return "modules/callcenterqaqc/agentqaqcinprogresscalls"; - } - - @GetMapping("/agent/qaqcfollowupcalls") - public String viewAgentQaqcFollowupCalls(@RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate,Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("userId",userId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - // Default dates if not provided - if (startDate == null || endDate == null) { - LocalDate today = LocalDate.now(); - startDate = today.toString(); - endDate = today.toString(); - } - - - List> details = agentsService.getAgentDashboard(userId, startDate, endDate); - model.addAttribute("details", details); - - List> qaqcfollowuplists=followUpService.getFollowUpCalls(userId); - model.addAttribute("qaqcfollowuplists",qaqcfollowuplists); - - List> qaqccategorylists=followUpService.getFollowUpCatergory(); - - model.addAttribute("qaqccategorylists",qaqccategorylists); - - List> fcSubmitDetails=followUpService.getFollowupSubmitDetails(userId); - model.addAttribute("fcSubmitDetails",fcSubmitDetails); - - return "modules/callcenterqaqc/agentqaqcfollowupcalls"; - } - - - @GetMapping("/agent/qaqcpublicfollowupcalls") - public String viewAgentQaqcPublicFollowupCalls(@RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate,Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("userId",userId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - // Default dates if not provided - if (startDate == null || endDate == null) { - LocalDate today = LocalDate.now(); - startDate = today.toString(); - endDate = today.toString(); - } - - - List> details = agentsService.getAgentDashboard(userId, startDate, endDate); - model.addAttribute("details", details); - - List> qaqcfollowuplists=publicService.getFollowUpCalls(userId); - model.addAttribute("qaqcfollowuplists",qaqcfollowuplists); - - List> qaqccategorylists=publicService.getFollowUpCatergory(); - - model.addAttribute("qaqccategorylists",qaqccategorylists); - - List> fcSubmitDetails=publicService.getFollowupSubmitDetails(userId); - model.addAttribute("fcSubmitDetails",fcSubmitDetails); - - return "modules/callcenterqaqc/agentqaqcpublicfollowupcalls"; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/PublicFollowUpController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/PublicFollowUpController.java deleted file mode 100644 index 47bb6464..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/PublicFollowUpController.java +++ /dev/null @@ -1,89 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.FollowUpService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.PublicFollowUpService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcCallsService; - -@RequestMapping("gcc/api/callcenterqaqc/agent/publicfollowupcalls") -@RestController -public class PublicFollowUpController { - - @Autowired - RestTemplate restTemplate; - - @Autowired - private QaqcCallsService qaqcCallsService; - - @Autowired - private FollowUpService followService; - - @Autowired - private PublicFollowUpService publicService; - - @PostMapping("/update") - @ResponseBody - public ResponseEntity updateCallDetails(@RequestParam("complaintNumber") String complaintNumber, - @RequestParam("dataId") int dataId, - @RequestParam("userId") String userId, - @RequestParam("action") String action, - @RequestParam(value = "remainderDate", required = false,defaultValue = "-") String remainderDate, - @RequestParam("remarks") String remarks) { - try { -// System.out.println("Updating Complaint Number: " + complaintNumber); -// System.out.println("Updating Data ID: " + dataId); -// System.out.println("Action: " + action); -// System.out.println("Remarks: " + remarks); - int updated_agent = Integer.parseInt(userId); -// System.out.println("updated_agent: " + updated_agent); - - Map complaintDetails = qaqcCallsService.getComplaintDetails(dataId); - - Integer agentId = (Integer) complaintDetails.get("agent_id"); - Map erp_username=qaqcCallsService.getErpnameById(agentId); - String Erpname=(String) erp_username.get("erp_username"); - - if ("COMPLETED".equals(action) || "REOPEN".equals(action) ||"WRONG_ASSIGN".equals(action)) - { - boolean statusUpdated =qaqcCallsService.ChangeStatusInErp(complaintNumber, remarks, action,Erpname); - System.out.println("statusUpdated="+statusUpdated); - if (!statusUpdated) - { - return ResponseEntity.ok("error"); - } - } - - // Update complaint details - followService.updateFollowupComplaintDetails(complaintNumber, dataId, action, remarks,updated_agent); - followService.updateComplaintHistoryDetails(complaintNumber, dataId, action, remarks,updated_agent, remainderDate); - - Map logDetails = qaqcCallsService.getComplaintDetails(dataId); - // Upload to logs - followService.uploadComplaintDetailsInLogs(logDetails, action, complaintNumber,remainderDate); - - return ResponseEntity.ok("Success"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - } - - @GetMapping("/getpubsubmittedcalls") - public List> getFollowupSubmitDetails(@RequestParam int userId) - { - return publicService.getFollowupSubmitDetails(userId); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAPIController.java deleted file mode 100644 index ff86f25b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAPIController.java +++ /dev/null @@ -1,391 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.security.SecureRandom; -import java.sql.Connection; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.FollowUpService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - - - -@RequestMapping("gcc/api/callcenterqaqc") -@RestController("GrivanceQCapiController") - -public class QaqcAPIController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - - @Autowired - public QaqcAPIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private QaqcService qaqcService; - - @Autowired - private FollowUpService followUpService; - - - - @GetMapping("/getComplaintDetails/{complaintNumber}") - public Map getComplaintDetails( - @PathVariable String complaintNumber, - @RequestParam(required = false) String gender, - @RequestParam(required = false) String compmode, - @RequestParam(required = false) String deptname) { - - Map resultMap = new HashMap<>(); - - try { - String url = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintByID&ComplaintId=" - + complaintNumber + "&imgUrlonly=yes"; - System.out.println("Request URL: " + url); - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - String responseBody = responseEntity.getBody(); - //System.out.println("Response Body: " + responseBody); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(responseBody); - - JsonNode complaintDetails = rootNode.path(0).path("ComplaintListHistory").path(0); - - String registerDate=complaintDetails.path("complaintopendate").asText("N/A"); - //System.out.println("registerdate====="+registerDate); - - String formattedDate = "N/A"; // Default value if parsing fails - - if (!registerDate.equals("N/A") && !registerDate.isEmpty()) { - try { - // Parse the input date string - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); - Date date = inputFormat.parse(registerDate); - - // Format the date to dd-MM-yyyy - SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - formattedDate = outputFormat.format(date); - } catch (Exception e) { - e.printStackTrace(); // Log exception for debugging - } - } - - if (!complaintDetails.isMissingNode()) { - // Existing fields - resultMap.put("complaintid", complaintDetails.path("complaintid").asText("N/A")); - resultMap.put("complaintdate", formattedDate); - resultMap.put("complainantName", complaintDetails.path("CustomerName").asText("N/A")); - resultMap.put("mobileNumber", complaintDetails.path("CustomerMobile").asText("N/A")); - resultMap.put("complaintType", complaintDetails.path("complainttype").asText("N/A")); - resultMap.put("description", complaintDetails.path("complaintdetails").asText("N/A")); - resultMap.put("currentStatus", complaintDetails.path("complaintcurrentstatus").asText("N/A")); - resultMap.put("Street", complaintDetails.path("Street").asText("N/A")); - resultMap.put("Area", complaintDetails.path("Area").asText("N/A")); - resultMap.put("Landmark", complaintDetails.path("Landmark").asText("N/A")); - resultMap.put("Location", complaintDetails.path("Location").asText("N/A")); - resultMap.put("Zone", complaintDetails.path("Zone").asText("N/A")); - resultMap.put("Division", complaintDetails.path("Division").asText("N/A")); - resultMap.put("OfficialMobile", complaintDetails.path("OfficialMobile").asText("N/A")); - resultMap.put("gender", gender != null ? gender : complaintDetails.path("GENDER").asText("N/A")); - resultMap.put("deptname", deptname != null ? deptname : complaintDetails.path("DEPT_NAME").asText("N/A")); - resultMap.put("compmode", compmode != null ? compmode : complaintDetails.path("COMP_MODE").asText("N/A")); - - // Comments section - JsonNode comments = complaintDetails.path("Comments"); - if (!comments.isMissingNode()) { - List> commentList = new ArrayList<>(); - for (JsonNode commentNode : comments) { - Map commentData = new HashMap<>(); - - // Extracting comment details - commentData.put("user", commentNode.path("user").asText("N/A")); - commentData.put("message", commentNode.path("message").asText("N/A")); - commentData.put("comment_date", commentNode.path("comment_date").asText("N/A")); - - // Handling media link (Image) as part of userimages array for each comment - JsonNode userImages = commentNode.path("userimages"); - if (!userImages.isMissingNode() && userImages.isArray() && userImages.size() > 0) { - String mediaLink = userImages.get(0).path("Comp_Image").asText(null); - // If media link is valid, add it to the comment data - if (mediaLink != null && !mediaLink.equals("null") && !mediaLink.isEmpty()) { - commentData.put("Comp_Image", mediaLink); - } else { - commentData.put("Comp_Image", "No image available"); - } - } else { - commentData.put("Comp_Image", "No image available"); - } - - // Add the comment data to the list - commentList.add(commentData); - } - resultMap.put("comments", commentList); - } - - - // Handling media link (Image) as part of userimages array - String mediaLink = complaintDetails.path("mediaLink").asText(null); - List> userImagesList = new ArrayList<>(); - Map imageMap = new HashMap<>(); - imageMap.put("Comp_Image", mediaLink != null && !mediaLink.equals("null") ? mediaLink : null); - userImagesList.add(imageMap); - resultMap.put("userimages", userImagesList); - - - // System.out.println("Image URL from API: " + mediaLink); - } - } else { - resultMap.put("error", "Failed to retrieve complaint details."); - } - } catch (Exception e) { - e.printStackTrace(); - resultMap.put("error", "Error processing request"); - } - - return resultMap; - } - - - @GetMapping("/followuplist") - @ResponseBody - public List> getFollowUpList( - @RequestParam(value = "callStatus", required = false) String callStatus, - @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, - @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate) { - - // Set default 'toDate' to a future date (1 year ahead) if not provided - if (toDate == null) { - toDate = LocalDate.now().plusMonths(1); // Set to one year ahead or any other future date - //toDate= qaqcService.getMaxRemainderdate(); - } - - // Set default 'fromDate' to the start of the current month if not provided - if (fromDate == null) { - fromDate = LocalDate.now().withDayOfMonth(1); // Start from the first day of the current month - } - - // Print debug info -// System.out.println("Received callStatus: " + callStatus); -// System.out.println("From Date: " + fromDate); -// System.out.println("To Date: " + toDate); - - // Call the service to fetch the filtered data based on the status and date range - return qaqcService.getFollowUpDetailsByStatus(callStatus, fromDate, toDate); - } - - - @GetMapping("/followup/todayCount") - public ResponseEntity> getTodayFollowUpCount(@RequestParam String followupStatus) { - LocalDate today = LocalDate.now(); // Get the current date - Map counts = qaqcService.countFollowUpsByDateAndStatus(today, followupStatus); - - return ResponseEntity.ok(counts); // Return the count in the response - } - - @GetMapping("/callhistory") - public ResponseEntity>> getCallHistory(@RequestParam String complaintNumber) { - List> callHistory = followUpService.getCallHistory(complaintNumber); - if (callHistory.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(Collections.emptyList()); - } - return ResponseEntity.ok(callHistory); - } - - @GetMapping("/getfilterreport") - public Map getFilterReports( - @RequestParam String startDate, - @RequestParam String endDate, - @RequestParam String status, - @RequestParam String group, - @RequestParam String type, - @RequestParam String mode, - @RequestParam String zone, - @RequestParam String region) { - Map response = new HashMap<>(); - - try { - - LocalDate fromLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ISO_DATE); - LocalDate toLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ISO_DATE); - String formattedFromDate = fromLocalDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); - String formattedToDate = toLocalDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); - - String url="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+mode+"&Zoneid="+zone+"&RegionId="+region; - System.out.println(url); - - RestTemplate restTemplate = new RestTemplate(); - - // Fetch response as String - ResponseEntity responses = restTemplate.getForEntity(url, String.class); - String rawResponse = responses.getBody(); - - // Preprocess response to remove invalid characters if needed - if (rawResponse != null) { - //rawResponse = rawResponse.replaceAll("\"\"", "\""); // Replace double-double quotes - //rawResponse = rawResponse.replaceAll("(? responseMap = objectMapper.readValue(rawResponse, Map.class); - List> details = (List>) responseMap.get("Details"); - //System.out.println(details); - if (details == null) { - response.put("status", "nodata"); - response.put("message", "No Data, please change criteria"); - } - else { - response.put("status", "success"); - response.put("details", details); - } - - } - catch (Exception e) { - response.put("status", "error"); - response.put("message", "An error occurred while fetching data."); - e.printStackTrace(); - } - - return response; - } - - @GetMapping("/getunattendedcount") - public Map GetUnattendedComplaints(@RequestParam int ucount) - { - Map response = new HashMap<>(); - - try { - // Logging input parameters - //System.out.println("Received Data: " + ucount); - - // Fetch unattended complaints - List> details = qaqcService.getUnattendedlist(ucount); - - if (details != null && !details.isEmpty()) { - response.put("status", "success"); - response.put("details", details); - } else { - response.put("status", "nodata"); - response.put("message", "No unattended complaints found for the given criteria."); - } - } catch (Exception e) { - System.err.println("Error while fetching unattended complaints: " + e.getMessage()); - e.printStackTrace(); // Log the complete stack trace for debugging - - response.put("status", "error"); - response.put("message", "An error occurred while fetching unattended complaints. Please try again."); - } - - return response; - } - - @PostMapping("/closingunattendedcomplaints") - public ResponseEntity> closeUnattendedComplaints(@RequestBody Map request) { - Map response = new HashMap<>(); - - try { - // Extract values from request map - String userId = (String) request.get("userId"); - String remarks = (String) request.get("remarks"); - List complaintNumbers = (List) request.get("complaintNumbers"); - - if (userId == null || remarks == null || complaintNumbers == null || complaintNumbers.isEmpty()) { - response.put("status", "error"); - response.put("message", "Invalid request data."); - return ResponseEntity.badRequest().body(response); - } - - // Get ERP Username - String erp_name = qaqcService.getErpusernamebyId(userId); - //System.out.println("ERP Name: " + erp_name); - - List completedComplaints = new ArrayList<>(); - List failedComplaints = new ArrayList<>(); - - // Process each complaint number - for (String complaintNumber : complaintNumbers) { - boolean isSuccess = qaqcService.ChangeStatusInErp(complaintNumber, erp_name, remarks); - if (isSuccess) { - completedComplaints.add(complaintNumber); - } else { - failedComplaints.add(complaintNumber); - } - } - - int updated=qaqcService.UpdateInHistoryTable(completedComplaints); - //System.out.println("Updated rows in history table: " + updated); - - int updateInlogs=qaqcService.insertInLogs(completedComplaints,remarks,userId); - //System.out.println("Updated rows in logs table: " + updateInlogs); - - //System.out.println("failedComplaints===="+failedComplaints); - - // Response handling - if (complaintNumbers.size() == completedComplaints.size()) { - response.put("status", "success"); - response.put("message", "All complaints Completed successfully."); - response.put("completedCount", completedComplaints.size()); - } else if (!completedComplaints.isEmpty()) { - response.put("status", "partial_success"); - response.put("message", "Some complaints failed to process."); - response.put("completedCount", completedComplaints.size()); - response.put("failedCount", failedComplaints.size()); - response.put("failedComplaints", failedComplaints); - } else { - response.put("status", "error"); - response.put("message", "Failed to process all complaints."); - } - - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", "An internal server error occurred."); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsApiController.java deleted file mode 100644 index 23b946b4..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsApiController.java +++ /dev/null @@ -1,208 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAdminSettingService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("gcc/api/callcenterqaqc/adminsettings") -@RestController -public class QaqcAdminSettingsApiController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - - @Autowired - public QaqcAdminSettingsApiController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private QaqcAdminSettingService adminService; - - @PostMapping("/saveproductivity") - public ResponseEntity> saveproductivity(@RequestParam int productivity_count) - { - Map response = new HashMap<>(); - try { - - // Save task ID - int rowsInserted = adminService.saveProductivity(productivity_count); - - if (rowsInserted > 0) { - response.put("status", "success"); - response.put("message", "Productivity inserted successfully"); - return ResponseEntity.ok(response); - } - - response.put("status", "fail"); - response.put("message", "Productivity not saved"); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); // Change to BAD_REQUEST for failure - - } catch (Exception e) { - // Logging the error - Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error saving task", e); - - response.put("status", "error"); - response.put("message", "Failed to save productivity"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - - @PostMapping("/updateproductivity") - public ResponseEntity> updateProductivityById(@RequestBody Map requestData) - { Map response = new HashMap<>(); - try { - - // Save task ID - int productivityCount = requestData.getOrDefault("productivity_count", 0); // Default to 0 if not provided - int rowsUpdated = adminService.updateProductivity(productivityCount); - - - if (rowsUpdated > 0) { - response.put("status", "success"); - response.put("message", "Productivity saved successfully"); - return ResponseEntity.ok(response); - } - - response.put("status", "fail"); - response.put("message", "Productivity not saved"); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); // Change to BAD_REQUEST for failure - - } catch (Exception e) { - // Logging the error - Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error saving task", e); - - response.put("status", "error"); - response.put("message", "Failed to save productivity"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - @GetMapping("/getproductivity") - public Integer getProductivity() - { - return adminService.getProductivity(); - } - - @GetMapping("/getadminsettingcounts") - public List> getadminsettingcounts() - { - return adminService.getAdminSettingCounts(); - - } - - @GetMapping("/assigncallingtype") - public List> assigncallingtype() - { - return adminService.getAgentsForCallingtype(); - - } - - @PostMapping("/updateCallType") // Bulk update endpoint - public ResponseEntity> updateCallType(@RequestBody List> selectedAgents) { - - Map response = new HashMap<>(); - - try { - int rowsUpdated = 0; - - // Loop through each selected agent and update their calling_type - for (Map agent : selectedAgents) { - String callingType = (String) agent.get("calling_type"); - - // Parse agent_id to Integer if it's passed as a String - int agentId = Integer.parseInt(agent.get("agent_id").toString()); // Ensure it's parsed as Integer - - // Update calling type for the agent - rowsUpdated += adminService.updateCallType(callingType, agentId); - - - } - adminService.saveCallingTypeInSettings(); - - if (rowsUpdated > 0) { - response.put("status", "success"); - response.put("message", "Agents Assigned successfully"); - return ResponseEntity.ok(response); - } else { - response.put("status", "error"); - response.put("message", "No agents updated"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } catch (Exception e) { - response.put("status", "error"); - response.put("message", "Error occurred while updating calling types: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - @PostMapping("/updateagentname") - public ResponseEntity> updateAgentnameById(@RequestBody Map requestData){ - Map response = new HashMap<>(); - - try { - // Extract and convert agent_id to int - String agentIdStr = requestData.get("agent_id"); - String updatedName = requestData.get("agent_name"); - - // Validate input - if (agentIdStr == null || updatedName == null || updatedName.trim().isEmpty()) { - response.put("status", "error"); - response.put("message", "Agent ID and name are required!"); - return ResponseEntity.badRequest().body(response); - } - - int agentId; - try { - agentId = Integer.parseInt(agentIdStr); - } catch (NumberFormatException e) { - response.put("status", "error"); - response.put("message", "Invalid Agent ID format!"); - return ResponseEntity.badRequest().body(response); - } - - // Call service layer to update the agent name - int updatedRows = adminService.updateAgentName(agentId, updatedName); // Now agentId is an int - - if (updatedRows == -1) { // If name already exists - response.put("status", "error"); - response.put("message", "Agent name already exists!"); - return ResponseEntity.status(HttpStatus.CONFLICT).body(response); - } else if (updatedRows > 0) { - response.put("status", "success"); - response.put("message", "Agent name updated successfully!"); - return ResponseEntity.ok(response); - } else { - response.put("status", "error"); - response.put("message", "Agent not found or update failed."); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); - } - - } - catch (Exception e) { - response.put("status", "error"); - response.put("message", "Error occurred while updating Agent name " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsMainController.java deleted file mode 100644 index 43914567..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsMainController.java +++ /dev/null @@ -1,47 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAdminSettingService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/callcenterqaqcadminsettings") -@Controller("callCenterQaQcAdminSettingsController") -public class QaqcAdminSettingsMainController { - - @Autowired - private QaqcAdminSettingService adminService; - - @GetMapping("/adminsettings") - public String viewAdminSettings(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - - - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - List> Counts=adminService.getAdminSettingCounts(); - model.addAttribute("Counts", Counts); - - List> agents=adminService.getAgentsForCallingtype(); - model.addAttribute("Agents", agents); - - - return "modules/callcenterqaqc/qaqcadminsettings"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentAssignAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentAssignAPIController.java deleted file mode 100644 index 35e8b427..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentAssignAPIController.java +++ /dev/null @@ -1,234 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.security.SecureRandom; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAdminSettingService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAgentAssignService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - - -@RestController -@RequestMapping("gcc/api/callcenterqaqc/agentassign") -public class QaqcAgentAssignAPIController { - - private final RestTemplate restTemplate; - - @Autowired - public QaqcAgentAssignAPIController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @Autowired - private QaqcAgentAssignService agentAssignService; - - @Autowired - private QaqcAdminSettingService adminService; - - - - @GetMapping("/getavailableagents") - public ResponseEntity> getAvailableAgents(@RequestParam int totalDataCount) { - Map response = new HashMap<>(); - try { - // Fetch available agents - List> availableAgents = agentAssignService.getAvailableOutboundAgents(); - Integer productivity_count = adminService.getProductivity(); - - if (availableAgents.isEmpty() || totalDataCount == 0) { - response.put("status", "error"); - response.put("message", "No available agents or totalDataCount must be greater than 0."); - return ResponseEntity.ok(response); - } - - - // Process and filter agents based on productivity_count - List> filteredAgents = new ArrayList<>(); - for (Map agent : availableAgents) { - Integer agentId = (Integer) agent.get("agent_id"); - String agentName = (String) agent.get("agent_name"); - Integer todayCount=agentAssignService.getTodayCountForAgent(agentId); - Integer campaignPendingCount = agentAssignService.getCampaignPendingCountForAgent(agentId); - Integer pendingCounts=todayCount+campaignPendingCount; - // Log the details of each agent - //System.out.println("Agent ID: " + agentId + ", Today Count: " + todayCount +", Campaign Pending Count: " + campaignPendingCount + ", Pending Counts: " + pendingCounts); - - if(pendingCounts> finalFilteredAgents = new ArrayList<>(); - filteredAgents.sort(Comparator.comparingInt(agent -> (Integer) agent.get("campaignPendingCount"))); - - for (int i = 0; i < filteredAgents.size(); i++) { - Map agent = filteredAgents.get(i); - Integer agentId = (Integer) agent.get("agent_id"); - String agentName = (String) agent.get("agent_name"); - Integer todayCount = (Integer) agent.get("todayCount"); - Integer campaignPendingCount = (Integer) agent.get("campaignPendingCount"); - // Add 1 extra call for agents handling the remainder, starting from the first agent - int additionalCalls = (i < remainder) ? 1 : 0; - int totalCallsCount = todayCount+campaignPendingCount + calls_per_agent + additionalCalls; - - if (totalCallsCount < productivity_count) { - finalFilteredAgents.add(Map.of( - "agent_id", agentId, - "agent_name", agentName, - "totalCallsCount", totalCallsCount, - "todayCount",todayCount, - "campaignPendingCount", campaignPendingCount, - "calls_per_agent", calls_per_agent + additionalCalls - )); - // System.out.println("Agent added to final======filteredAgents: " + agentName); - } - } - //System.out.println("Final Filtered Agents Size: " + finalFilteredAgents.size()); - - if (finalFilteredAgents.isEmpty()) { - response.put("status", "error"); - response.put("message", "No Available Agents,To continue Increase the Productivity"); - return ResponseEntity.ok(response); - } - - - int agent_available_count2 = finalFilteredAgents.size(); - - // Calculate calls per agent using filtered agent count - int calls_per_agent2 = totalDataCount / agent_available_count2; - int remainder2 = totalDataCount % agent_available_count2; - - // Distribute calls_per_agent and remainder - List> LastfinalFilteredAgents = new ArrayList<>(); - finalFilteredAgents.sort(Comparator.comparingInt(agent -> (Integer) agent.get("campaignPendingCount"))); - - for (int i = 0; i < finalFilteredAgents.size(); i++) { - Map agent = finalFilteredAgents.get(i); - Integer agentId = (Integer) agent.get("agent_id"); - String agentName = (String) agent.get("agent_name"); - Integer todayCount1 = (Integer) agent.get("todayCount"); - Integer campaignPendingCount = (Integer) agent.get("campaignPendingCount"); - // Add 1 extra call for agents handling the remainder, starting from the first agent - int additionalCalls1 = (i < remainder2) ? 1 : 0; - int totalCallsCount1 = todayCount1+campaignPendingCount + calls_per_agent2 + additionalCalls1; - - if (totalCallsCount1 < productivity_count) { - LastfinalFilteredAgents.add(Map.of( - "agent_id", agentId, - "agent_name", agentName, - "totalCallsCount", totalCallsCount1, - "todayCount1",todayCount1, - "campaignPendingCount", campaignPendingCount, - "calls_per_agent", calls_per_agent2 + additionalCalls1 - )); - // System.out.println("Agent added to Lastfinal======LastfinalFilteredAgents: " + agentName); - } - } - //System.out.println("Filtered Agents Size: " + LastfinalFilteredAgents.size()); - - if (LastfinalFilteredAgents.isEmpty()) { - response.put("status", "error"); - response.put("message", "No Available Agents,To continue Increase the Productivity"); - return ResponseEntity.ok(response); - } - - // Build response - response.put("status", "success"); - response.put("message", "Available agents fetched successfully"); - response.put("available_agents", LastfinalFilteredAgents); - response.put("productivity_count", productivity_count); - response.put("agent_available_count", LastfinalFilteredAgents.size()); - - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - - // Return error response in case of failure - response.put("status", "error"); - response.put("message", "Failed to fetch available agents"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - - @PostMapping("/taskassign") - public ResponseEntity> assignTasks(@RequestBody Map requestData) { - Map response; - try { - // Delegate transactional work to the service - response = agentAssignService.assignTasksTransactionally(requestData); - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - response = new HashMap<>(); - response.put("status", "error"); - response.put("message", "An error occurred: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - @GetMapping("/deleteRecords") - public ResponseEntity deleteRecordsInUploadData() { - try { - int rowsAffected = agentAssignService.deleteUploadDataTable(); - if (rowsAffected > 0) { - return ResponseEntity.ok("success"); - } else { - return ResponseEntity.ok("No records to delete"); - } - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error deleting records"); - } - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentsAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentsAPIController.java deleted file mode 100644 index 8d277e8e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentsAPIController.java +++ /dev/null @@ -1,161 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Required; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.ui.Model; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAgentsService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/callcenterqaqc/agent") -@RestController -public class QaqcAgentsAPIController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - - @Autowired - public QaqcAgentsAPIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private QaqcAgentsService agentsService; - - - @GetMapping("/getdataforagents") - public ResponseEntity> getdataforagents(@RequestParam int agent_id,@RequestParam int qaqc_id) - { - Map response = new HashMap<>(); - - try { - - List> tasks = agentsService.getdataforagents(agent_id,qaqc_id); - - if (tasks.isEmpty()) { - - response.put("status", "no_data"); - response.put("message", "No data found for the given agent_id and qaqc_id."); - } else { - // Success case - response.put("status", "success"); - response.put("message", "Data retrieved successfully."); - response.put("tasks", tasks); - } - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", "An error occurred: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - - } - - @PostMapping("/savecallstatus") - public ResponseEntity savecallstatus(@RequestParam String call_status,@RequestParam String remarks,@RequestParam String complaintNumber)//get full body data - { - - agentsService.savecallstatus(call_status, remarks,complaintNumber);//get all dbdata and save here and service also - agentsService.savecallstatusinlogs(call_status, remarks,complaintNumber);//get all dbdata and save here and service also - - return ResponseEntity.ok("Data Inserted successfully."); - - } - - - - @GetMapping("/getagentperformancecount") - public List> getAgentPerformanceCount( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - List> counts = agentsService.getAgentPerformanceCount(startDate, endDate); -// System.out.println("fromdates: " + startDate); -// System.out.println("todate: " + endDate); -// System.out.println("overallcounts: " + counts ); - return counts; - } - - @GetMapping("/getagentperformancelist") - public List> getAgentPerformanceList( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - // Fetch agent performance data from service - List> agentPerformanceData = agentsService.getAgentPerformanceList(startDate, endDate); - - // Log or return the data - //System.out.println("Agent Performance Data: " + agentPerformanceData); - return agentPerformanceData; - } - - @GetMapping("/agenttaskwise") - public List> getAgentTaskwiseData(@RequestParam String agentId,@RequestParam String startDate,@RequestParam String endDate) { - // Call the service to fetch agent task-wise data - List> agentTaskwiseData = agentsService.getAgentTaskwiseData(agentId, startDate, endDate); - //System.out.println("Agent Task Wise Data: " + agentTaskwiseData); - return agentTaskwiseData; - } - - @GetMapping("/agentattendedcomplaints") - public List> getAttendedComplaintStatus( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate, - @RequestParam(required = false) String complaintNumber, - @RequestParam(required = false) String complaintMobileNumber){ - - List> agentAttendedData = agentsService.getAttendedComplaintStatus(startDate, endDate, complaintNumber, complaintMobileNumber); - //System.out.println("Agent attended Data: " + agentAttendedData); - return agentAttendedData; - } - - @GetMapping("/attendedcomplaintshistory") - public List> getAttendedComplainthistory( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate, - @RequestParam(required = false) String complaintNumber, - @RequestParam(required = false) String complaintMobileNumber){ - - List> agentAttendedData = agentsService.getAttendedComplainthistory(startDate, endDate, complaintNumber, complaintMobileNumber); - //System.out.println("Agent attended Data: " + agentAttendedData); - return agentAttendedData; - } - - - @GetMapping("/agenttaskassign") - public List> getAgentTaskwiseAssign(@RequestParam String agentId) { - // Call the service to fetch agent task-wise data - List> agentTaskwiseAssign = agentsService.getAgentTaskwiseAssign(agentId); - //System.out.println("Agent Task Wise Assign: " + agentTaskwiseAssign); - return agentTaskwiseAssign; - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcCallsController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcCallsController.java deleted file mode 100644 index 5e908552..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcCallsController.java +++ /dev/null @@ -1,519 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -//import java.util.stream.Stream; -import java.text.ParseException; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcCallsService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/callcenterqaqc/agent/qaqccalls") -@RestController -public class QaqcCallsController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public QaqcCallsController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private QaqcCallsService qaqcCallsService; - - @PostMapping("/update") - @ResponseBody - public ResponseEntity updateCallDetails(@RequestParam("complaintNumber") String complaintNumber, - @RequestParam("dataId") int dataId, @RequestParam("action") String action, - @RequestParam("userId") String userId, - @RequestParam(value = "remainderDate", required = false, defaultValue = "-") String remainderDate, - @RequestParam("remarks") String remarks) { - try { -// System.out.println("Updating Complaint Number: " + complaintNumber); -// System.out.println("Updating Data ID: " + dataId); -// System.out.println("Action: " + action); -// System.out.println("Remarks: " + remarks); - int updated_agent = Integer.parseInt(userId); -// System.out.println("updated_agent: " + updated_agent); - - -// Map followUpComplaint = -// qaqcCallsService.checkComplaintDetail(complaintNumber); -// -// try { -// int followupid = (int) followUpComplaint.get("id"); -// // update complaintstaus if exist in followup call logs table -// if (followUpComplaint != null &&!followUpComplaint.isEmpty()) -// { -// qaqcCallsService.updateFollowupCallLogs(complaintNumber, action, remarks,followupid); -// } -// -// } -// catch(Exception e) -// { -// System.out.println("Exception:"+e); -// } - - //to insert incorrect office mobile number details in table - if(action.equals("MOBILE_NUM")) { - qaqcCallsService.saveMobileNumDetails(complaintNumber, remarks); } - - // Get complaint details - Map complaintDetails =qaqcCallsService.getComplaintDetails(dataId); - - Integer agentId = (Integer) complaintDetails.get("agent_id"); - Map erp_username=qaqcCallsService.getErpnameById(agentId); - String Erpname=(String) erp_username.get("erp_username"); - - // Handle COMPLETED and REOPEN actions - - if ("COMPLETED".equals(action) || "REOPEN".equals(action) ||"WRONG_ASSIGN".equals(action)) - { - boolean statusUpdated =qaqcCallsService.ChangeStatusInErp(complaintNumber, remarks, action,Erpname); - System.out.println("statusUpdated="+statusUpdated); - if (!statusUpdated) - { - return ResponseEntity.ok("error"); - } - } - - if("FOLLOWUP".equals(action)) { - - String pname = (String) complaintDetails.get("complaint_person_name"); - String mob_no = (String) complaintDetails.get("complaint_mobilenumber"); - String cat = (String) complaintDetails.get("complaint_type"); - - String result = sendWhatsappMsg(pname, cat, mob_no, complaintNumber); - if(result.equals("200")) { - System.out.println("Followup Whatsapp Message Triggered for "+complaintNumber); - } - } - - - - - // Execute common update methods - qaqcCallsService.updateComplaintDetails(complaintNumber, dataId, action,remarks,updated_agent); - qaqcCallsService.updateComplaintHistoryDetails(complaintNumber,dataId, action, remarks,updated_agent, remainderDate); - Map logDetails =qaqcCallsService.getComplaintDetails(dataId); - qaqcCallsService.uploadComplaintDetailsInLogs(logDetails, action,complaintNumber, remainderDate); - - - return ResponseEntity.ok("Success"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - } - - @GetMapping("/getComplaintDetails") - public Map getComplaintDetails(@RequestParam String complaintNumber) { - - Map resultMap = new HashMap<>(); - - try { - String url = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintByID&ComplaintId=" - + complaintNumber + "&imgUrlonly=yes&isQcuser=Yes&jsonResp=Yes"; - System.out.println("Request URL: " + url); - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - String responseBody = responseEntity.getBody(); - //System.out.println("Response Body: " + responseBody); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(responseBody); - - JsonNode complaintDetails = rootNode.path(0).path("ComplaintListHistory").path(0); - - String registerDate = complaintDetails.path("complaintopendate").asText("N/A"); - String ClosedDate = complaintDetails.path("complaintcloseddate").asText("N/A"); - String ReopenDate = complaintDetails.path("REOPENDDATE").asText("N/A"); - String FinalcloseDate = complaintDetails.path("FINALCLOSEDDATE").asText("N/A"); - - //System.out.println("registerdate=====" + registerDate); - - String formattedDate = "N/A"; // Default value if parsing fails - - if (!registerDate.equals("N/A") && !registerDate.isEmpty()) { - try { - // Parse the input date string - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); - Date date = inputFormat.parse(registerDate); - - // Format the date to dd-MM-yyyy - SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - formattedDate = outputFormat.format(date); - } catch (Exception e) { - e.printStackTrace(); // Log exception for debugging - } - } - - /* - DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); - DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - LocalDateTime maxDate = Stream.of(registerDate, ClosedDate, ReopenDate, FinalcloseDate) - .filter(date -> date != null && !date.equalsIgnoreCase("null")) - .map(date -> { - try { - return LocalDateTime.parse(date, inputFormatter); - } catch (DateTimeParseException e) { - return null; // Skip invalid date formats - } - }) - .filter(Objects::nonNull) - .max(LocalDateTime::compareTo) // Find the greatest date - .orElse(null); // Default to null if no valid dates are found - - String greatestDateFormatted = (maxDate != null) ? maxDate.format(outputFormatter) : "N/A"; - */ - - SimpleDateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); - SimpleDateFormat outputFormatter = new SimpleDateFormat("dd-MM-yyyy"); - - Date maxDate = null; - - // Put all date strings into array - String[] dates = { registerDate, ClosedDate, ReopenDate, FinalcloseDate }; - - for (int i = 0; i < dates.length; i++) { - - String dateStr = dates[i]; - - if (dateStr == null || "null".equalsIgnoreCase(dateStr)) { - continue; - } - - try { - Date parsedDate = inputFormatter.parse(dateStr); - - if (maxDate == null || parsedDate.after(maxDate)) { - maxDate = parsedDate; - } - - } catch (ParseException e) { - // Ignore invalid date formats - } - } - - String greatestDateFormatted = - (maxDate != null) ? outputFormatter.format(maxDate) : "N/A"; - - if (!complaintDetails.isMissingNode()) { - // Existing fields - resultMap.put("complaintid", complaintDetails.path("complaintid").asText("N/A")); - resultMap.put("complaintdate", formattedDate); - resultMap.put("complainantName", complaintDetails.path("CustomerName").asText("N/A")); - resultMap.put("mobileNumber", complaintDetails.path("CustomerMobile").asText("N/A")); - resultMap.put("complaintType", complaintDetails.path("complainttype").asText("N/A")); - resultMap.put("description", complaintDetails.path("complaintdetails").asText("N/A")); - resultMap.put("currentStatus", complaintDetails.path("complaintcurrentstatus").asText("N/A")); - resultMap.put("OfficialMobile", complaintDetails.path("OfficialMobile").asText("N/A")); - resultMap.put("Street", complaintDetails.path("Street").asText("N/A")); - resultMap.put("Area", complaintDetails.path("Area").asText("N/A")); - resultMap.put("Landmark", complaintDetails.path("Landmark").asText("N/A")); - resultMap.put("Location", complaintDetails.path("Location").asText("N/A")); - resultMap.put("Zone", complaintDetails.path("Zone").asText("N/A")); - resultMap.put("Division", complaintDetails.path("Division").asText("N/A")); - resultMap.put("gender", complaintDetails.path("GENDER").asText("N/A")); - resultMap.put("deptname", complaintDetails.path("DEPT_NAME").asText("N/A")); - resultMap.put("compmode", complaintDetails.path("COMP_MODE").asText("N/A")); - resultMap.put("greatestDate", greatestDateFormatted); - - // Comments section - JsonNode comments = complaintDetails.path("Comments"); - if (!comments.isMissingNode()) { - List> commentList = new ArrayList<>(); - for (JsonNode commentNode : comments) { - Map commentData = new HashMap<>(); - - // Extracting comment details - commentData.put("user", commentNode.path("user").asText("N/A")); - commentData.put("message", commentNode.path("message").asText("N/A")); - commentData.put("comment_date", commentNode.path("comment_date").asText("N/A")); - - // Handling media link (Image) as part of userimages array for each comment - JsonNode userImages = commentNode.path("userimages"); - if (!userImages.isMissingNode() && userImages.isArray() && userImages.size() > 0) { - String mediaLink = userImages.get(0).path("Comp_Image").asText(null); - // If media link is valid, add it to the comment data - if (mediaLink != null && !mediaLink.equals("null") && !mediaLink.isEmpty()) { - commentData.put("Comp_Image", mediaLink); - } else { - commentData.put("Comp_Image", "No image available"); - } - } else { - commentData.put("Comp_Image", "No image available"); - } - - // Add the comment data to the list - commentList.add(commentData); - } - resultMap.put("comments", commentList); - } - - // Handling media link (Image) as part of userimages array - String mediaLink = complaintDetails.path("mediaLink").asText(null); - List> userImagesList = new ArrayList<>(); - Map imageMap = new HashMap<>(); - imageMap.put("Comp_Image", mediaLink != null && !mediaLink.equals("null") ? mediaLink : null); - userImagesList.add(imageMap); - resultMap.put("userimages", userImagesList); - - //System.out.println("Image URL from API: " + mediaLink); - } - } else { - resultMap.put("error", "Failed to retrieve complaint details."); - } - } catch (Exception e) { - e.printStackTrace(); - resultMap.put("error", "Error processing request"); - } - - return resultMap; - } - - @GetMapping("/getComplaintDetailsByMobileNumber") - public Map getComplaintDetailsByMobileNumber(@RequestParam String complaintMobileNumber, - @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate, - @RequestParam String complaintYear) { - -// System.out.println("Computed Start Date: " + startDate); -// System.out.println("Computed End Date: " + endDate); -// System.out.println("Computed Year: " + complaintYear); -// System.out.println("Computed MobileNumber: " + complaintMobileNumber); - - Map resultMap = new HashMap<>(); - List> complaintsList = new ArrayList<>(); - - try { - // Determine current year's starting date and today's date - LocalDate currentDate = LocalDate.now(); - LocalDate yearStartDate = currentDate.withDayOfYear(1); - - // Set default dates if startDate or endDate are empty - if (startDate == null || startDate.isEmpty()) { - startDate = yearStartDate.toString(); // Set to current year's start date - } - if (endDate == null || endDate.isEmpty()) { - endDate = currentDate.toString(); // Set to today's date - } - - DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); - - startDate = LocalDate.parse(startDate, inputFormatter).format(outputFormatter); - endDate = LocalDate.parse(endDate, inputFormatter).format(outputFormatter); - - // Debug logs (optional) -// System.out.println("Formatted Start Date: " + startDate); -// System.out.println("Formatted End Date: " + endDate); - - String url = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintListWithImg&From_date=" - + startDate + "&To_date=" + endDate - + "&jsonResp=Yes&UserType=Public&Token=&PageIndex=null&Status=null&repYear=" + complaintYear - + "&MobileNo=" + complaintMobileNumber; - - System.out.println("Request URL: " + url); - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - String responseBody = responseEntity.getBody(); - // System.out.println("Response Body: " + responseBody); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(responseBody); - - JsonNode complaintListHistory = rootNode.path(0).path("ComplaintListHistory"); - - if (complaintListHistory.isArray()) { - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); - SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy"); - for (JsonNode complaintDetails : complaintListHistory) { - Map complaintMap = new HashMap<>(); - - String registerDate = complaintDetails.path("complaintopendate").asText("N/A"); - Date parsedDate = null; - - if (!registerDate.equals("N/A") && !registerDate.isEmpty() && !"null".equalsIgnoreCase(registerDate)) { - try { - parsedDate = inputFormat.parse(registerDate); - String formattedDate = outputFormat.format(parsedDate); - complaintMap.put("complaintdate", formattedDate); - } catch (Exception e) { - e.printStackTrace(); - complaintMap.put("complaintdate", "N/A"); - } - } else { - complaintMap.put("complaintdate", "N/A"); - } - - // Add complaint details to the map - complaintMap.put("complaintid", complaintDetails.path("complaintid").asText("N/A")); - complaintMap.put("complainantName", complaintDetails.path("CustomerName").asText("N/A")); - complaintMap.put("mobileNumber", complaintDetails.path("CustomerMobile").asText("N/A")); - complaintMap.put("complaintType", complaintDetails.path("complainttype").asText("N/A")); - complaintMap.put("currentStatus",complaintDetails.path("complaintcurrentstatus").asText("N/A")); - complaintMap.put("OfficialMobile", complaintDetails.path("OfficialMobile").asText("N/A")); - complaintMap.put("Street", complaintDetails.path("Street").asText("N/A")); - complaintMap.put("Area", complaintDetails.path("Area").asText("N/A")); - complaintMap.put("Landmark", complaintDetails.path("Landmark").asText("N/A")); - complaintMap.put("Location", complaintDetails.path("Location").asText("N/A")); - complaintMap.put("Zone", complaintDetails.path("Zone").asText("N/A")); - complaintMap.put("Division", complaintDetails.path("Division").asText("N/A")); - String closedDate = complaintDetails.path("complaintcloseddate").asText("N/A"); - - // Check if the value is explicitly "null" (as a string) - if ("null".equalsIgnoreCase(closedDate)) { - closedDate = "N/A"; - } - - complaintMap.put("complaintcloseddate", closedDate); - complaintMap.put("parsedComplaintDate", parsedDate); - - // Add the complaint to the list - complaintsList.add(complaintMap); - } - - // Sort complaintsList by parsedComplaintDate in descending order - complaintsList.sort((a, b) -> { - Date dateA = (Date) a.get("parsedComplaintDate"); - Date dateB = (Date) b.get("parsedComplaintDate"); - if (dateA == null && dateB == null) return 0; - if (dateA == null) return 1; - if (dateB == null) return -1; - return dateB.compareTo(dateA); - }); - - for (Map complaint : complaintsList) { - complaint.remove("parsedComplaintDate"); - } - } - resultMap.put("status", "success"); - resultMap.put("complaints", complaintsList); - } else { - resultMap.put("status", "error"); - resultMap.put("message", "Failed to retrieve complaint details."); - } - } catch (Exception e) { - e.printStackTrace(); - resultMap.put("status", "error"); - resultMap.put("message", "Error processing request"); - } - - return resultMap; - } - - - @GetMapping("/getqcsubmittedcalls") - public List> getSubmittedList(@RequestParam int userId) - { - return qaqcCallsService.getSubmitDetails(userId); - } - - /* - * System.out.println("Computed Start Date: " + startDate); - * System.out.println("Computed End Date: " + endDate); - * System.out.println("Computed Year: " + complaintYear); - * System.out.println("Computed MobileNumber: " + complaintMobileNumber); - * - * String url - * ="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintListWithImg&From_date=" - * +startDate+"&To_date="+endDate+ - * "&jsonResp=Yes&UserType=Public&Token=&PageIndex=null&Status=null&repYear="+ - * complaintYear+"&MobileNo="+complaintMobileNumber; - * - * System.out.println("Request URL: " + url); - * - */ - - - private String sendWhatsappMsg(String pname,String cat,String mob_no, String complaintNumber) { - String urlString = ""; - - //urlString="https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=5c995535-6244-11f0-98fc-02c8a5e042bd&from=919445061913&to="+mob_no+"&templateid=3285616&type=template&placeholders="+pname+"||"+cat+"||"+complaintNumber+"&button_placeholder="+complaintNumber; - - try { - - String placeholders = - URLEncoder.encode( - pname + "|~|" + cat + "|~|" + complaintNumber, - StandardCharsets.UTF_8.toString()); - - String buttonPlaceholder = - URLEncoder.encode( - complaintNumber, - StandardCharsets.UTF_8.toString()); - - String mobile = - URLEncoder.encode( - mob_no, - StandardCharsets.UTF_8.toString()); - - - urlString="https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=5c995535-6244-11f0-98fc-02c8a5e042bd&from=919445061913&to="+mobile+"&templateid=3285616&type=template&placeholders="+placeholders+"&button_placeholder="+buttonPlaceholder; - - String res = hitURL(urlString); - return res; - - } catch (Exception e) { - e.printStackTrace(); - return ""; - } - - - } - - private String hitURL(String urlString) { - String response = ""; - try { - URL url = new URL(urlString); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = String.valueOf(responseCode); - //System.out.println("Response Code for URL: " + urlString + " is " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("response=" + response); - return response; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcPgrComplaintsMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcPgrComplaintsMainController.java deleted file mode 100644 index bdb7187d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcPgrComplaintsMainController.java +++ /dev/null @@ -1,38 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAgentsService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/callcenterqaqccomplaintsregistration") -@Controller("callCenterQaQcComplaintsRegistrationController") -public class QaqcPgrComplaintsMainController { - - @Autowired - private QaqcAgentsService agentsService; - - @GetMapping("/pgrcomplaint") - public String viewPGRpage(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId",userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - return "modules/callcenterqaqc/pgrcomplaints"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java deleted file mode 100644 index 7df25593..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java +++ /dev/null @@ -1,68 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAdminSettingService; -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcTaskListService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("gcc/api/callcenterqaqc/qaqctasklist") -@RestController -public class QaqcTaskListAPIController { - - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - - @Autowired - public QaqcTaskListAPIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private QaqcTaskListService tasklist; - - @GetMapping("/overalltaskcount") - public List> getComplaintAndCallStatusCounts( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - List> counts = tasklist.getComplaintAndCallStatusCounts(startDate, endDate); - //System.out.println("overallcounts:" + counts); - return counts; - } - - - - @GetMapping("/taskdatacount") - public List> getTaskwiseData( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - List> taskdata = tasklist.getTaskwiseData(startDate, endDate); - //System.out.println("taskdata "+ taskdata); - return taskdata; - } - - - - @GetMapping("/agentdatacount") - public List> getAgentwiseData(@RequestParam String qaqc_id) - { - List> agentwisedata = tasklist.getAgentwiseData(qaqc_id); - //System.out.println("agentdata "+agentwisedata); - return agentwisedata; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ReportsMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ReportsMainController.java deleted file mode 100644 index 29ec48ae..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ReportsMainController.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - - -@RequestMapping("/gcc/callcenterqaqcreports") -@Controller("callCenterQaQcReportsController") -public class ReportsMainController { - - - @GetMapping("/overallreport") - public String viewOverallReports(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - return "modules/callcenterqaqc/overallreport"; - } - - - @GetMapping("/qaqctasklist") - public String viewqaqctasklist(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - - return "modules/callcenterqaqc/qaqctasklist"; - } - - @GetMapping("/qaqcagentperformance") - public String viewAgentPerformance(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String agent_name=LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("agent_name", agent_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/callcenterqaqc/qaqcagentperformance"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ScpApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ScpApiController.java deleted file mode 100644 index 400a7210..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ScpApiController.java +++ /dev/null @@ -1,563 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; -import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.ScpService; - -@RestController -@RequestMapping("/gcc/api/scp") -public class ScpApiController { - - - @Autowired - private RestTemplate restTemplate; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private ScpService scpservice; - - @GetMapping("/getdatabyfilters") - public Map getdatabyfilters( - @RequestParam String startDate, - @RequestParam String endDate, - @RequestParam String zone, - @RequestParam String ward) { - - Map response = new HashMap<>(); - - try { - - DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - String formattedStartDate = LocalDate.parse(startDate, inputFormat).format(outputFormat); - String formattedEndDate = LocalDate.parse(endDate, inputFormat).format(outputFormat); - - // Build API URL - String apiUrl = "https://gccservices.in/gccofficialapp/api/asset/scpfilterReports" - + "?assetTypeId=2" - + "&fromDate=" + formattedStartDate - + "&toDate=" + formattedEndDate - + "&loginId=5662"; - - if (!zone.isEmpty()) { - apiUrl += "&zone=" + zone; - } - if (!ward.isEmpty()) { - apiUrl += "&ward=" + ward; - } - - System.out.println("apiUrl=" + apiUrl); - - // Call the external API - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity apiResponse = restTemplate.getForEntity(apiUrl, String.class); - - if (apiResponse.getStatusCode().is2xxSuccessful() && apiResponse.getBody() != null) { - - ObjectMapper mapper = new ObjectMapper(); - - // Parse full JSON - JsonNode rootNode = mapper.readTree(apiResponse.getBody()); - - // Extract "scpreport" array - JsonNode reportNode = rootNode.path("scpreport"); - - if (reportNode.isMissingNode() || !reportNode.isArray() || reportNode.size() == 0) { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } else { - // Convert JSON array → List> - List> reportList = mapper.convertValue( - reportNode, - new TypeReference>>() {} - ); - - response.put("status", "success"); - response.put("data", reportList); - if(zone.isEmpty() && ward.isEmpty()) { - response.put("table", "table1"); - } - else if(ward.isEmpty() && !zone.isEmpty()) { - response.put("table", "table2"); - } - else if(!ward.isEmpty() && !zone.isEmpty()) { - response.put("table", "table3"); - } - - } - } else { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - @GetMapping("/getzones") - public ResponseEntity> getzones() { - String apiUrl = "https://gccservices.in/gccrestservices/dropdown/api/zone"; - Map responseMap = new HashMap<>(); - - try { - RestTemplate restTemplate = new RestTemplate(); - String response = restTemplate.getForObject(apiUrl, String.class); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode rootArray = objectMapper.readTree(response); - - // ✅ The response is an array, so get the first element - if (rootArray.isArray() && rootArray.size() > 0) { - JsonNode firstObject = rootArray.get(0); - - boolean status = firstObject.path("status").asBoolean(false); - - if (status) { - JsonNode dataArray = firstObject.path("data"); - responseMap.put("status", "success"); - responseMap.put("code", 200); - responseMap.put("message", "Data found"); - responseMap.put("data", objectMapper.convertValue( - dataArray, new TypeReference>>() {})); - return ResponseEntity.ok(responseMap); - } else { - responseMap.put("status", "failure"); - responseMap.put("code", 404); - responseMap.put("message", "No Zones found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap); - } - } else { - responseMap.put("status", "failure"); - responseMap.put("code", 404); - responseMap.put("message", "Invalid response format"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap); - } - - } catch (Exception ex) { - responseMap.put("status", "error"); - responseMap.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value()); - responseMap.put("message", "Unexpected error occurred"); - responseMap.put("details", ex.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseMap); - } - } - - - @GetMapping("/getwardbyzone") - public ResponseEntity> getwardbyzone( @RequestParam String zone) { - String apiUrl = "https://gccservices.in/gccrestservices/dropdown/api/wardbyzone?zoneId="+zone; - Map responseMap = new HashMap<>(); - - try { - RestTemplate restTemplate = new RestTemplate(); - String response = restTemplate.getForObject(apiUrl, String.class); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode rootArray = objectMapper.readTree(response); - - // ✅ The response is an array, so get the first element - if (rootArray.isArray() && rootArray.size() > 0) { - JsonNode firstObject = rootArray.get(0); - - boolean status = firstObject.path("status").asBoolean(false); - - if (status) { - JsonNode dataArray = firstObject.path("data"); - responseMap.put("status", "success"); - responseMap.put("code", 200); - responseMap.put("message", "Data found"); - responseMap.put("data", objectMapper.convertValue( - dataArray, new TypeReference>>() {})); - return ResponseEntity.ok(responseMap); - } else { - responseMap.put("status", "failure"); - responseMap.put("code", 404); - responseMap.put("message", "No Zones found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap); - } - } else { - responseMap.put("status", "failure"); - responseMap.put("code", 404); - responseMap.put("message", "Invalid response format"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap); - } - - } catch (Exception ex) { - responseMap.put("status", "error"); - responseMap.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value()); - responseMap.put("message", "Unexpected error occurred"); - responseMap.put("details", ex.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseMap); - } - } - - - @GetMapping("/getstreetdetails") - public Map getstreetdetails( - @RequestParam String startDate, - @RequestParam String endDate, - @RequestParam String variable) { - - Map response = new HashMap<>(); - - try { - DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - String formattedStartDate = LocalDate.parse(startDate, inputFormat).format(outputFormat); - String formattedEndDate = LocalDate.parse(endDate, inputFormat).format(outputFormat); - - // 🔹 Call external API - String apiUrl = "https://gccservices.in/gccofficialapp/api/asset/scpReportAssetList" - + "?assetTypeId=2" - + "&fromDate=" + formattedStartDate - + "&toDate=" + formattedEndDate - + "&loginId=5662" - + "&status=Cleaned" - + "&streetid=" + variable; - - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity apiResponse = restTemplate.getForEntity(apiUrl, String.class); - - List> reportData = new ArrayList<>(); - - if (apiResponse.getStatusCode().is2xxSuccessful() && apiResponse.getBody() != null) { - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(apiResponse.getBody()); - JsonNode reportNode = rootNode.path("scpreport"); - - if (reportNode.isArray() && reportNode.size() > 0) { - reportData = mapper.convertValue( - reportNode, - new TypeReference>>() {} - ); - } - } - - if (reportData.isEmpty()) { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } else { - // 🔹 Enrich each data item with questions_part - List> enrichedData = scpservice.enrichScpReportWithQuestions(reportData); - - response.put("status", "success"); - response.put("data", enrichedData); - } - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - -// @PostMapping("/saveanswer") -// public ResponseEntity> saveAnswer(@RequestBody List> answers) { -// Map response = new HashMap<>(); -// -// try { -// boolean success = scpservice.saveAnswers(answers); -// if (success) { -// response.put("status", "success"); -// response.put("message", "Feedback submitted successfully!"); -// return ResponseEntity.ok(response); -// } else { -// response.put("status", "error"); -// response.put("message", "Fail to Save."); -// return ResponseEntity.status(500).body(response); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// response.put("status", "error"); -// response.put("message", "Exception: " + e.getMessage()); -// return ResponseEntity.status(500).body(response); -// } -// } - - - @PostMapping("/saveanswer") - public ResponseEntity> saveAnswer(@RequestBody List> answers) { - Map response = new HashMap<>(); - - try { - String result = scpservice.saveAnswers(answers); - - if ("success".equals(result)) { - response.put("status", "success"); - response.put("message", "Feedback submitted successfully!"); - return ResponseEntity.ok(response); - - } else if ("duplicate".equals(result)) { - response.put("status", "duplicate"); - response.put("message", "Already submitted by another one, So refresh the page"); - return ResponseEntity.ok(response); - - } else { - response.put("status", "error"); - response.put("message", "Fail to Save."); - return ResponseEntity.ok(response); - } - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", "Exception: " + e.getMessage()); - return ResponseEntity.status(500).body(response); - } - } - - - - @GetMapping("/getreportdatabyfilters") - public Map getreportdatabyfilters( - @RequestParam String startDate, - @RequestParam String endDate, - @RequestParam String zone, - @RequestParam String ward) { - - Map response = new HashMap<>(); - - try { - - DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - String formattedStartDate = LocalDate.parse(startDate, inputFormat).format(outputFormat); - String formattedEndDate = LocalDate.parse(endDate, inputFormat).format(outputFormat); - - // Build API URL - String apiUrl = "https://gccservices.in/gccofficialapp/api/asset/scpfilterReports" - + "?assetTypeId=2" - + "&fromDate=" + formattedStartDate - + "&toDate=" + formattedEndDate - + "&loginId=5662"; - - if (!zone.isEmpty()) { - apiUrl += "&zone=" + zone; - } - if (!ward.isEmpty()) { - apiUrl += "&ward=" + ward; - } - - System.out.println("apiUrl=" + apiUrl); - - // Call the external API - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity apiResponse = restTemplate.getForEntity(apiUrl, String.class); - - if (apiResponse.getStatusCode().is2xxSuccessful() && apiResponse.getBody() != null) { - - ObjectMapper mapper = new ObjectMapper(); - - // Parse full JSON - JsonNode rootNode = mapper.readTree(apiResponse.getBody()); - - // Extract "scpreport" array - JsonNode reportNode = rootNode.path("scpreport"); - - if (reportNode.isMissingNode() || !reportNode.isArray() || reportNode.size() == 0) { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } else { - // Convert JSON array → List> - List> reportList = mapper.convertValue( - reportNode, - new TypeReference>>() {} - ); - - - // Declare dbMap outside conditional blocks - Map> dbMap = new HashMap<>(); - List> dbList = new ArrayList<>(); -/* - // Fetch DB data based on filters - if (zone.isEmpty() && ward.isEmpty()) { - dbList = scpservice.getZoneWiseReportData(); - dbMap = dbList.stream().collect(Collectors.toMap( - row -> String.valueOf(row.get("zone")), - row -> row - )); - } else if (ward.isEmpty() && !zone.isEmpty()) { - dbList = scpservice.getWardWiseReportData(zone); - dbMap = dbList.stream().collect(Collectors.toMap( - row -> String.valueOf(row.get("ward")), - row -> row - )); - } else if (!ward.isEmpty() && !zone.isEmpty()) { - dbList = scpservice.getStreetWiseReportData(zone, ward); - dbMap = dbList.stream().collect(Collectors.toMap( - row -> String.valueOf(row.get("streetid")), - row -> row - )); - } - */ - // Fetch DB data based on filters - if (zone.isEmpty() && ward.isEmpty()) { - - dbList = scpservice.getZoneWiseReportData(); - - for (Map row : dbList) { - String key = String.valueOf(row.get("zone")); - dbMap.put(key, row); - } - - } else if (ward.isEmpty() && !zone.isEmpty()) { - - dbList = scpservice.getWardWiseReportData(zone); - - for (Map row : dbList) { - String key = String.valueOf(row.get("ward")); - dbMap.put(key, row); - } - - } else if (!ward.isEmpty() && !zone.isEmpty()) { - - dbList = scpservice.getStreetWiseReportData(zone, ward); - - for (Map row : dbList) { - String key = String.valueOf(row.get("streetid")); - dbMap.put(key, row); - } - } - - - // Merge API data with DB data - // Merge API data with DB data - for (int i = 0; i < reportList.size(); i++) { - Map apiRow = reportList.get(i); - String variableValue = String.valueOf(apiRow.get("VARIABLE")); - boolean isLast = (i == reportList.size() - 1); // check if it's the last element - - if (dbMap.containsKey(variableValue)) { - Map dbRow = dbMap.get(variableValue); - apiRow.put("Completed", dbRow.get("Completed")); - apiRow.put("Yes", dbRow.get("YesCount")); - apiRow.put("No", dbRow.get("NoCount")); - apiRow.put("Available", dbRow.get("AvailableCount")); - apiRow.put("Not Available", dbRow.get("NotAvailableCount")); - apiRow.put("Image Not Clear", dbRow.get("ImageNotClearCount")); - apiRow.put("LidGoodYesCount", dbRow.get("LidGoodYesCount")); - apiRow.put("LidGoodNoCount", dbRow.get("LidGoodNoCount")); - } else { - // If last list → use "-" - if (isLast) { - apiRow.put("Completed", "-"); - apiRow.put("Yes", "-"); - apiRow.put("No", "-"); - apiRow.put("Available", "-"); - apiRow.put("Not Available", "-"); - apiRow.put("Image Not Clear", "-"); - apiRow.put("LidGoodYesCount", "-"); - apiRow.put("LidGoodNoCount", "-"); - } else { - // For all others → use 0 - apiRow.put("Completed", 0); - apiRow.put("Yes", 0); - apiRow.put("No", 0); - apiRow.put("Available", 0); - apiRow.put("Not Available", 0); - apiRow.put("Image Not Clear", 0); - apiRow.put("LidGoodYesCount", 0); - apiRow.put("LidGoodNoCount", 0); - } - } - } - - - response.put("status", "success"); - response.put("data", reportList); - if(zone.isEmpty() && ward.isEmpty()) { - response.put("table", "table1"); - } - else if(ward.isEmpty() && !zone.isEmpty()) { - response.put("table", "table2"); - } - else if(!ward.isEmpty() && !zone.isEmpty()) { - response.put("table", "table3"); - } - - } - } else { - response.put("status", "nodata"); - response.put("data", Collections.emptyList()); - } - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - - @GetMapping("/getdetailreportdata") - public Map getDetailreportdatabyfilters( - @RequestParam String startDate, - @RequestParam String endDate) { - - Map response = new HashMap<>(); - - try { - - List> list=scpservice.getdetailreport(startDate,endDate); - - if(list.isEmpty()) { - response.put("status", "nodata"); - response.put("message", "No Data"); - } - else { - response.put("status", "success"); - response.put("data", list); - response.put("message", "Fetched Data Successfully"); - } - } - catch (Exception e) { - e.printStackTrace(); - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ScpMaincontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ScpMaincontroller.java deleted file mode 100644 index 868d60b2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ScpMaincontroller.java +++ /dev/null @@ -1,55 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.QaqcAgentsService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/callcenterqaqcscp") -@Controller("callCenterQaQcScpController") -public class ScpMaincontroller { - - @Autowired - private QaqcAgentsService agentsService; - - @GetMapping("/scpverification") - public String viewDomesticWastepage(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId",userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - return "modules/callcenterqaqc/scpverification"; - } - - - @GetMapping("/scpreport") - public String viewReportPage(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId",userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - List> agent=agentsService.getAgentName(userId); - model.addAttribute("agent", agent); - - return "modules/callcenterqaqc/scpreport"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaApiController.java deleted file mode 100644 index 79dd3795..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaApiController.java +++ /dev/null @@ -1,464 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.multipart.MultipartFile; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.SocialMediaService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("gcc/api/callcenterqaqc/socialmedia") -@RestController -public class SocialMediaApiController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public SocialMediaService socialservice; - - @Autowired - public SocialMediaApiController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @PostMapping("/update") - @ResponseBody - public ResponseEntity updateCallDetails(@RequestParam("complaintNumber") String complaintNumber, - @RequestParam("userId") String userId,@RequestParam("action") String action,@RequestParam("remarks") String remarks, - @RequestParam(value = "remainderDate", required = false) String remainderDate - ) { - try { -// System.out.println("Updating Complaint Number: " + complaintNumber); -// System.out.println("userId= " + userId); -// System.out.println("action= " + action); -// System.out.println("remarks="+remarks); - int updated_agent = Integer.parseInt(userId); -// System.out.println("remainderDate: " + remainderDate); - if(remarks.isEmpty()) - { - remarks="N/A"; - } - - String erp_name=socialservice.getErpusernamebyId(userId); -// System.out.println("erp_name=="+erp_name); - if (erp_name.isEmpty()) { - return ResponseEntity.ok("erpname"); - } - - if ("COMPLETED".equals(action) || "REOPEN".equals(action)) - { - boolean statusUpdated =ChangeStatusInErp(complaintNumber,action,remarks,erp_name); - //System.out.println("statusUpdated="+statusUpdated); - - if (!statusUpdated) - { - return ResponseEntity.ok("error"); - } - } - - - Map details =getDetailsByComplaintNumber(complaintNumber); - int rowInserted=socialservice.uploadComplaintDetailsInLogs(details,action,remarks,updated_agent,remainderDate); - if(rowInserted!=1) - { - return ResponseEntity.ok("save"); - } - return ResponseEntity.ok("Success"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - } - - public Map getDetailsByComplaintNumber(String complaintNumber) { - - Map resultMap = new HashMap<>(); - - try { - String url = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintByID&ComplaintId=" - + complaintNumber + "&imgUrlonly=yes&isQcuser=Yes&jsonResp=Yes"; - //System.out.println("Request URL: " + url); - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - String responseBody = responseEntity.getBody(); - //System.out.println("Response Body: " + responseBody); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(responseBody); - - JsonNode complaintDetails = rootNode.path(0).path("ComplaintListHistory").path(0); - - String registerDate=complaintDetails.path("complaintopendate").asText("N/A"); - //System.out.println("registerdate====="+registerDate); - - String formattedDate = "N/A"; // Default value if parsing fails - - if (!registerDate.equals("N/A") && !registerDate.isEmpty()) { - try { - // Parse the input date string - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); - Date date = inputFormat.parse(registerDate); - - // Format the date to dd-MM-yyyy - SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy"); - formattedDate = outputFormat.format(date); - } catch (Exception e) { - e.printStackTrace(); // Log exception for debugging - } - } - - if (!complaintDetails.isMissingNode()) { - // Existing fields - resultMap.put("complaintid", complaintDetails.path("complaintid").asText("N/A")); - resultMap.put("complaintdate", formattedDate); - resultMap.put("complainantName", complaintDetails.path("CustomerName").asText("N/A")); - resultMap.put("mobileNumber", complaintDetails.path("CustomerMobile").asText("N/A")); - resultMap.put("complaintType", complaintDetails.path("complainttype").asText("N/A")); - resultMap.put("description", complaintDetails.path("complaintdetails").asText("N/A")); - resultMap.put("currentStatus", complaintDetails.path("complaintcurrentstatus").asText("N/A")); - resultMap.put("Street", complaintDetails.path("Street").asText("N/A")); - resultMap.put("Area", complaintDetails.path("Area").asText("N/A")); - resultMap.put("Landmark", complaintDetails.path("Landmark").asText("N/A")); - resultMap.put("Location", complaintDetails.path("Location").asText("N/A")); - resultMap.put("Zone", complaintDetails.path("Zone").asText("N/A")); - resultMap.put("Division", complaintDetails.path("Division").asText("N/A")); - resultMap.put("OfficialMobile", complaintDetails.path("OfficialMobile").asText("N/A")); - resultMap.put("gender", complaintDetails.path("GENDER").asText("N/A")); - resultMap.put("deptname",complaintDetails.path("DEPT_NAME").asText("N/A")); - resultMap.put("compmode", complaintDetails.path("COMP_MODE").asText("N/A")); - resultMap.put("Officialname", complaintDetails.path("Officialname").asText("N/A")); - - - } - } else { - resultMap.put("error", "Failed to retrieve complaint details."); - } - } catch (Exception e) { - e.printStackTrace(); - resultMap.put("error", "Error processing request"); - } - - return resultMap; - } - - - public boolean ChangeStatusInErp(String complaintNumber,String action ,String remarks,String erp_name) { - String baseUrl = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?"; - String status = ""; - - - //String Erpname ="QAops1"; - - try { - // Encode parameters - String encodedComplaintNumber = URLEncoder.encode(complaintNumber, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - String encodedRemarks = URLEncoder.encode(remarks, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - String encodedErpname = URLEncoder.encode(erp_name, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - - // Determine status based on action - if ("COMPLETED".equals(action)) { - status = "11"; - } else if ("REOPEN".equals(action)) { - status = "9"; - } else { - return false; // Invalid action, return false - } - - // Construct the URL - String urlString = baseUrl - + "serviceId=UpdateComplaint" - + "&ComplaintId=" + encodedComplaintNumber - + "&Message=" + encodedRemarks - + "&UserType=Official" - + "&Status=" + status - + "&Comp_Image=" - + "&erp_username=" + encodedErpname; - - System.out.println("ERP Hitting URL="+urlString); - - // Send the request - return sendRequest(urlString); - // return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - - private boolean sendRequest(String urlString) { - try { - URL url = new URL(urlString); - URLConnection urlcon = url.openConnection(); - InputStream stream = urlcon.getInputStream(); - StringBuilder responseBuilder = new StringBuilder(); - int i; - while ((i = stream.read()) != -1) { - responseBuilder.append((char) i); - } - stream.close(); - - // Parse the response - String response = responseBuilder.toString(); - //System.out.println("Raw Response: " + response); - - // Check ResultStatus in the response - if (response.contains("\"ResultStatus\": true")) { - //System.out.println("ResultStatus is true in the response."); - return true; - } else { - System.out.println("ResultStatus is false or not present in the response."); - return false; - } - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - @GetMapping("/getsocialmediacomps") - public Map viewSocialMediaData( - @RequestParam String startDate, - @RequestParam String endDate, - @RequestParam String status, - @RequestParam String group, - @RequestParam String type, - @RequestParam String zone, - @RequestParam String region) { - Map response = new HashMap<>(); - - try { - - LocalDate fromLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ISO_DATE); - LocalDate toLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ISO_DATE); - String formattedFromDate = fromLocalDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); - String formattedToDate = toLocalDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); - - String mode="SOCIAL MEDIA"; - - String encoded_mode=URLEncoder.encode(mode, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - - //String url="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+encoded_mode+"&Zoneid="+zone; - - //String url="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+mode+"&Zoneid="+zone; - - String url="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+mode+"&Zoneid="+zone+"&RegionId="+region; - - //System.out.println("url==="+url); - - RestTemplate restTemplate = new RestTemplate(); - - // Fetch response as String - ResponseEntity responses = restTemplate.getForEntity(url, String.class); - String rawResponse = responses.getBody(); - - // Preprocess response to remove invalid characters if needed - if (rawResponse != null) { - //rawResponse = rawResponse.replaceAll("\"\"", "\""); // Replace double-double quotes - //rawResponse = rawResponse.replaceAll("(? responseMap = objectMapper.readValue(rawResponse, Map.class); - List> details; - details = (List>) responseMap.get("Details"); - //System.out.println("details="+details); - - - if (details != null) { - if(status.equals("redressed") || status.equals("closed")) { - - details=socialservice.getfiltreddetails(details); - } - } - - if (details == null) { - response.put("status", "nodata"); - response.put("message", "No Data, please change criteria"); - } - else { - response.put("status", "success"); - response.put("details", details); - } - - } - catch (Exception e) { - response.put("status", "error"); - response.put("message", "An error occurred while fetching data."); - e.printStackTrace(); - } - - return response; - } - - @GetMapping("/socialmediacompletedlist") - public Map viewSocialMediaCompletedData( - @RequestParam String startDate, - @RequestParam String endDate, @RequestParam String status, - @RequestParam String zone) { - - //System.out.printf("==================="+startDate,endDate,zone); - Map response = new HashMap<>(); - - try { - - LocalDate fromLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ISO_DATE); - LocalDate toLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ISO_DATE); - String formattedFromDate = fromLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); - String formattedToDate = toLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); - - List> details= socialservice.getdetails(formattedFromDate,formattedToDate,status,zone); - if(details==null) - { - response.put("status", "nodata"); - response.put("message", "No data for Selected filter"); - } - else { - response.put("status", "success"); - response.put("details", details); - } - } - catch (DateTimeParseException e) { - response.put("status", "error"); - response.put("message", "Invalid date format. Please use 'yyyy-MM-dd'."); - e.printStackTrace(); - } - catch (Exception e) { - response.put("status", "error"); - response.put("message", "An error occurred while fetching data."); - e.printStackTrace(); - } - - return response; - } - - @GetMapping("/getA1dropdowns") - public ResponseEntity getA1dropdowns(){ - try { - List> list = socialservice.getA1dropdowns(); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @GetMapping("/getA2dropdowns") - public ResponseEntity getA2dropdowns(){ - try { - List> list = socialservice.getA2dropdowns(); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @GetMapping("/checkregisteredcomplaint") - public Map checkRegisteredComplaint( - @RequestParam String complaintNumber) { - - return socialservice.checkRegisteredComplaint(complaintNumber); - } - - @PostMapping("/submitRegClosingComplaint") - public Map submitRegClosingComplaint( - @RequestParam String complaintNumber, - @RequestParam String remarks, - @RequestParam MultipartFile resolvedImage, - @RequestParam String cby) { - - - return socialservice.submitRegClosingComplaint( - complaintNumber, - remarks, - resolvedImage, - cby); - } - - @GetMapping("/getfilteredregcomps") - public Map getFilteredRegComps() { - - return socialservice.getFilteredRegComps(); - } - - @PostMapping("/approveComplaint") - @ResponseBody - public Map approveComplaint( - @RequestParam String complaintId, - @RequestParam String remarks, - @RequestParam String imgFullPath, - @RequestParam String userid - ) { - - - return socialservice.approveComplaint( - complaintId, - remarks, - imgFullPath, - userid); - } - - @PostMapping("/rejectComplaint") - public Map rejectComplaint( - @RequestParam String complaintId, - @RequestParam String userid - ) { - - return socialservice.rejectComplaint( - complaintId, - userid); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaMainController.java deleted file mode 100644 index 38416eae..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaMainController.java +++ /dev/null @@ -1,50 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/callcenterqaqcsocialmedia") -@Controller("callCenterQaQcSocialMediaController") -public class SocialMediaMainController { - - @GetMapping("/socialmediacomplaints") - public String viewSocialMediaComplaints(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId", userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - return "modules/callcenterqaqc/socialmediacomplaints"; - } - - - @GetMapping("/smfinishedcomplaints") - public String viewSocialMediaCompletedComplaints(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(loginUserId); - - model.addAttribute("LoginUserId", loginUserId); - model.addAttribute("userId", userId); - model.addAttribute("agent_name", LoginUserInfo.getCurrentUserDetails().getUsername()); - model.addAttribute("UserRole", LoginUserInfo.getUserRole()); - - return "modules/callcenterqaqc/socialmediacompletedlist"; - } - - @GetMapping("/regcompclosing") - public String viewregCompClosing(Model model) { - - String userId = LoginUserInfo.getLoginUserId(); - model.addAttribute("userId", userId); - - return "modules/callcenterqaqc/socialmediaregcompclosing"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java deleted file mode 100644 index 3181074b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java +++ /dev/null @@ -1,82 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.StatusCountService; - -@RequestMapping("gcc/api/callcenterqaqc") -@RestController -public class StatusCountController { - - @Autowired - private StatusCountService statusCountService; - - - @Autowired - public StatusCountController(StatusCountService statusCountService) { - this.statusCountService = statusCountService; - } - - @GetMapping("/dashboard") - public ResponseEntity> getDashboardData( - @RequestParam(value = "startDate", required = false, defaultValue = "") String fromDate, - @RequestParam(value = "endDate", required = false, defaultValue = "") String toDate, - @RequestParam(value = "dropdown1", required = false, defaultValue = "") String compType, - @RequestParam(value = "dropdown2", required = false, defaultValue = "") String zoneName, - @RequestParam(value = "dropdown3", required = false,defaultValue = "") String compMode, - @RequestParam(value = "dropdown4", required = false, defaultValue = "") String compGroup, - @RequestParam(value = "regiondropdown", required = false, defaultValue = "") String region) { - - - Map counts = statusCountService.fetchComplaintCounts(fromDate, toDate, compType, zoneName, compMode, compGroup,region); - //System.out.println("counts:" + counts); - //System.out.println("group:" + compGroup); - return ResponseEntity.ok(counts); - } - - - @GetMapping("/getComplaintTypesByGroup") - public ResponseEntity> getComplaintTypesByGroup(@RequestParam String group) { - List complaintTypes = statusCountService.fetchComplaintTypes(group); - return ResponseEntity.ok(complaintTypes); - } - - - @GetMapping("/getComplaintGroup") - public ResponseEntity> getComplaintGroup() { - List complaintGroup= statusCountService.fetchComplaintGroup(); - //System.out.println("types:"+complaintTypes); - return ResponseEntity.ok(complaintGroup); - } - - - @GetMapping("/getModes") - public ResponseEntity> getModes() { - List modes= statusCountService.fetchModes(); - //System.out.println("types:"+modes); - return ResponseEntity.ok(modes); - } - - - @GetMapping("/getZones") - public ResponseEntity> getZones() { - List zones= statusCountService.fetchZones(); - //System.out.println("types:"+zones); - return ResponseEntity.ok(zones); - } - - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/WhatsappController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/WhatsappController.java deleted file mode 100644 index d439d73d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/WhatsappController.java +++ /dev/null @@ -1,358 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.controller; - -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.callcenterqaqc.service.WhatsappqaqcMsgService; - -@RestController("callcenterqaqcwhatsapp") -@RequestMapping("/gcc/api/qaqc/whatsapp") -public class WhatsappController { - - @Autowired - private WhatsappqaqcMsgService whatsappqaqcMsgService; - - @PostMapping("/send-whatsapp-message") - public ResponseEntity sendWhatsAppMessage(@RequestParam String msgUrl,@RequestParam String tamilmsgUrl) { - String response = whatsappqaqcMsgService.sendMsg(msgUrl,tamilmsgUrl); - return ResponseEntity.ok(response); - } - - @GetMapping("/checkforwhatsappmsg") - public boolean checkforwhatsappmsg( - @RequestParam String complaintNumber, - @RequestParam String action, - @RequestParam String complaintTypeName, - @RequestParam String mobnumber, - @RequestParam String pname) { - - Map ismsg = - whatsappqaqcMsgService.checkforwhatsappmsg( - complaintNumber, - action); - - String returnedAction = - String.valueOf(ismsg.get("action")); - - boolean status = - Boolean.TRUE.equals(ismsg.get("status")); - - System.out.println("Action = " + returnedAction); - System.out.println("Status = " + status); - - if (status) { - - String result = sendWhatsappMsg(pname, complaintTypeName, mobnumber, complaintNumber,returnedAction); - if(result.equals("200")) { - System.out.println(returnedAction+" Whatsapp Message Triggered for "+complaintNumber); - return true; - } - else { - System.out.println(returnedAction+ " Whatsapp Message Failed for "+complaintNumber); - return false; - } - } - - return false; - } - - private String sendWhatsappMsg(String pname,String cat,String mob_no, String complaintNumber,String returnedAction) { - String urlString = ""; - - try { - - - String placeholders = - URLEncoder.encode( - pname + "|~|" + cat + "|~|" + complaintNumber, - StandardCharsets.UTF_8.toString()); - - String buttonPlaceholder = - URLEncoder.encode( - complaintNumber+ "|~|" +complaintNumber, - StandardCharsets.UTF_8.toString()); - - String mobile = - URLEncoder.encode( - mob_no, - StandardCharsets.UTF_8.toString()); - - - if("COMPLETED".equalsIgnoreCase(returnedAction)) { - - urlString="https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=5c995535-6244-11f0-98fc-02c8a5e042bd&from=919445061913&to="+mobile+"&templateid=3310383&type=template&placeholders="+placeholders; - - } - - if("UNATTENDED".equalsIgnoreCase(returnedAction)) { - - - urlString="https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=5c995535-6244-11f0-98fc-02c8a5e042bd&from=919445061913&to="+mobile+"&templateid=3304038&type=template&placeholders="+placeholders+"&button_placeholder="+buttonPlaceholder; - - } - - - String res = hitURL(urlString); - return res; - - } catch (Exception e) { - e.printStackTrace(); - return ""; - } - - - } - - private String hitURL(String urlString) { - String response = ""; - try { - URL url = new URL(urlString); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = String.valueOf(responseCode); - System.out.println("Response Code for Whatsapp msg URL: " + urlString + " is " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("response=" + response); - return response; - } - -// @GetMapping("/getclosefromuser") -// public String getclosefromuser(@RequestParam String complaintNumber) { -// -// return whatsappqaqcMsgService.getclosefromuser(complaintNumber); -// -// } - - @GetMapping(value = "/getclosefromuser", produces = "text/html") - public String getclosefromuser(@RequestParam String complaintNumber) { - - String result = whatsappqaqcMsgService.getclosefromuser(complaintNumber); - - boolean success = result.contains("Successfully"); - String color = success ? "#28a745" : "#dc3545"; - - String logoUrl = "https://gccservices.in/gcc/assets/images/logo.png"; - - //background: #f5f5f5; - - return """ - - - - - GCC PGR Complaint Status - - - -
- -
- GCC Logo -

Thanks For Your Response !!!

-
- -
-

%s

-
- - - -
- - - """.formatted(color, logoUrl, result); - } - - - @GetMapping(value="/getreopenfromuser", produces = "text/html") - public String getreopenfromuser(@RequestParam String complaintNumber) { - - String result= whatsappqaqcMsgService.getreopenfromuser(complaintNumber); - - boolean success = result.contains("Successfully"); - String color = success ? "#28a745" : "#dc3545"; - - String logoUrl = "https://gccservices.in/gcc/assets/images/logo.png"; - - //background: #f5f5f5; - - return """ - - - - - GCC PGR Complaint Status - - - -
- -
- GCC Logo -

Thanks For Your Response !!!

-
- -
-

%s

-
- - - -
- - - """.formatted(color, logoUrl, result); - - } - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/ComplaintService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/ComplaintService.java deleted file mode 100644 index 0ddba511..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/ComplaintService.java +++ /dev/null @@ -1,95 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -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.sql.DataSource; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.apache.naming.java.javaURLContextFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class ComplaintService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - private final String baseUrl = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice"; - - public String fetchComplaintCategories() { - RestTemplate restTemplate = new RestTemplate(); - String url = baseUrl + "?serviceId=getComplCategory&ComplaintGroupId=null"; - return restTemplate.getForObject(url, String.class); - } - - public String fetchComplaintSubTypes(String groupId) { - RestTemplate restTemplate = new RestTemplate(); - String url = baseUrl + "?serviceId=getComplCategory&ComplaintGroupId=" + groupId; - return restTemplate.getForObject(url, String.class); - } - - public List> fetchComplaintDetailsById(String complaintId) { - RestTemplate restTemplate = new RestTemplate(); - String url = baseUrl + "?serviceId=getComplaintByID&ComplaintId=" + complaintId; - String response = restTemplate.getForObject(url, String.class); - - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(response, new TypeReference>>() { - }); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public List> fetchComplaintDetailsByMobile(String mobileNo) { - RestTemplate restTemplate = new RestTemplate(); - String url = baseUrl - + "?serviceId=getComplaintListWithImg&From_date=01/01/2024&To_date=20/08/2024&jsonResp=Yes&UserType=Public&MobileNo=" - + mobileNo + "&PageIndex=null&Status=null&repYear=2024"; - String response = restTemplate.getForObject(url, String.class); - - try { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(response, new TypeReference>>() { - }); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public int saveInLogs(String mobileNo, String complaintNo,String userId) { - - int agent_id; - try { - agent_id = Integer.parseInt(userId); - } catch (NumberFormatException e) { - return 0; - } - - String sql = "INSERT INTO pgr_complaint_reg (user_mobile_num, complaint_number, agent_id) VALUES (?, ?, ?)"; - return jdbcTemplate.update(sql, mobileNo, complaintNo, agent_id); - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/DomesticWasteService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/DomesticWasteService.java deleted file mode 100644 index 398cee05..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/DomesticWasteService.java +++ /dev/null @@ -1,308 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Service -public class DomesticWasteService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Value("${fileBaseUrl}") - private String fileBaseUrl; - - @Autowired - public void setDatasource(@Qualifier("mysqlDomesticWasteDataSource") DataSource datasource) { - this.jdbcTemplate=new JdbcTemplate(datasource); - } - - - - public Map saveMultipleWasteRequests(String user_name, String mobile, String address, - String latitude, String longitude, - String street_name, String street_id, String remarks, - String itemsJson,String userId,String zone, String ward) { - - - int agent_id=Integer.parseInt(userId); - int is_app=3; - String remarks1; - if (remarks == null || remarks.trim().isEmpty()) { - remarks1 = "-"; - } else { - remarks1 = remarks; - } - - try { - - ObjectMapper objectMapper = new ObjectMapper(); - List> items = objectMapper.readValue(itemsJson, new TypeReference<>() {}); - - String sofaSize = null; // declare before lambda - for (Map item : items) { - if ("2".equals(item.get("item_id").toString())) { // Sofa id = 2 - Object sizeObj = item.get("sofa_size"); // match your JS payload key - if (sizeObj != null && !sizeObj.toString().isEmpty()) { - sofaSize = sizeObj.toString(); - } - break; // found sofa, no need to loop further - } - } - - final String finalSofaSize = sofaSize; - - - // Step 1: Insert main request (one time) - String insertMainSql = "INSERT INTO user_request_table " + - "(request_id, user_name, mobile, address, latitude, longitude, street_name, street_id, remarks,agent_id,is_app,zone,division,sofa_type) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(con -> { - PreparedStatement ps = con.prepareStatement(insertMainSql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, "TEMP"); // placeholder - ps.setString(2, user_name); - ps.setString(3, mobile); - ps.setString(4, address); - ps.setString(5, latitude); - ps.setString(6, longitude); - ps.setString(7, street_name); - ps.setString(8, street_id); - ps.setString(9, remarks1); - ps.setInt(10, agent_id); - ps.setInt(11, is_app); - ps.setString(12, zone); - ps.setString(13, ward); - ps.setString(14, finalSofaSize); - return ps; - }, keyHolder); - - int generatedId = keyHolder.getKey().intValue(); - String requestId = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + generatedId; - - // Update request_id in user_request_table - jdbcTemplate.update("UPDATE user_request_table SET request_id = ? WHERE id = ?", requestId, generatedId); - - - String insertItemSql = "INSERT INTO items (iteam_id, quantity, req_table_id, requedt_id) VALUES (?, ?, ?, ?)"; - - for (Map item : items) { - Object itemIdObj = item.get("item_id"); - Object quantityObj = item.get("quantity"); - - if (itemIdObj == null || quantityObj == null) { - continue; - } - - int itemId = Integer.parseInt(itemIdObj.toString()); - int quantity = Integer.parseInt(quantityObj.toString()); - - jdbcTemplate.update(insertItemSql, itemId, quantity, generatedId, requestId); - } - - return Map.of("status", true,"message", "Request saved successfully","requestId", requestId); - - } - catch (Exception e) { - e.printStackTrace(); - return Map.of("status", false, "message", "Error: " + e.getMessage()); - } - } - - - - - public List> getAllComplaintsList(String startDate, String endDate, String mobile, String requestId) { - StringBuilder sql = new StringBuilder( - "SELECT u.*, sm.status_master AS status_name, DATE(u.cdate) AS created_date " + - "FROM user_request_table u " + - "JOIN status_master sm ON sm.id = u.status_id " + - "WHERE u.is_active = 1 AND u.is_delete = 0 AND sm.is_active = 1 AND sm.is_delete = 0 " - ); - - List params = new ArrayList<>(); - - if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) { - sql.append(" AND DATE(u.cdate) BETWEEN ? AND ? "); - params.add(startDate); - params.add(endDate); - } - - if (mobile != null && !mobile.isEmpty()) { - sql.append(" AND u.mobile = ? "); - params.add(mobile); - } - - if (requestId != null && !requestId.isEmpty()) { - sql.append(" AND u.request_id = ? "); - params.add(requestId); - } - - List> result = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - - for (Map complaint : result) { - Number reqTableId = (Number) complaint.get("id"); - List> itemList = getItemsByRequestId(reqTableId.intValue()); - complaint.put("items", itemList); - } - - return result; - } - - - - public List> getpendingcomplaints(String startDate, String endDate, String mobile) { - - StringBuilder sql = new StringBuilder("SELECT u.*, sm.status_master AS status_name, DATE(u.cdate) AS created_date" - + " FROM user_request_table u " - + " JOIN status_master sm ON sm.id = u.status" - + " WHERE u.is_active = 1 AND u.is_delete = 0 AND u.status IN (1,3) " - ); - - List params = new ArrayList<>(); - - if (startDate != null && !startDate.isEmpty() && endDate != null && !endDate.isEmpty()) { - sql.append(" AND DATE(u.cdate) BETWEEN ? AND ? "); - params.add(startDate); - params.add(endDate); - } - - if (mobile != null && !mobile.isEmpty()) { - sql.append(" AND u.mobile = ? "); - params.add(mobile); - } - - List> result = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - - for (Map complaint : result) { - Number reqTableId = (Number) complaint.get("id"); - List> itemList = getItemsByRequestId(reqTableId.intValue()); - complaint.put("items", itemList); - } - - return result; - } - - public List> getItemsByRequestId(int reqTableId) { - String itemSql = "SELECT i.iteam_id, im.item_name, i.quantity " + - "FROM items i " + - "LEFT JOIN item_master im ON i.iteam_id = im.id " + - "WHERE i.is_active = 1 AND i.is_delete = 0 AND i.req_table_id = ?"; - return jdbcTemplate.queryForList(itemSql, reqTableId); - } - - - - public List> getDetailsByReqId(String requestId) { - - String sql = "SELECT " + - "u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " + - "u.zone, u.division, u.street_name, u.quantity AS main_quantity, u.remarks, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " + - "DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, " + - "u.is_active, u.is_delete, u.street_id, sm.status_master AS status, u.is_app, " + - "DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " + - "itm.iteam_id, itm.quantity, im.item_name " + - "FROM user_request_table u " + - "LEFT JOIN items itm ON u.id = itm.req_table_id " + - "LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " + - "LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " + - "WHERE u.request_id = ? AND u.is_active = 1"; - - List> rawList = jdbcTemplate.queryForList(sql, requestId); - - Map> groupedMap = new LinkedHashMap<>(); - - for (Map row : rawList) { - Integer id = (Integer) row.get("id"); - - Map item = null; - if (row.get("item_name") != null) { - item = new LinkedHashMap<>(); - item.put("item_name", row.get("item_name")); - item.put("quantity", row.get("quantity")); - } - - if (groupedMap.containsKey(id)) { - if (item != null) { - ((List>) groupedMap.get(id).get("items")).add(item); - } - } else { - Map newEntry = new LinkedHashMap<>(); - newEntry.put("id", id); - newEntry.put("request_id", row.get("request_id")); - newEntry.put("user_name", row.get("user_name")); - newEntry.put("mobile", row.get("mobile")); - newEntry.put("address", row.get("address")); - newEntry.put("latitude", row.get("latitude")); - newEntry.put("longitude", row.get("longitude")); - newEntry.put("zone", row.get("zone")); - newEntry.put("division", row.get("division")); - newEntry.put("street_name", row.get("street_name")); - newEntry.put("main_quantity", row.get("main_quantity")); - newEntry.put("remarks", row.get("remarks")); - newEntry.put("image_url", row.get("image_url")); - newEntry.put("cdate", row.get("cdate")); - newEntry.put("is_active", row.get("is_active")); - newEntry.put("is_delete", row.get("is_delete")); - newEntry.put("street_id", row.get("street_id")); - newEntry.put("status", row.get("status")); // Now this is human-readable - newEntry.put("is_app", row.get("is_app")); - newEntry.put("close_date", row.get("close_date")); - newEntry.put("officer_upload_url", row.get("officer_upload_url")); - - List> items = new ArrayList<>(); - if (item != null) { - items.add(item); - } - newEntry.put("items", items); - - groupedMap.put(id, newEntry); - } - } - - return new ArrayList<>(groupedMap.values()); - } - - - - public boolean changeStatus(String requestId, String remarks, String userId) { - String sql = "UPDATE user_request_table " + - "SET status = 5, " + - "officer_remark = ?, " + - "cancelled_by = ?, " + - "rejecttype = 'Without Location', " + - "reject_latitude = 0.0, " + - "reject_longitude = 0.0 " + - "WHERE request_id = ?"; - - int result = jdbcTemplate.update(sql, remarks, userId, requestId); - return result > 0; - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/FollowUpService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/FollowUpService.java deleted file mode 100644 index 69ffe9f9..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/FollowUpService.java +++ /dev/null @@ -1,224 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.time.LocalDateTime; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class FollowUpService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> getFollowUpCalls(int agent_id) { - String query = "SELECT data_id, complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, " + - "complaint_type, official_name, official_mobilenum, call_category, complaint_mode, department " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE call_category = 'OFFICIALFOLLOWUP' AND agent_id = ? AND is_processed = FALSE"; - - return jdbcTemplate.queryForList(query, agent_id); - } - - public List> getFollowUpCatergory() - { - String query = "SELECT call_status " + - "FROM gcc_1913_qaqc.call_status WHERE call_category_id = 2 and isactive='1'"; - - return jdbcTemplate.queryForList(query); - } - -//public List> getAgentCallStatus(int agentId) { -// -// String query = "SELECT " + -// " (SELECT SUM(aa.data_count) " + -// " FROM agent_assigned aa " + -// " WHERE aa.agent_id = ?) AS total_data_count, " + -// " COUNT(CASE WHEN cl.call_status = 'COMPLETED' THEN 1 END) AS completed_count, " + -// " COUNT(CASE WHEN cl.call_status != 'COMPLETED' THEN 1 END) AS pending_count " + -// "FROM " + -// " qaqc_call_logs cl " + -// "WHERE " + -// " cl.agent_id = ?"; -// return jdbcTemplate.queryForList(query,agentId); -// -// } - - public void updateFollowupComplaintDetails(String complaintNumber,int dataId, String action, String remarks,int updated_agent) - { - String query = "UPDATE gcc_1913_qaqc.qaqc_upload_data " + - "SET call_status = ?, " + " remarks = ?, updated_agent=?," + - " updated_date = CURRENT_TIMESTAMP, " + " is_processed = TRUE " + - "WHERE data_id = ? " +" AND complaint_number = ? "; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks,updated_agent, dataId,complaintNumber); - - //System.out.println("Rows Updated in upload data: " + rowsUpdated); - } - - @Transactional - public int uploadComplaintDetailsInLogs(Map logDetails, String action, String complaintNumber, String remainderDate) { - //System.out.println("Complaint Details: " + logDetails); - // Extract other field values from complaintDetails - int qaqcid = (int) logDetails.get("qaqc_id"); - String ccategory = logDetails.get("call_category").toString(); - String personName = logDetails.get("complaint_person_name").toString(); - String personMobNo = logDetails.get("complaint_mobilenumber").toString(); - String complaintDate = logDetails.get("complaint_date").toString(); - String cType = logDetails.get("complaint_type").toString(); - String cMode = logDetails.get("complaint_mode").toString(); - String department = logDetails.get("department").toString(); - String cGroup = logDetails.get("complaint_group").toString(); - String officialName = logDetails.get("official_name").toString(); - String officialMobileNum = logDetails.get("official_mobilenum").toString(); - String callStatus = logDetails.get("call_status").toString(); - String remarks = logDetails.get("remarks").toString(); - int agentId = (int) logDetails.get("agent_id"); - int updated_agent=(int)logDetails.get("updated_agent"); - boolean isProcessed = (boolean)logDetails.get("is_processed"); - LocalDateTime currentDate = LocalDateTime.now(); - - // Determine which table to insert into based on the action - if (action.equals("FOLLOWUP")) { - - - String query ="INSERT INTO gcc_1913_qaqc.qaqc_followup_call_logs (qaqc_id, call_category, agent_id, complaint_number, complaint_date,complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name,remainder_date, official_mobilenum, call_status, remarks,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - - int rowsAffected = jdbcTemplate.update(query, qaqcid, ccategory, agentId, complaintNumber, complaintDate,personName, - personMobNo, cType, cMode, department, cGroup, officialName,remainderDate, officialMobileNum, callStatus, remarks, - updated_agent); - //System.out.println("Rows Updated in qaqc_followup_call_logs : " + rowsAffected); - } - - String query1 = "INSERT INTO gcc_1913_qaqc.qaqc_call_logs (qaqc_id, call_category, agent_id, complaint_number,complaint_date, complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, call_status, remarks, is_processed,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - int rowsAffected1 = jdbcTemplate.update(query1, qaqcid, ccategory, agentId, complaintNumber,complaintDate, personName, - personMobNo, cType, cMode, department, cGroup, officialName, officialMobileNum, callStatus, remarks, - isProcessed,updated_agent); - - //System.out.println("Rows Updated in qaqc_call_logs: " + rowsAffected1); - - return rowsAffected1; - - } - - /* - @Transactional - public int uploadComplaintDetailsInLogs(Map logDetails, String action, String complaintNumber, String remainderDate) { - //System.out.println("Complaint Details: " + logDetails); - // Extract other field values from complaintDetails - int qaqcid = (int) logDetails.get("qaqc_id"); - String ccategory = logDetails.get("call_category").toString(); - String personName = logDetails.get("complaint_person_name").toString(); - String personMobNo = logDetails.get("complaint_mobilenumber").toString(); - String complaintDate = logDetails.get("complaint_date").toString(); - String cType = logDetails.get("complaint_type").toString(); - String cMode = logDetails.get("complaint_mode").toString(); - String department = logDetails.get("department").toString(); - String cGroup = logDetails.get("complaint_group").toString(); - String officialName = logDetails.get("official_name").toString(); - String officialMobileNum = logDetails.get("official_mobilenum").toString(); - String callStatus = logDetails.get("call_status").toString(); - String remarks = logDetails.get("remarks").toString(); - int agentId = (int) logDetails.get("agent_id"); - int updated_agent=(int)logDetails.get("updated_agent"); - boolean isProcessed = (boolean)logDetails.get("is_processed"); - LocalDateTime currentDate = LocalDateTime.now(); - - // Determine which table to insert into based on the action - if (action.equals("FOLLOWUP")) { - String query = "UPDATE gcc_1913_qaqc.qaqc_followup_call_logs " - + "SET qaqc_id = ?, call_category = ?, agent_id = ?, remainder_date = ?, call_status = ?, remarks = ?, updated_agent = ?, updated_date = CURRENT_TIMESTAMP " - + "WHERE complaint_number = ? " - + "AND id = (SELECT max_id FROM (SELECT MAX(id) AS max_id FROM gcc_1913_qaqc.qaqc_followup_call_logs WHERE complaint_number = ?) AS temp)"; - - int rowsAffected = jdbcTemplate.update(query,qaqcid, ccategory,agentId,remainderDate, callStatus, remarks,updated_agent,complaintNumber,complaintNumber); - //System.out.println("Rows Updated in qaqc_followup_call_logs : " + rowsAffected); - - - String query1 = "INSERT INTO gcc_1913_qaqc.qaqc_call_logs (qaqc_id, call_category, agent_id, complaint_number, complaint_date,complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name,remainder_date, official_mobilenum, call_status, remarks, is_processed,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?)"; - - int rowsAffected1 = jdbcTemplate.update(query1, qaqcid, ccategory, agentId, complaintNumber, complaintDate,personName, - personMobNo, cType, cMode, department, cGroup, officialName,remainderDate, officialMobileNum, callStatus, remarks, - isProcessed,updated_agent); - //System.out.println("Rows Updated in qaqc_call_logs : " + rowsAffected1); - - return rowsAffected + rowsAffected1; - - } else { - - String query = "UPDATE gcc_1913_qaqc.qaqc_followup_call_logs " - + "SET qaqc_id = ?, call_category = ?, agent_id = ?, call_status = ?, remarks = ?, updated_agent = ?, updated_date = CURRENT_TIMESTAMP " - + "WHERE complaint_number = ? " - + "AND id = (SELECT max_id FROM (SELECT MAX(id) AS max_id FROM gcc_1913_qaqc.qaqc_followup_call_logs WHERE complaint_number = ?) AS temp)"; - - int rowsAffected = jdbcTemplate.update(query,qaqcid, ccategory,agentId, callStatus, remarks,updated_agent,complaintNumber,complaintNumber); - //System.out.println("Rows Updated in qaqc_followup_call_logs : " + rowsAffected); - - String query1 = "INSERT INTO gcc_1913_qaqc.qaqc_call_logs (qaqc_id, call_category, agent_id, complaint_number,complaint_date, complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, call_status, remarks, is_processed,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - int rowsAffected1 = jdbcTemplate.update(query1, qaqcid, ccategory, agentId, complaintNumber,complaintDate, personName, - personMobNo, cType, cMode, department, cGroup, officialName, officialMobileNum, callStatus, remarks, - isProcessed,updated_agent); - - //System.out.println("Rows Updated in qaqc_call_logs: " + rowsAffected1); - - return rowsAffected + rowsAffected1; - } - } - */ - - public List> getCallHistory(String complaintNumber) - { - String query = "SELECT complaint_number, agent_id, remainder_date, remarks, created_date " + - "FROM gcc_1913_qaqc.qaqc_call_logs " + - "WHERE complaint_number = ? and call_status='FOLLOWUP'"; - return jdbcTemplate.queryForList(query, complaintNumber); - - } - - public List> getFollowupSubmitDetails(int userId) { - - String query = "SELECT complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber,official_name,official_mobilenum, " + - "complaint_type, call_status, remarks " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE call_category = 'OFFICIALFOLLOWUP' AND agent_id = ? AND is_processed = '1'"; - - return jdbcTemplate.queryForList(query,userId); - - } - - public void updateComplaintHistoryDetails(String complaintNumber, int dataId, String action, String remarks,int updated_agent, - String remainderDate) { - - String query = "UPDATE gcc_1913_qaqc.qaqc_upload_data_history \r\n" - + "SET call_status = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP, remainder_date = ?,updated_agent=?\r\n" - + "WHERE data_id = ? AND complaint_number = ?"; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks, remainderDate, updated_agent,dataId, complaintNumber); - - //System.out.println("Rows Updated in upload history: " + rowsUpdated); - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/InprogresscallService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/InprogresscallService.java deleted file mode 100644 index 80af3d69..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/InprogresscallService.java +++ /dev/null @@ -1,102 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -@Service -public class InprogresscallService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - public List> getActionsCatergory() - { - String query = "SELECT call_status " + - "FROM gcc_1913_qaqc.call_status WHERE call_category_id = 3 and isactive='1'"; - - return jdbcTemplate.queryForList(query); - } - -// public List> getInProgressCalls(int agent_id) { -// String sql = "SELECT complaint_number, " + -// " official_name , " + -// " official_mobilenum , " + -// " complaint_type, " + -// " call_category, " + -// " complaint_mode, " + -// " department " + -// -// "FROM gcc_1913_qaqc.qaqc_upload_data " + -// "WHERE call_category ='inprogress' and agent_id= ?"; -// -// -// return jdbcTemplate.queryForList(sql, agent_id); -// } - - public List> getInProgressCalls(int agent_id) { - String query = "SELECT data_id, complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, " + - "complaint_type, official_name, official_mobilenum, call_category, complaint_mode, department " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE (call_category = 'PROCESSING' OR call_category = 'REOPENED' OR call_category = 'REDRESSED' OR call_category = 'INPROGRESS') " + - " AND is_processed = FALSE " + - " AND agent_id = ?"; - return jdbcTemplate.queryForList(query, agent_id); - } - - public void updateInprogressComplaintDetails(String complaintNumber,int dataId, String action, String remarks,int updated_agent) - { - String query = "UPDATE gcc_1913_qaqc.qaqc_upload_data " + - "SET call_status = ?, " + " remarks = ?,updated_agent=?, " + - " updated_date = CURRENT_TIMESTAMP, " + " is_processed = TRUE " + - "WHERE data_id = ? " +" AND complaint_number = ?"; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks,updated_agent, dataId,complaintNumber); - - //System.out.println("Rows Updated in upload data: " + rowsUpdated); - } - - public void saveMobileNumDetails(String complaintNumber, String remarks) { - String query = "insert into officer_mobileno (complaint_number,remarks) values(?,?)"; - int rowsUpdated = jdbcTemplate.update(query, complaintNumber, remarks); - //System.out.println("Rows Updated: " + rowsUpdated); - } - - public List> getInprogressSubmitDetails(int userId) { - - String query = "SELECT complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber,official_name,official_mobilenum, " + - "complaint_type, call_status, remarks " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE (call_category = 'PROCESSING' OR call_category = 'REOPENED' OR call_category = 'REDRESSED' OR call_category = 'INPROGRESS') AND agent_id = ? AND is_processed = '1'"; - - return jdbcTemplate.queryForList(query,userId); - - } - - - public void updateComplaintHistoryDetails(String complaintNumber, int dataId, String action, String remarks,int updated_agent, - String remainderDate) { - - String query = "UPDATE gcc_1913_qaqc.qaqc_upload_data_history \r\n" - + "SET call_status = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP, remainder_date = ?,updated_agent=?\r\n" - + "WHERE data_id = ? AND complaint_number = ?"; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks, remainderDate,updated_agent, dataId, complaintNumber); - - //System.out.println("Rows Updated in upload data history: " + rowsUpdated); - - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/PublicFollowUpService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/PublicFollowUpService.java deleted file mode 100644 index 5c8ee3df..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/PublicFollowUpService.java +++ /dev/null @@ -1,52 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class PublicFollowUpService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> getFollowUpCalls(int agent_id) { - String query = "SELECT data_id, complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, " + - "complaint_type, official_name, official_mobilenum, call_category, complaint_mode, department " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE call_category = 'PUBLICFOLLOWUP' AND agent_id = ? AND is_processed = FALSE"; - - return jdbcTemplate.queryForList(query, agent_id); - } - - public List> getFollowUpCatergory() - { - String query = "SELECT call_status " + - "FROM gcc_1913_qaqc.call_status WHERE call_category_id = 4 and isactive='1'"; - - return jdbcTemplate.queryForList(query); - } - - public List> getFollowupSubmitDetails(int userId) { - - String query = "SELECT complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber,official_name,official_mobilenum, " + - "complaint_type, call_status, remarks " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE call_category = 'PUBLICFOLLOWUP' AND agent_id = ? AND is_processed = '1'"; - - return jdbcTemplate.queryForList(query,userId); - - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java deleted file mode 100644 index 10c63c1f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java +++ /dev/null @@ -1,123 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class QaqcAdminSettingService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional - public int updateProductivity(int productivity_count) { - String updateSql = "UPDATE productivity SET productivity_count=? where isactive='1' and isdelete='0'"; - return jdbcTemplate.update(updateSql,productivity_count); - - } - - @Transactional - public int saveProductivity(int productivity_count) { - String insertSql = "INSERT INTO productivity (productivity_count) VALUES (?)"; - return jdbcTemplate.update(insertSql, productivity_count); - - } - - @Transactional - public Integer getProductivity() { - String insertSql = "select productivity_count\r\n" - + "from productivity\r\n" - + "where isactive='1' and isdelete='0'" - + "LIMIT 1"; - return jdbcTemplate.queryForObject(insertSql, Integer.class); - - } - - @Transactional - public List> getAdminSettingCounts() { - - String sqlQuery = "SELECT " + - "COALESCE(p.productivity_count, 0) AS productivity_count, " + - "COUNT(al.agent_id) AS total_count, " + - "COALESCE(p.inbound_count, 0) AS inbound_count, " + - "COALESCE(p.outbound_count, 0) AS outbound_count, " + - "COALESCE(p.inbound_count, 0) + COALESCE(p.outbound_count, 0) As assigned, " + - "(COUNT(al.agent_id) - (COALESCE(p.inbound_count, 0) + COALESCE(p.outbound_count, 0))) AS notassigned " + - "FROM productivity p " + - "JOIN agents_list al " + - "WHERE p.isactive = '1' AND p.isdelete = '0' AND al.isactive = '1' AND al.isdelete = '0' " + - "GROUP BY p.productivity_count, p.inbound_count, p.outbound_count"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - - @Transactional - public int saveCallingTypeInSettings() { - // Query to get inbound and outbound counts - String selectSql = "SELECT\r\n" - + "SUM(CASE WHEN calling_type = 'INBOUND' THEN 1 ELSE 0 END) AS inbound, \r\n" - + "SUM(CASE WHEN calling_type = 'OUTBOUND' THEN 1 ELSE 0 END) AS outbound \r\n" - + "FROM agents_list \r\n" - + "WHERE isactive = '1' AND isdelete = '0'"; - - // Fetch the counts - Map result = jdbcTemplate.queryForMap(selectSql); - int inbound = ((Number) result.get("inbound")).intValue(); // Convert to int - int outbound = ((Number) result.get("outbound")).intValue(); // Convert to int - - //Corrected SQL syntax for updating multiple columns - String updateSql = "UPDATE productivity SET inbound_count = ?, outbound_count = ? WHERE isactive = '1' AND isdelete = '0'"; - return jdbcTemplate.update(updateSql, inbound, outbound); - } - - - @Transactional - public int updateCallType(String calling_type,int agent_id) { - String updateSql = "UPDATE agents_list SET calling_type=? WHERE agent_id=? AND isactive='1'"; - - return jdbcTemplate.update(updateSql,calling_type,agent_id); - } - - @Transactional - public List> getAgentsForCallingtype() - { - String sqlQuery = "select al.agent_id as agent_id,ap.username as username,al.agent_name as agent_name,al.mobile_number as mobile_number,\r\n" - + "al.calling_type as calling_type\r\n" - + "from gcc_1913_qaqc.agents_list al\r\n" - + "LEFT join gcc_apps.appusers ap on ap.userid=al.agent_id\r\n" - + "where al.isactive='1' and al.isdelete='0'"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - public int updateAgentName(int agentId, String updatedName) { - // Query to check if the name exists for another agent - String checkSql = "SELECT COUNT(*) FROM agents_list WHERE agent_name = ? AND agent_id <> ? AND isactive = '1'"; - - int count = jdbcTemplate.queryForObject(checkSql, Integer.class, updatedName, agentId); - - if (count > 0) { - return -1; // Indicate that the name already exists - } - - // Proceed with the update if the name is unique - String updateSql = "UPDATE agents_list SET agent_name = ? WHERE agent_id = ? AND isactive = '1'"; - return jdbcTemplate.update(updateSql, updatedName, agentId); - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentAssignService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentAssignService.java deleted file mode 100644 index 4a9cf40e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentAssignService.java +++ /dev/null @@ -1,1166 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; -import javax.transaction.Transactional; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import java.sql.PreparedStatement; -import java.sql.Statement; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import java.util.stream.Collectors; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Service -public class QaqcAgentAssignService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - private JdbcTemplate jdbcTemplate2; - - @Autowired - public void setDataSource2(@Qualifier("mysql1913CampaignDataSource") DataSource dataSource) { - this.jdbcTemplate2 = new JdbcTemplate(dataSource); - } - - @Transactional - public Integer getCampaignPendingCountForAgent(int agentId) { - String countQuery = "SELECT COUNT(ud.data_id) FROM gcc_1913_campaign.upload_data ud\r\n" - + "JOIN gcc_1913_campaign.campaign_request cr ON cr.campaign_id=ud.campaign_id\r\n" - + "WHERE cr.campaign_status='ONGOING' AND ud.agent_id = ? AND ud.call_status IS NULL"; - return jdbcTemplate2.queryForObject(countQuery, Integer.class, agentId); - } - - @Transactional - public List> getAvailableOutboundAgents() - { - String sqlQuery = "select agent_id,agent_name\r\n" - + "from gcc_1913_qaqc.agents_list\r\n" - + "where calling_type='OUTBOUND' and isactive='1' and isdelete='0'"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - @Transactional - public Integer getTodayCountForAgent(int agentId) { - String countQuery = "SELECT coalesce(sum(aa.data_count),0) as todaycounts \r\n" - + "from gcc_1913_qaqc.agent_assigned aa \r\n" - + "join gcc_1913_qaqc.agents_list al on al.agent_id=aa.agent_id \r\n" - + "where date(aa.created_date)=curdate() and al.agent_id=?"; - return jdbcTemplate.queryForObject(countQuery, Integer.class, agentId); - } - - - -// @Transactional -// public List> getAvailableOutboundAgents() -// { -// String sqlQuery = "SELECT al.agent_id as agent_id,al.agent_name as agent_name,coalesce(sum(aa.data_count),0) as todaycounts\r\n" -// + "from agent_assigned aa\r\n" -// + "join agents_list al on al.agent_id=aa.agent_id\r\n" -// + "where date(aa.created_date)=curdate() and al.calling_type='OUTBOUND' and al.isactive='1' and al.isdelete='0'\r\n" -// + "group by al.agent_id,al.agent_name"; -// -// return jdbcTemplate.queryForList(sqlQuery); -// } - - - @Transactional // Ensures atomicity of operations - public Map assignTasksTransactionally(Map requestData) { - Map response = new HashMap<>(); - // Extract input data - String description = (String) requestData.get("description"); - String fromDate = (String) requestData.get("startDate"); - String toDate = (String) requestData.get("endDate"); - String status = (String) requestData.get("closeName"); - - String group = (String) requestData.get("group"); - String type = (String) requestData.get("type"); - String mode = (String) requestData.get("mode"); - String zone= (String) requestData.get("zone"); - String region= (String) requestData.get("region"); - - int closedCount = Integer.parseInt(requestData.get("closedCount").toString()); - //System.out.println("closedCount====="+closedCount); - List> agents = (List>) requestData.get("agents"); - //System.out.println("agents====="+agents); - // Step 1: Save task details - LocalDate fromLocalDate = LocalDate.parse(fromDate, DateTimeFormatter.ISO_DATE); - LocalDate toLocalDate = LocalDate.parse(toDate, DateTimeFormatter.ISO_DATE); - String formattedFromDate = fromLocalDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); - String formattedToDate = toLocalDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); - - LocalDateTime now = LocalDateTime.now(); - ZonedDateTime indiaTime = now.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("Asia/Kolkata")); - String taskId = "#" + indiaTime.format(DateTimeFormatter.ofPattern("yyMMddHHmmss")); - //System.out.println("taskId==="+taskId); -// if ("closed".equalsIgnoreCase(status)) { -// status = "Action Taken Level 2"; -// } - - int rowsInserted = savetaskid(taskId, formattedFromDate, formattedToDate, description, status, closedCount,group,type,mode,zone,region); - - if (rowsInserted <= 0) { - throw new RuntimeException("Failed to create task"); - } - - // Step 2: Get the last task - List> lastTask = getLastTask(); - if (lastTask.isEmpty()) { - throw new RuntimeException("Failed to fetch last task"); - } - int qaqcId = (int) lastTask.get(0).get("qaqc_id"); - - - List> assignedIDList = new ArrayList<>(); - - //System.out.println("Before shuffle: " + agents); - - // Shuffle the agents list - Collections.shuffle(agents); - - //System.out.println("After shuffle: " + agents); - // Step 3: Save agents' task counts - for (Map agent : agents) { - Integer agentId = Integer.valueOf(agent.get("agentId").toString()); - Integer dataCounts = Integer.valueOf(agent.get("callsPerAgent").toString()); - assignedIDList.add( saveInAgentAssigned(agentId, qaqcId, dataCounts)); - } - //System.out.println("outside assignedIDList===="+assignedIDList); - - - // Step 4: Save upload data - if (!"officialfollowup".equalsIgnoreCase(status) && !"publicfollowup".equalsIgnoreCase(status)) - { - String url="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+mode+"&Zoneid="+zone+"&RegionId="+region; - System.out.println("url=="+url); - boolean isSaved = processAndSaveDetails(url, qaqcId, agents, status,assignedIDList, mode); - if (!isSaved) { - throw new RuntimeException("Failed to process upload data"); - } - } - else - { - boolean isSaved=processAndSaveFollowupDetails(qaqcId, agents, status,formattedFromDate); - if (!isSaved) { - throw new RuntimeException("Failed to process upload data"); - } - } - - - response.put("status", "success"); - response.put("message", "Data Transferred Successfully"); - return response; - } - - @Transactional - public List> getfollowupdata(String fromdate, String status) { - try { - // Parse input date from dd/MM/yyyy to yyyy-MM-dd - DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); - DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate formattedDate = LocalDate.parse(fromdate, inputFormatter); - - // Format the date into yyyy-MM-dd - String formattedFromDate = formattedDate.format(outputFormatter); - if (!"officialfollowup".equalsIgnoreCase(status)) - { - //String sqlQuery = "SELECT * FROM gcc_1913_qaqc.qaqc_followup_call_logs WHERE remainder_date = ? AND call_status='FOLLOWUP' AND call_category IN ('CLOSED','PUBLICFOLLOWUP')"; - String sqlQuery = "SELECT * FROM gcc_1913_qaqc.qaqc_followup_call_logs WHERE remainder_date = ? AND call_status='FOLLOWUP' AND call_category IN ('CLOSED','PUBLICFOLLOWUP') AND isactive=1"; - return jdbcTemplate.queryForList(sqlQuery, formattedFromDate); - } - else - { - //String sqlQuery = "SELECT * FROM gcc_1913_qaqc.qaqc_followup_call_logs WHERE remainder_date = ? AND call_status='FOLLOWUP' AND call_category NOT IN ('CLOSED','PUBLICFOLLOWUP')"; - String sqlQuery = "SELECT * FROM gcc_1913_qaqc.qaqc_followup_call_logs WHERE remainder_date = ? AND call_status='FOLLOWUP' AND call_category NOT IN ('CLOSED','PUBLICFOLLOWUP') AND isactive=1"; - return jdbcTemplate.queryForList(sqlQuery, formattedFromDate); - } - - } catch (DateTimeParseException e) { - throw new IllegalArgumentException("Invalid date format. Expected dd/MM/yyyy.", e); - } - } - - @Transactional - public boolean processAndSaveFollowupDetails(int qaqc_id, List> agents, String status, - String fromdate) { - try { - - List> detail = getfollowupdata(fromdate, status); - - - int index = 0; - - - for (Map agent : agents) { - int remainingDataCountForAgent = Integer.parseInt(agent.get("callsPerAgent").toString()); - // System.out.println(remainingDataCountForAgent); - int currentAgentId = Integer.parseInt(agent.get("agentId").toString()); - // System.out.println(agent.get("agentName").toString()); - - for (int i = 0; i < remainingDataCountForAgent && index < detail.size(); i++, index++) { - // System.out.println(i +" "+index); - // Save the current complaint details with the current agent_id - Integer isactive_id=(Integer) detail.get(index).get("id"); - - String complaintNumber = (String) detail.get(index).get("complaint_number"); - String complaintDate = (String) detail.get(index).get("complaint_date"); - String complanitPersonName = (String) detail.get(index).get("complaint_person_name"); - String complaintPersonMobileNum = (String) detail.get(index).get("complaint_mobilenumber"); - String complaintType = (String) detail.get(index).get("complaint_type"); - String complaintMode = (String) detail.get(index).get("complaint_mode"); - String department = (String) detail.get(index).get("department"); - String complaintGroup = (String) detail.get(index).get("complaint_group"); - String officerName = (String) detail.get(index).get("official_name"); - String officerMobileNumber = (String) detail.get(index).get("official_mobilenum"); - - String status3 = status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - // jdbcTemplate.update(insertQuery, qaqc_id,status3 - // ,complaintNumber,complaintDate, complanitPersonName, - // complaintPersonMobileNum, complaintType, complaintMode, department, - // complaintGroup, officerName, officerMobileNumber, currentAgentId); - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, - Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status3); - ps.setString(3, complaintNumber); - ps.setString(4, complaintDate); - ps.setString(5, complanitPersonName); - ps.setString(6, complaintPersonMobileNum); - ps.setString(7, complaintType); - ps.setString(8, complaintMode); - ps.setString(9, department); - ps.setString(10, complaintGroup); - ps.setString(11, officerName); - ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - - if (generatedDataId != null) { - long dataId = generatedDataId.longValue(); - // System.out.println("followdataId=="+dataId); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " - + "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status3, complaintNumber, complaintDate, complanitPersonName, - complaintPersonMobileNum, complaintType, complaintMode, department, complaintGroup, - officerName, officerMobileNumber, currentAgentId, dataId); - } - - //System.out.println("isactive_id===="+isactive_id); - - String upsql2 = "UPDATE gcc_1913_qaqc.qaqc_followup_call_logs set isactive=0 where id=?"; - jdbcTemplate.update(upsql2, isactive_id); - - } - } - return true; - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /* - @Transactional - public boolean processAndSaveFollowupDetails(int qaqc_id, List> agents,String status,String fromdate) { - try { - - List> detail=getfollowupdata(fromdate, status); - - int index = 0; - - for(Map agent: agents) { - int remainingDataCountForAgent = Integer.parseInt(agent.get("callsPerAgent").toString()); - //System.out.println(remainingDataCountForAgent); - int currentAgentId = Integer.parseInt(agent.get("agentId").toString()); - //System.out.println(agent.get("agentName").toString()); - - for (int i = 0; i < remainingDataCountForAgent && index < detail.size(); i++, index++) { - //System.out.println(i +" "+index); - // Save the current complaint details with the current agent_id - String complaintNumber = (String) detail.get(index).get("complaint_number"); - String complaintDate = (String) detail.get(index).get("complaint_date"); - String complanitPersonName = (String) detail.get(index).get("complaint_person_name"); - String complaintPersonMobileNum = (String) detail.get(index).get("complaint_mobilenumber"); - String complaintType = (String) detail.get(index).get("complaint_type"); - String complaintMode = (String) detail.get(index).get("complaint_mode"); - String department = (String) detail.get(index).get("department"); - String complaintGroup = (String) detail.get(index).get("complaint_group"); - String officerName = (String) detail.get(index).get("official_name"); - String officerMobileNumber = (String) detail.get(index).get("official_mobilenum"); - - - String status3=status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - //jdbcTemplate.update(insertQuery, qaqc_id,status3 ,complaintNumber,complaintDate, complanitPersonName, complaintPersonMobileNum, complaintType, complaintMode, department, complaintGroup, officerName, officerMobileNumber, currentAgentId); - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status3); - ps.setString(3, complaintNumber); - ps.setString(4, complaintDate); - ps.setString(5, complanitPersonName); - ps.setString(6, complaintPersonMobileNum); - ps.setString(7, complaintType); - ps.setString(8, complaintMode); - ps.setString(9, department); - ps.setString(10, complaintGroup); - ps.setString(11, officerName); - ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - - if (generatedDataId != null) { - long dataId = generatedDataId.longValue(); - //System.out.println("followdataId=="+dataId); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " + - "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status3, complaintNumber, complaintDate, complanitPersonName, - complaintPersonMobileNum, complaintType, complaintMode, department, - complaintGroup, officerName, officerMobileNumber, currentAgentId, dataId); - } - - } - } - return true; - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - */ - /* - @Transactional - public boolean processAndSaveDetails(String url, int qaqc_id, List> agents,String status,List> assignedIDList, String mode) { - try { - - RestTemplate restTemplate = new RestTemplate(); - - // Fetch response as String - ResponseEntity response = restTemplate.getForEntity(url, String.class); - String rawResponse = response.getBody(); - - // Preprocess response to remove invalid characters if needed - if (rawResponse != null) { -// rawResponse = rawResponse.replaceAll("\"\"", "\""); // Replace double-double quotes -// rawResponse = rawResponse.replaceAll("(? responseMap = objectMapper.readValue(rawResponse, Map.class); - - // Target the specific field where double-double quotes might appear - String targetField = "Address"; // Replace with the actual field name - if (responseMap.containsKey(targetField)) { - String fieldValue = (String) responseMap.get(targetField); - if (fieldValue != null && fieldValue.contains("\"\"")) { - // Clean double-double quotes in the field value - fieldValue = fieldValue.replaceAll("\"\"", "\""); - responseMap.put(targetField, fieldValue); // Update the field with cleaned value - } - } - - // Extract "Details" array from the response - List> details = (List>) responseMap.get("Details"); - //System.out.println(details); - if (details == null) { - System.err.println("No 'Details' found in the response."); - return false; // Or handle as per your requirement - } - if(mode.isEmpty() || mode.isBlank() || mode==null ) { - details=details.stream() - .filter(map-> !map.get("Complaint Mode").equals("SOCIAL MEDIA")).collect(Collectors.toList()); - } - - // Apply filtering based on the status value - if ("withdraw".equalsIgnoreCase(status)) { - // Keep only records where "Current Status" is "Completed" - details = details.stream() - .filter(entry -> "Completed".equals(entry.get("Current Status"))) - .collect(Collectors.toList()); - } else { - // Remove records where "Current Status" is "Completed" - details = details.stream() - .filter(entry -> !"Completed".equals(entry.get("Current Status"))) - .collect(Collectors.toList()); - } - - int index = 0; - - List> followupData= getFollowupData(); - - List> countDetails = new ArrayList<>(); - - for(Map agent: agents) { - int remainingDataCountForAgent = Integer.parseInt(agent.get("callsPerAgent").toString()); - //System.out.println(remainingDataCountForAgent); - int currentAgentId = Integer.parseInt(agent.get("agentId").toString()); - //System.out.println(agent.get("agentName").toString()); - - Map countResult = new HashMap<>(); - int assignedCount = 0; - - for (int i = 0; i < remainingDataCountForAgent && index < details.size(); i++, index++) { - - System.out.println("CHECK = "+index+" "+details.get(index).get("Complaint Mode")); - //System.out.println(i +" "+index); - - String complaintNumber1 = (String) details.get(index).get("Complaint Number"); - //System.out.println("complaintNumber = "+complaintNumber1); - - Map result = followupData.stream() - .filter(map -> complaintNumber1.equals(map.get("complaint_number"))) - .findFirst().orElse(null); - - String compnum = ""; - String callstatus =""; - Date calldate = null ; - if(result!= null) { - compnum = (String) result.get("complaint_number"); - callstatus = (String) result.get("call_status"); - calldate = (Date) result.get("remainder_date"); - } - - - if(!compnum.equals("") && compnum.equals(complaintNumber1)) { - //System.out.println("1 if complaintNumber = "+complaintNumber); - Date currentDate = new Date(); - if(!callstatus.equalsIgnoreCase("followup") && calldate.before(currentDate)) { - //System.out.println("2 if complaintNumber = "+complaintNumber1); - String complaintDate = (String) details.get(index).get("Complaint Opened Date"); - String complanitPersonName = (String) details.get(index).get("Complaint Person Name"); - String complaintPersonMobileNum = (String) details.get(index).get("Complaint Person Number"); - String complaintType = (String) details.get(index).get("Complaint Type"); - String complaintMode = (String) details.get(index).get("Complaint Mode"); - String department = (String) details.get(index).get("Department"); - String complaintGroup = (String) details.get(index).get("Complaint Group"); - String officerName = (String) details.get(index).get("Assign To"); - String officerMobileNumber = (String) details.get(index).get("Official Contact Number"); - String status1 = status.toUpperCase(); - - - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number,complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - //jdbcTemplate.update(insertQuery, qaqc_id, status1, complaintNumber1,complaintDate, complanitPersonName, complaintPersonMobileNum, complaintType, complaintMode, department, complaintGroup, officerName, officerMobileNumber, currentAgentId); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status); - ps.setString(3, complaintNumber1); - ps.setString(4, complaintDate); - ps.setString(5, complanitPersonName); - ps.setString(6, complaintPersonMobileNum); - ps.setString(7, complaintType); - ps.setString(8, complaintMode); - ps.setString(9, department); - ps.setString(10, complaintGroup); - ps.setString(11, officerName); - ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - // Retrieve the generated data_id - Number generatedDataId = keyHolder.getKey(); - if (generatedDataId != null) { - long dataId = generatedDataId.longValue(); - - //System.out.println("dataId if=="+dataId); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " + - "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status1, complaintNumber1, complaintDate, complanitPersonName, - complaintPersonMobileNum, complaintType, complaintMode, department, - complaintGroup, officerName, officerMobileNumber, currentAgentId, dataId); - - } - - - assignedCount++; - - } - - } else { - //System.out.println("else complaintNumber = "+complaintNumber1); - String complaintDate2 = (String) details.get(index).get("Complaint Opened Date"); - String complanitPersonName2 = (String) details.get(index).get("Complaint Person Name"); - String complaintPersonMobileNum2 = (String) details.get(index).get("Complaint Person Number"); - String complaintType2 = (String) details.get(index).get("Complaint Type"); - String complaintMode2 = (String) details.get(index).get("Complaint Mode"); - String department2 = (String) details.get(index).get("Department"); - String complaintGroup2 = (String) details.get(index).get("Complaint Group"); - String officerName2 = (String) details.get(index).get("Assign To"); - String officerMobileNumber2 = (String) details.get(index).get("Official Contact Number"); - String status2 = status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number,complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - //jdbcTemplate.update(insertQuery, qaqc_id, status2, complaintNumber1,complaintDate2, complanitPersonName2, complaintPersonMobileNum2, complaintType2, complaintMode2, department2, complaintGroup2, officerName2, officerMobileNumber2, currentAgentId); - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status2); - ps.setString(3, complaintNumber1); - ps.setString(4, complaintDate2); - ps.setString(5, complanitPersonName2); - ps.setString(6, complaintPersonMobileNum2); - ps.setString(7, complaintType2); - ps.setString(8, complaintMode2); - ps.setString(9, department2); - ps.setString(10, complaintGroup2); - ps.setString(11, officerName2); - ps.setString(12, officerMobileNumber2); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - - if (generatedDataId != null) { - long dataId2 = generatedDataId.longValue(); - //System.out.println("dataId2 else=="+dataId2); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " + - "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status2, complaintNumber1, complaintDate2, complanitPersonName2, - complaintPersonMobileNum2, complaintType2, complaintMode2, department2, - complaintGroup2, officerName2, officerMobileNumber2, currentAgentId, dataId2); - } - - - assignedCount++; - } - } - - countResult.put("assignedCount", assignedCount); - countResult.put("qaqc_id", qaqc_id); - countResult.put("agent_id", currentAgentId); - countDetails.add(countResult); - } - for(Map assgn : assignedIDList) { - - for(Map count : countDetails) { - - if(((int)assgn.get("agent_id"))==((int)count.get("agent_id"))) { - int assignedid = (int)assgn.get("assigned_id"); - int agentid = (int)assgn.get("agent_id"); - int assignedCount = (int)count.get("assignedCount"); - String sql = "UPDATE agent_assigned SET data_count = ? WHERE assigned_id = ? and agent_id = ?"; - jdbcTemplate.update(sql, assignedCount, assignedid, agentid); - } - } - } - - return true; - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - */ - - @Transactional - public boolean processAndSaveDetails(String url, int qaqc_id, List> agents, String status, - List> assignedIDList, String mode) { - try { - - RestTemplate restTemplate = new RestTemplate(); - - // Fetch response as String - ResponseEntity response = restTemplate.getForEntity(url, String.class); - String rawResponse = response.getBody(); - - // Preprocess response to remove invalid characters if needed - if (rawResponse != null) { -// rawResponse = rawResponse.replaceAll("\"\"", "\""); // Replace double-double quotes -// rawResponse = rawResponse.replaceAll("(? responseMap = objectMapper.readValue(rawResponse, Map.class); - - // Target the specific field where double-double quotes might appear - String targetField = "Address"; // Replace with the actual field name - if (responseMap.containsKey(targetField)) { - String fieldValue = (String) responseMap.get(targetField); - if (fieldValue != null && fieldValue.contains("\"\"")) { - // Clean double-double quotes in the field value - fieldValue = fieldValue.replaceAll("\"\"", "\""); - responseMap.put(targetField, fieldValue); // Update the field with cleaned value - } - } - - - // Extract "Details" array from the response - List> details = (List>) responseMap.get("Details"); - /* - // System.out.println(details); - if (details == null) { - System.err.println("No 'Details' found in the response."); - return false; // Or handle as per your requirement - } - - if (mode.isEmpty() || mode.isBlank() || mode == null) { - details = details.stream().filter(map -> !map.get("Complaint Mode").equals("SOCIAL MEDIA")) - .collect(Collectors.toList()); - } - - // Apply filtering based on the status value - if ("withdraw".equalsIgnoreCase(status)) { - // Keep only records where "Current Status" is "Completed" - //details = details.stream().filter(entry -> "Completed".equals(entry.get("Current Status"))).toList(); - details = details.stream() - .filter(entry -> "Completed".equals(entry.get("Current Status"))) - .collect(Collectors.toList()); - } else { - // Remove records where "Current Status" is "Completed" - //details = details.stream().filter(entry -> !"Completed".equals(entry.get("Current Status"))).toList(); - details = details.stream() - .filter(entry -> !"Completed".equals(entry.get("Current Status"))) - .collect(Collectors.toList()); - } - */ - - // Filter out SOCIAL MEDIA if mode is empty, blank, or null - if (mode == null || mode.isEmpty() || mode.trim().isEmpty()) { - List> filteredDetails = new ArrayList>(); - for (Map map : details) { - Object complaintMode = map.get("Complaint Mode"); - if (complaintMode == null || !"SOCIAL MEDIA".equals(complaintMode.toString())) { - filteredDetails.add(map); - } - } - details = filteredDetails; - } - - // Apply filtering based on the status value - if ("withdraw".equalsIgnoreCase(status)) { - // Keep only records where "Current Status" is "Completed" - List> filteredDetails = new ArrayList>(); - for (Map entry : details) { - Object currentStatus = entry.get("Current Status"); - if ("Completed".equals(currentStatus != null ? currentStatus.toString() : null)) { - filteredDetails.add(entry); - } - } - details = filteredDetails; - } else { - // Remove records where "Current Status" is "Completed" - List> filteredDetails = new ArrayList>(); - for (Map entry : details) { - Object currentStatus = entry.get("Current Status"); - if (!"Completed".equals(currentStatus != null ? currentStatus.toString() : null)) { - filteredDetails.add(entry); - } - } - details = filteredDetails; - } - int index = 0; - - List> followupData = getFollowupData(); - System.out.println("followupData=" + followupData); - - List> countDetails = new ArrayList<>(); - - for (Map agent : agents) { - int remainingDataCountForAgent = Integer.parseInt(agent.get("callsPerAgent").toString()); - // System.out.println(remainingDataCountForAgent); - int currentAgentId = Integer.parseInt(agent.get("agentId").toString()); - // System.out.println(agent.get("agentName").toString()); - - Map countResult = new HashMap<>(); - int assignedCount = 0; - - for (int i = 0; i < remainingDataCountForAgent && index < details.size(); i++, index++) { - - //System.out.println("CHECK = " + index + " " + details.get(index).get("Complaint Mode")); - // System.out.println(i +" "+index); - - String complaintNumber1 = (String) details.get(index).get("Complaint Number"); - // System.out.println("complaintNumber = "+complaintNumber1); -/* - Map result = followupData.stream() - .filter(map -> complaintNumber1.equals(map.get("complaint_number"))).findFirst() - .orElse(null); -*/ - Map result = null; - - if (followupData != null) { - for (Map map : followupData) { - Object complaintNumberValue = map.get("complaint_number"); - if (complaintNumber1 != null && complaintNumber1.equals(complaintNumberValue != null ? complaintNumberValue.toString() : null)) { - result = map; - break; // Stop at the first match - } - } - } - - String compnum = ""; - String callstatus = ""; - String callcat = ""; - Integer isactive_id = 0; - Date calldate = null; - if (result != null) { - compnum = (String) result.get("complaint_number"); - callstatus = (String) result.get("call_status"); - calldate = (Date) result.get("remainder_date"); - callcat = (String) result.get("call_category"); - isactive_id = (Integer) result.get("id"); - - } - - if (!compnum.equals("") && compnum.equals(complaintNumber1)) { - //System.out.println("1 if complaintNumber = " + complaintNumber1); - Date currentDate = new Date(); - - if (status.equalsIgnoreCase("CLOSED") || status.equalsIgnoreCase("PUBLICFOLLOWUP")) { - - if ((callcat.equalsIgnoreCase("CLOSED") || callcat.equalsIgnoreCase("PUBLICFOLLOWUP")) - && calldate.before(currentDate)) { - - //System.out.println("2 if complaintNumber = " + complaintNumber1); - String complaintDate = (String) details.get(index).get("Complaint Opened Date"); - String complanitPersonName = (String) details.get(index).get("Complaint Person Name"); - String complaintPersonMobileNum = (String) details.get(index) - .get("Complaint Person Number"); - String complaintType = (String) details.get(index).get("Complaint Type"); - String complaintMode = (String) details.get(index).get("Complaint Mode"); - String department = (String) details.get(index).get("Department"); - String complaintGroup = (String) details.get(index).get("Complaint Group"); - String officerName = (String) details.get(index).get("Assign To"); - String officerMobileNumber = (String) details.get(index).get("Official Contact Number"); - String status1 = status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number,complaint_date, " - + "complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, " - + "official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - // jdbcTemplate.update(insertQuery, qaqc_id, status1, - // complaintNumber1,complaintDate, complanitPersonName, - // complaintPersonMobileNum, complaintType, complaintMode, department, - // complaintGroup, officerName, officerMobileNumber, currentAgentId); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, - Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status); - ps.setString(3, complaintNumber1); - ps.setString(4, complaintDate); - ps.setString(5, complanitPersonName); - ps.setString(6, complaintPersonMobileNum); - ps.setString(7, complaintType); - ps.setString(8, complaintMode); - ps.setString(9, department); - ps.setString(10, complaintGroup); - ps.setString(11, officerName); - ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - // Retrieve the generated data_id - Number generatedDataId = keyHolder.getKey(); - if (generatedDataId != null) { - long dataId = generatedDataId.longValue(); - - // System.out.println("dataId if=="+dataId); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " - + "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status1, complaintNumber1, complaintDate, - complanitPersonName, complaintPersonMobileNum, complaintType, complaintMode, - department, complaintGroup, officerName, officerMobileNumber, - currentAgentId, dataId); - - } - - assignedCount++; - - String upsql = "UPDATE gcc_1913_qaqc.qaqc_followup_call_logs set isactive=0 where id=?"; - jdbcTemplate.update(upsql, isactive_id); - - } - - if (callcat.equalsIgnoreCase("REDRESSED") || callcat.equalsIgnoreCase("OFFICIALFOLLOWUP")) { - - //System.out.println("3 if complaintNumber = " + complaintNumber1); - String complaintDate = (String) details.get(index).get("Complaint Opened Date"); - String complanitPersonName = (String) details.get(index).get("Complaint Person Name"); - String complaintPersonMobileNum = (String) details.get(index) - .get("Complaint Person Number"); - String complaintType = (String) details.get(index).get("Complaint Type"); - String complaintMode = (String) details.get(index).get("Complaint Mode"); - String department = (String) details.get(index).get("Department"); - String complaintGroup = (String) details.get(index).get("Complaint Group"); - String officerName = (String) details.get(index).get("Assign To"); - String officerMobileNumber = (String) details.get(index).get("Official Contact Number"); - String status1 = status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number,complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - // jdbcTemplate.update(insertQuery, qaqc_id, status1, - // complaintNumber1,complaintDate, complanitPersonName, - // complaintPersonMobileNum, complaintType, complaintMode, department, - // complaintGroup, officerName, officerMobileNumber, currentAgentId); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, - Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status); - ps.setString(3, complaintNumber1); - ps.setString(4, complaintDate); - ps.setString(5, complanitPersonName); - ps.setString(6, complaintPersonMobileNum); - ps.setString(7, complaintType); - ps.setString(8, complaintMode); - ps.setString(9, department); - ps.setString(10, complaintGroup); - ps.setString(11, officerName); - ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - // Retrieve the generated data_id - Number generatedDataId = keyHolder.getKey(); - if (generatedDataId != null) { - long dataId = generatedDataId.longValue(); - - // System.out.println("dataId if=="+dataId); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " - + "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status1, complaintNumber1, complaintDate, - complanitPersonName, complaintPersonMobileNum, complaintType, complaintMode, - department, complaintGroup, officerName, officerMobileNumber, - currentAgentId, dataId); - - } - - assignedCount++; - - String upsql1 = "UPDATE gcc_1913_qaqc.qaqc_followup_call_logs set isactive=0 where id=?"; - jdbcTemplate.update(upsql1, isactive_id); - } - - } - - else if (status.equalsIgnoreCase("REDRESSED") || status.equalsIgnoreCase("OFFICIALFOLLOWUP")) { - - if ((callcat.equalsIgnoreCase("REDRESSED") || callcat.equalsIgnoreCase("OFFICIALFOLLOWUP")) - && calldate.before(currentDate)) { - - //System.out.println("2 if complaintNumber = " + complaintNumber1); - String complaintDate = (String) details.get(index).get("Complaint Opened Date"); - String complanitPersonName = (String) details.get(index).get("Complaint Person Name"); - String complaintPersonMobileNum = (String) details.get(index) - .get("Complaint Person Number"); - String complaintType = (String) details.get(index).get("Complaint Type"); - String complaintMode = (String) details.get(index).get("Complaint Mode"); - String department = (String) details.get(index).get("Department"); - String complaintGroup = (String) details.get(index).get("Complaint Group"); - String officerName = (String) details.get(index).get("Assign To"); - String officerMobileNumber = (String) details.get(index).get("Official Contact Number"); - String status1 = status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number,complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - // jdbcTemplate.update(insertQuery, qaqc_id, status1, - // complaintNumber1,complaintDate, complanitPersonName, - // complaintPersonMobileNum, complaintType, complaintMode, department, - // complaintGroup, officerName, officerMobileNumber, currentAgentId); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, - Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status); - ps.setString(3, complaintNumber1); - ps.setString(4, complaintDate); - ps.setString(5, complanitPersonName); - ps.setString(6, complaintPersonMobileNum); - ps.setString(7, complaintType); - ps.setString(8, complaintMode); - ps.setString(9, department); - ps.setString(10, complaintGroup); - ps.setString(11, officerName); - ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - // Retrieve the generated data_id - Number generatedDataId = keyHolder.getKey(); - if (generatedDataId != null) { - long dataId = generatedDataId.longValue(); - - // System.out.println("dataId if=="+dataId); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " - + "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status1, complaintNumber1, complaintDate, - complanitPersonName, complaintPersonMobileNum, complaintType, complaintMode, - department, complaintGroup, officerName, officerMobileNumber, - currentAgentId, dataId); - - } - - assignedCount++; - - String upsql2 = "UPDATE gcc_1913_qaqc.qaqc_followup_call_logs set isactive=0 where id=?"; - jdbcTemplate.update(upsql2, isactive_id); - - } - - } - - } else { - //System.out.println("else complaintNumber = " + complaintNumber1); - String complaintDate2 = (String) details.get(index).get("Complaint Opened Date"); - String complanitPersonName2 = (String) details.get(index).get("Complaint Person Name"); - String complaintPersonMobileNum2 = (String) details.get(index).get("Complaint Person Number"); - String complaintType2 = (String) details.get(index).get("Complaint Type"); - String complaintMode2 = (String) details.get(index).get("Complaint Mode"); - String department2 = (String) details.get(index).get("Department"); - String complaintGroup2 = (String) details.get(index).get("Complaint Group"); - String officerName2 = (String) details.get(index).get("Assign To"); - String officerMobileNumber2 = (String) details.get(index).get("Official Contact Number"); - String status2 = status.toUpperCase(); - - // Insert into the database - String insertQuery = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data (qaqc_id, call_category, complaint_number,complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - // jdbcTemplate.update(insertQuery, qaqc_id, status2, - // complaintNumber1,complaintDate2, complanitPersonName2, - // complaintPersonMobileNum2, complaintType2, complaintMode2, department2, - // complaintGroup2, officerName2, officerMobileNumber2, currentAgentId); - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertQuery, - Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, qaqc_id); - ps.setString(2, status2); - ps.setString(3, complaintNumber1); - ps.setString(4, complaintDate2); - ps.setString(5, complanitPersonName2); - ps.setString(6, complaintPersonMobileNum2); - ps.setString(7, complaintType2); - ps.setString(8, complaintMode2); - ps.setString(9, department2); - ps.setString(10, complaintGroup2); - ps.setString(11, officerName2); - ps.setString(12, officerMobileNumber2); - ps.setInt(13, currentAgentId); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - - if (generatedDataId != null) { - long dataId2 = generatedDataId.longValue(); - // System.out.println("dataId2 else=="+dataId2); - // Use the dataId in the next insert for qaqc_upload_data_history - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_upload_data_history " - + "(qaqc_id, call_category, complaint_number, complaint_date, complaint_person_name, complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, agent_id, data_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, qaqc_id, status2, complaintNumber1, complaintDate2, - complanitPersonName2, complaintPersonMobileNum2, complaintType2, complaintMode2, - department2, complaintGroup2, officerName2, officerMobileNumber2, currentAgentId, - dataId2); - } - - assignedCount++; - } - } - - countResult.put("assignedCount", assignedCount); - countResult.put("qaqc_id", qaqc_id); - countResult.put("agent_id", currentAgentId); - countDetails.add(countResult); - } - for (Map assgn : assignedIDList) { - - for (Map count : countDetails) { - - if (((int) assgn.get("agent_id")) == ((int) count.get("agent_id"))) { - int assignedid = (int) assgn.get("assigned_id"); - int agentid = (int) assgn.get("agent_id"); - int assignedCount = (int) count.get("assignedCount"); - String sql = "UPDATE agent_assigned SET data_count = ? WHERE assigned_id = ? and agent_id = ?"; - jdbcTemplate.update(sql, assignedCount, assignedid, agentid); - } - } - } - - return true; - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - private List> getFollowupData() { - - //String sqlQuery ="select complaint_number, remainder_date, call_status from qaqc_followup_call_logs"; - String sqlQuery = "select id, call_category,complaint_number, remainder_date, call_status from qaqc_followup_call_logs where isactive=1"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - -// @Transactional -// public int saveInAgentAssigned(int agent_id, int qaqc_id,int data_counts) { -// String insertSql = "INSERT INTO gcc_1913_qaqc.agent_assigned (agent_id, qaqc_id,data_count) VALUES (?, ?,?)"; -// int rowsInserted = jdbcTemplate.update(insertSql, agent_id, qaqc_id,data_counts); -// -// return rowsInserted; -// } - - @Transactional - public Map saveInAgentAssigned(int agent_id, int qaqc_id, int data_counts) { - String insertSql = "INSERT INTO gcc_1913_qaqc.agent_assigned (agent_id, qaqc_id, data_count) VALUES (?, ?, ?)"; - KeyHolder keyHolder = new GeneratedKeyHolder(); - - int rowsInserted = jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, agent_id); - ps.setInt(2, qaqc_id); - ps.setInt(3, data_counts); - return ps; - }, keyHolder); - - if (rowsInserted > 0 && keyHolder.getKey() != null) { - Map result = new HashMap<>(); - result.put("assigned_id", keyHolder.getKey().intValue()); - result.put("agent_id", agent_id); - return result; - } else { - throw new RuntimeException("Failed to insert data into agent_assigned table."); - } - } - @Transactional - public int savetaskid(String taskid,String fromdate,String todate,String description,String status, int closedCount,String group, String type, String mode, String zone,String region) { - - // Ensure default values for nullable parameters - if (group == null || group.isEmpty()) { - group = "ALL"; - } - if (type == null || type.isEmpty()) { - type = "ALL"; - } - if (mode == null || mode.isEmpty()) { - mode = "ALL"; - } - if (zone == null || zone.isEmpty()) { - zone = "ALL"; - } - if (region == null || region.isEmpty()) { - region = "ALL"; - } - - String sql = "INSERT INTO gcc_1913_qaqc.qaqc_request (taskid,fromdate,todate,description,call_category,total_data,complaint_group,complaint_type,complaint_mode,complaint_zone,complaint_region) " + - "VALUES (?,?,?,?,?,?,?,?,?,?,?)"; - int rowsInserted = jdbcTemplate.update(sql,taskid,fromdate,todate,description,status,closedCount,group,type,mode,zone,region); - return rowsInserted; - } - @Transactional - public List> getLastTask() - { - String sqlQuery ="SELECT qaqc_id\r\n" - + "FROM gcc_1913_qaqc.qaqc_request\r\n" - + "ORDER BY qaqc_id DESC\r\n" - + "LIMIT 1"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - public int deleteUploadDataTable() { - String sql = "DELETE FROM gcc_1913_qaqc.qaqc_upload_data WHERE 1=1"; - int rowsAffected= jdbcTemplate.update(sql); - return rowsAffected; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentsService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentsService.java deleted file mode 100644 index f8da762e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentsService.java +++ /dev/null @@ -1,686 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class QaqcAgentsService { - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - @Transactional - public List> getAgentsAllTasksCounts(int agent_id) { - String SqlQuery = "SELECT \r\n" - + " cr.taskid,\r\n" - + " cr.call_category,\r\n" - + " cr.description,\r\n" - + " aa.qaqc_id,\r\n" - + " aa.agent_id,\r\n" - + " aa.created_date,\r\n" - + " (SELECT COUNT(data_id) \r\n" - + " FROM qaqc_upload_data up \r\n" - + " WHERE up.agent_id = aa.agent_id \r\n" - + " AND up.qaqc_id = cr.qaqc_id\r\n" - + " ) AS calls_assigned,\r\n" - + " (SELECT COUNT(CASE WHEN up.call_status IS NULL THEN 1 END) \r\n" - + " FROM qaqc_upload_data up \r\n" - + " WHERE up.agent_id = aa.agent_id \r\n" - + " AND up.qaqc_id = cr.qaqc_id\r\n" - + " ) AS pending_count,\r\n" - + " (SELECT COUNT(CASE WHEN up.call_status IS NOT NULL THEN 1 END) \r\n" - + " FROM qaqc_upload_data up \r\n" - + " WHERE up.agent_id = aa.agent_id \r\n" - + " AND up.qaqc_id = cr.qaqc_id\r\n" - + " ) AS complete_count,\r\n" - + " (SELECT COUNT(CASE WHEN up.call_status ='CALL_BACK_LATER' OR up.field_9 = 'UNATTENDED' THEN 1 END) \r\n" - + " FROM qaqc_upload_data up \r\n" - + " WHERE up.agent_id = aa.agent_id \r\n" - + " AND up.qaqc_id = cr.qaqc_id\r\n" - + " ) AS followup_count\r\n" - + " \r\n" - + "FROM \r\n" - + " agent_assigned aa\r\n" - + "JOIN \r\n" - + " agents_list al ON aa.agent_id = al.agent_id\r\n" - + "JOIN \r\n" - + " qaqc_request cr ON cr.qaqc_id = aa.qaqc_id\r\n" - + "WHERE \r\n" - + " aa.agent_id = ? \r\n" - + " AND aa.isactive = '1'"; - - return jdbcTemplate.queryForList(SqlQuery,agent_id); - } - - public List> getdataforagents(int agent_id,int qaqc_id) { - String sqlQuery = "select *\r\n" - + "from qaqc_upload_data\r\n" - + "where agent_id=? and qaqc_id=?"; - - return jdbcTemplate.queryForList(sqlQuery,agent_id,qaqc_id); - } - - @Transactional - public void savecallstatus(String call_status, String remarks,String complaintNumber) - { - - - String SqlQuery = "UPDATE qaqc_upload_data SET call_status = ?,remarks=?, updated_date = NOW() WHERE (complaint_number = ? )"; - - jdbcTemplate.update(SqlQuery,call_status, remarks,complaintNumber); - } - - @Transactional - public void savecallstatusinlogs(String call_status, String remarks,String complaintNumber) { - - // Step 1: Fetch details from the source table using the complaintNumber - String selectQuery = "SELECT * FROM qaqc_upload_data WHERE complaint_number = ?"; - Map details = jdbcTemplate.queryForMap(selectQuery, complaintNumber); - - // Extract the required fields from the result (modify based on your table structure) - String detailField1 = (String) details.get("qaqc_id"); - String detailField2 = (String) details.get("agent_id"); - String detailField3 = (String) details.get("complaint_number"); - String detailField4 = (String) details.get("complaint_person_name"); - String detailField5 = (String) details.get("complaint_mobilenumber"); - String detailField6 = (String) details.get("complaint_type"); - String detailField7 = (String) details.get("complaint_mode"); - String detailField8 = (String) details.get("department"); - String detailField9 = (String) details.get("complaint_group"); - String detailField10 = (String) details.get("official_name"); - String detailField11 = (String) details.get("official_mobilenum"); - - // Step 2: Insert the fetched details along with call_status and remarks into qaqc_call_logs - String insertQuery = "INSERT INTO qaqc_call_logs (qaqc_id, agent_id, complaint_number, complaint_person_name, complaint_mobilenumber,complaint_type,complaint_mode,department,complaint_group,official_name,official_mobilenum) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; - jdbcTemplate.update(insertQuery,detailField1, detailField2,detailField3,detailField4,detailField5,detailField6,detailField7,detailField8,detailField9,detailField10,detailField11,call_status,remarks); - - } - - - public List> getPreviousDayDashboardCounts() - { - String sqlQuery = "SELECT \r\n" - + " COUNT(DISTINCT assigned_stats.agent_id) AS TotalAgents, \r\n" - + " SUM(COALESCE(assigned_stats.Assigned, 0)) AS TotalAssigned, \r\n" - + " SUM(COALESCE(completed_stats.TotalCompleted, 0)) AS TotalCompleted, \r\n" - + " SUM(COALESCE(assigned_stats.Assigned, 0) - COALESCE(completed_stats.TotalCompleted, 0)) AS TotalPending \r\n" - + "FROM \r\n" - + " (SELECT al.agent_id AS agent_id, SUM(aa.data_count) AS Assigned \r\n" - + " FROM agent_assigned aa \r\n" - + " JOIN agents_list al ON aa.agent_id = al.agent_id \r\n" - + " WHERE DATE(aa.created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" - + " GROUP BY al.agent_id) AS assigned_stats \r\n" - + "LEFT JOIN \r\n" - + " (SELECT agent_id, COUNT(DISTINCT (complaint_number)) AS TotalCompleted \r\n" - + " FROM qaqc_call_logs \r\n" - + " WHERE DATE(created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" - + " GROUP BY agent_id) AS completed_stats \r\n" - + "ON assigned_stats.agent_id = completed_stats.agent_id;"; - - - return jdbcTemplate.queryForList(sqlQuery); - } - -// public List> getAgentPreviousDayCount() -// { -// String sqlQuery = "SELECT DISTINCT \r\n" -// + " assigned_stats.agent_id, \r\n" -// + " assigned_stats.agent_name as agent_name, -- Use the alias assigned_stats here instead of aa\r\n" -// + " COALESCE(assigned_stats.Assigned, 0) AS Assigned, \r\n" -// + " COALESCE(completed_stats.TotalCompleted, 0) AS TotalCompleted, \r\n" -// + " COALESCE(assigned_stats.Assigned, 0) - COALESCE(completed_stats.TotalCompleted, 0) AS Pending, \r\n" -// + " CASE \r\n" -// + " WHEN COALESCE(assigned_stats.Assigned, 0) = 0 THEN 0 \r\n" -// + " ELSE ROUND(COALESCE(completed_stats.TotalCompleted, 0) * 100.0 / COALESCE(assigned_stats.Assigned, 1)) \r\n" -// + " END AS CompletionPercentage, \r\n" -// + " COALESCE(call_stats.Completed_count, 0) AS Completed_count, \r\n" -// + " COALESCE(call_stats.Reopened_count, 0) AS Reopened_count, \r\n" -// + " COALESCE(call_stats.Followup_count, 0) AS Followup_count, \r\n" -// + " COALESCE(call_stats.Other_count, 0) AS Other_count \r\n" -// + "FROM \r\n" -// + " (SELECT al.agent_id AS agent_id, al.agent_name AS agent_name, SUM(aa.data_count) AS Assigned \r\n" -// + " FROM agent_assigned aa \r\n" -// + " JOIN agents_list al ON aa.agent_id = al.agent_id \r\n" -// + " WHERE DATE(aa.created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" -// + " GROUP BY al.agent_id,al.agent_name) AS assigned_stats -- The alias 'assigned_stats' is used here\r\n" -// + "LEFT JOIN \r\n" -// + " (SELECT agent_id, COUNT(qaqc_id) AS TotalCompleted \r\n" -// + " FROM qaqc_call_logs \r\n" -// + " WHERE DATE(created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" -// + " GROUP BY agent_id) AS completed_stats ON assigned_stats.agent_id = completed_stats.agent_id \r\n" -// + "LEFT JOIN \r\n" -// + " (SELECT agent_id, \r\n" -// + " SUM(CASE WHEN call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 ELSE 0 END) AS Completed_count, \r\n" -// + " SUM(CASE WHEN call_status = 'REOPEN' THEN 1 ELSE 0 END) AS Reopened_count, \r\n" -// + " SUM(CASE WHEN call_status = 'FOLLOWUP' THEN 1 ELSE 0 END) AS Followup_count, \r\n" -// + " SUM(CASE WHEN call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 ELSE 0 END) AS Other_count \r\n" -// + " FROM qaqc_call_logs \r\n" -// + " WHERE DATE(created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" -// + " GROUP BY agent_id) AS call_stats ON assigned_stats.agent_id = call_stats.agent_id;\r\n"; -// -// return jdbcTemplate.queryForList(sqlQuery); -// } - - - public List> getAgentPreviousDayCount() - { - String sqlQuery = "SELECT DISTINCT \r\n" - + " assigned_stats.agent_id, \r\n" - + " assigned_stats.agent_name as agent_name, -- Use the alias assigned_stats here instead of aa\r\n" - + " COALESCE(assigned_stats.Assigned, 0) AS Assigned, \r\n" - + " COALESCE(completed_stats.TotalCompleted, 0) AS TotalCompleted, \r\n" - + " COALESCE(assigned_stats.Assigned, 0) - COALESCE(completed_stats.TotalCompleted, 0) AS Pending, \r\n" - + " CASE \r\n" - + " WHEN COALESCE(assigned_stats.Assigned, 0) = 0 THEN 0 \r\n" - + " ELSE ROUND(COALESCE(completed_stats.TotalCompleted, 0) * 100.0 / COALESCE(assigned_stats.Assigned, 1)) \r\n" - + " END AS CompletionPercentage, \r\n" - + " COALESCE(call_stats.Completed_count, 0) AS Completed_count, \r\n" - + " COALESCE(call_stats.Reopened_count, 0) AS Reopened_count, \r\n" - + " COALESCE(call_stats.Followup_count, 0) AS Followup_count, \r\n" - + " COALESCE(call_stats.Other_count, 0) AS Other_count \r\n" - + "FROM \r\n" - + " (SELECT al.agent_id AS agent_id, al.agent_name AS agent_name, SUM(aa.data_count) AS Assigned \r\n" - + " FROM agent_assigned aa \r\n" - + " JOIN agents_list al ON aa.agent_id = al.agent_id \r\n" - + " WHERE DATE(aa.created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" - + " GROUP BY al.agent_id,al.agent_name) AS assigned_stats -- The alias 'assigned_stats' is used here\r\n" - + "LEFT JOIN \r\n" - + " (SELECT agent_id, count(DISTINCT (complaint_number)) AS TotalCompleted \r\n" - + " FROM qaqc_call_logs \r\n" - + " WHERE DATE(created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" - + " GROUP BY agent_id) AS completed_stats ON assigned_stats.agent_id = completed_stats.agent_id \r\n" - + "LEFT JOIN \r\n" - + " (SELECT agent_id, \r\n" - + " SUM(CASE WHEN call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 ELSE 0 END) AS Completed_count, \r\n" - + " SUM(CASE WHEN call_status = 'REOPEN' THEN 1 ELSE 0 END) AS Reopened_count, \r\n" - + " SUM(CASE WHEN call_status = 'FOLLOWUP' THEN 1 ELSE 0 END) AS Followup_count, \r\n" - + " SUM(CASE WHEN call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 ELSE 0 END) AS Other_count \r\n" - + " FROM qaqc_call_logs \r\n" - + " WHERE DATE(created_date) = DATE(SUBDATE(CURDATE(), 1)) \r\n" - + " GROUP BY agent_id) AS call_stats ON assigned_stats.agent_id = call_stats.agent_id \r\n" - + " ORDER BY agent_name \r\n;"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - - public List> getAgentDashboard(int userId, String startDate, String endDate) { - String sql = "SELECT " + - " COALESCE(SUM(aa.data_count), 0) AS Total_Calls_assigned, " + - " COALESCE(SUM(CASE WHEN qr.call_category = 'closed' THEN aa.data_count ELSE 0 END), 0) AS Closed_Call_count, " + - " COALESCE(SUM(CASE WHEN qr.call_category IN ('inprogress', 'redressed', 'reopened','processing') THEN aa.data_count ELSE 0 END), 0) AS Inprogress_Call_count, " + - " COALESCE(SUM(CASE WHEN qr.call_category = 'officialfollowup' THEN aa.data_count ELSE 0 END), 0) AS Followup_Call_count, " + - " COALESCE(SUM(CASE WHEN qr.call_category = 'publicfollowup' THEN aa.data_count ELSE 0 END), 0) AS PublicFollowup_Call_count " + - "FROM agent_assigned aa " + - "LEFT JOIN qaqc_request qr ON aa.qaqc_id = qr.qaqc_id " + - "WHERE aa.agent_id = ? " + - "AND DATE(qr.created_date) BETWEEN ? AND ?"; - - return jdbcTemplate.queryForList(sql, userId, startDate, endDate); - } - - - public List> getAgentPerformanceData(int agentId, String startDate, String endDate) { - // String sql = "SELECT \n" - // + " COALESCE(total_data_count, 0) AS total_data_count,\n" // Ensure total_data_count is 0 if null - // + " COALESCE(completed_count, 0) AS completed_count,\n" // Ensure completed_count is 0 if null - // + " COALESCE((total_data_count - completed_count), 0) AS pending_count,\n" // Ensure pending_count is 0 - // + " CASE \n" - // + " WHEN COALESCE(total_data_count, 0) > 0 THEN ROUND((COALESCE(completed_count, 0) / total_data_count) * 100, 1)\n" - // + " ELSE 0\n" - // + " END AS completed_percentage\n" - // + "FROM \n" - // + " (\n" - // + " SELECT \n" - // + " (SELECT COALESCE(SUM(aa.data_count), 0) \n" - // + " FROM agent_assigned aa \n" - // + " WHERE aa.agent_id = ? AND DATE(aa.created_date) BETWEEN ? AND ?) AS total_data_count,\n" - // + " \n" - // + " (SELECT COALESCE(COUNT(*), 0) \n" - // + " FROM qaqc_call_logs cl \n" - // + " WHERE cl.agent_id = ?\n" - // + " AND DATE(cl.created_date) BETWEEN ? AND ? \n" - // + " AND cl.call_status IS NOT NULL) AS completed_count\n" - // + " ) AS combined"; - - // return jdbcTemplate.queryForList(sql, agentId, startDate, endDate, agentId, startDate, endDate); - - String sql="SELECT " - + " total_data_count," - + " completed_count," - + " (total_data_count - completed_count) AS pending_count," - + " CASE " - + " WHEN total_data_count > 0 " - + " THEN ROUND((completed_count / total_data_count) * 100, 1)" - + " ELSE 0" - + " END AS completed_percentage" - + " FROM (" - + " SELECT " - + " COUNT(*) AS total_data_count," - + " COUNT(call_status) AS completed_count" - + " FROM qaqc_upload_data_history" - + " WHERE created_date >= ? " - + " AND created_date < DATE_ADD( ? , INTERVAL 1 DAY)" - + " AND agent_id = ? " - + ") t"; - - return jdbcTemplate.queryForList(sql, startDate, endDate, agentId); - } - - - - - public List> getAgentTaskDetails(int userId, String startDate, String endDate) { - String sql = "WITH LatestCallLogs AS ( " + - " SELECT " + - " cl.qaqc_id, " + - " cl.agent_id, " + - " cl.complaint_number, " + - " cl.call_status, " + - " cl.created_date, " + - " ROW_NUMBER() OVER (PARTITION BY cl.qaqc_id, cl.agent_id, cl.complaint_number ORDER BY cl.created_date DESC) AS row_num " + - " FROM " + - " qaqc_call_logs cl " + - ") " + - "SELECT DISTINCT " + - " qr.taskid AS taskid, " + - " qr.call_category AS call_category, " + - " DATE(aa.created_date) AS cdate, " + - " aa.data_count AS assigned, " + - " COUNT(lcl.agent_id) AS callstaken, " + - " (aa.data_count - COUNT(lcl.agent_id)) AS pending, " + - " ROUND((CASE WHEN aa.data_count > 0 THEN (COUNT(lcl.agent_id) / aa.data_count) * 100 ELSE 0 END), 2) AS percentage, " + - " COUNT(CASE WHEN lcl.call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 END) AS Completed, " + - " COUNT(CASE WHEN lcl.call_status = 'REOPEN' THEN 1 END) AS Reopened, " + - " COUNT(CASE WHEN lcl.call_status = 'FOLLOWUP' THEN 1 END) AS Followup, " + - " COUNT(CASE WHEN lcl.call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 END) AS Others " + - "FROM " + - " qaqc_request qr " + - "JOIN " + - " agent_assigned aa ON aa.qaqc_id = qr.qaqc_id " + - "JOIN " + - " agents_list al ON al.agent_id = aa.agent_id " + - "LEFT JOIN " + - " LatestCallLogs lcl ON qr.qaqc_id = lcl.qaqc_id AND al.agent_id = lcl.agent_id AND lcl.row_num = 1 " + - "WHERE " + - " al.agent_id = ? AND aa.data_count != 0 " + - " AND DATE(aa.created_date) BETWEEN ? AND ? " + - "GROUP BY " + - " taskid, cdate, assigned, call_category"; - - return jdbcTemplate.queryForList(sql, userId, startDate, endDate); - } - - public List> getAgentPerformanceCount(String startDate, String endDate) { - String sql = "SELECT " + - "t2.total_calls, " + - "t3.completed_calls, " + - "t2.total_calls - t3.completed_calls AS pending_calls, " + - "t4.no_of_agents " + - "FROM " + - "( " + - " SELECT " + - " SUM(aa.data_count) AS total_calls " + - " FROM " + - " agent_assigned aa " + - " INNER JOIN " + - " qaqc_request qr " + - " ON " + - " aa.qaqc_id = qr.qaqc_id " + - " WHERE " + - " (? IS NULL OR date(qr.created_date) BETWEEN ? AND ?) " + - ") AS t2, " + - "( " + - " SELECT " + - " SUM(qr.total_data) AS total_data, " + - " COUNT(CASE WHEN qcl.call_status IS NOT NULL THEN qcl.qaqc_id END) AS completed_calls" + - " FROM " + - " qaqc_request qr " + - " LEFT JOIN " + - " qaqc_upload_data_history qcl " + - " ON " + - " qr.qaqc_id = qcl.qaqc_id " + - " WHERE " + - " (? IS NULL OR date(qr.created_date) BETWEEN ? AND ?) " + - ") AS t3, " + - "( " + - " SELECT " + - " COUNT(DISTINCT aa.agent_id) AS no_of_agents " + - " FROM " + - " agent_assigned aa " + - " WHERE " + - " (? IS NULL OR date(aa.created_date) BETWEEN ? AND ?) " + - ") AS t4"; - - // Prepare the parameters for the query - Object[] params = new Object[] { - startDate, startDate, endDate, // For t2 - startDate, startDate, endDate, // For t3 - startDate, startDate, endDate // For t4 - }; - - // Execute the query and return the results as a List of Maps - return jdbcTemplate.queryForList(sql, params); - } - - public List> getAgentPerformanceList(String startDate, String endDate) { - // Base query with subqueries for Assigned, Completed, and Pending - StringBuilder query = new StringBuilder( - "SELECT DISTINCT " + - " assigned_stats.agent_id, " + - " assigned_stats.agent_name, " + - " COALESCE(assigned_stats.Assigned, 0) AS Assigned, " + - " COALESCE(completed_stats.TotalCompleted, 0) AS TotalCompleted, " + - " COALESCE(assigned_stats.Assigned, 0) - COALESCE(completed_stats.TotalCompleted, 0) AS Pending, " + - " CASE WHEN COALESCE(assigned_stats.Assigned, 0) = 0 THEN 0 ELSE " + - " ROUND(COALESCE(completed_stats.TotalCompleted, 0) * 100.0 / COALESCE(assigned_stats.Assigned, 1), 2) " + - " END AS CompletionPercentage, " + - " COALESCE(call_stats.Completed_count, 0) AS Completed_count, " + - " COALESCE(call_stats.Reopened_count, 0) AS Reopened_count, " + - " COALESCE(call_stats.Followup_count, 0) AS Followup_count, " + - " COALESCE(call_stats.Other_count, 0) AS Other_count " + - "FROM " + - " (SELECT al.agent_id as agent_id, al.agent_name as agent_name,SUM(aa.data_count) AS Assigned " + - " FROM agent_assigned aa JOIN agents_list al ON aa.agent_id=al.agent_id " + - " WHERE (? IS NULL OR DATE(aa.created_date) >= STR_TO_DATE(?, '%Y-%m-%d')) " + // Conditional date filtering - " AND (? IS NULL OR DATE(aa.created_date) <= STR_TO_DATE(?, '%Y-%m-%d')) " + - " GROUP BY al.agent_id,al.agent_name) AS assigned_stats " + // The alias 'assigned_stats' is used here - "LEFT JOIN " + - " (SELECT agent_id, COUNT(call_status) AS TotalCompleted " + - " FROM qaqc_upload_data_history " + - " WHERE (? IS NULL OR DATE(created_date) >= STR_TO_DATE(?, '%Y-%m-%d')) " + // Conditional date filtering - " AND (? IS NULL OR DATE(created_date) <= STR_TO_DATE(?, '%Y-%m-%d')) " + - " GROUP BY agent_id) AS completed_stats ON assigned_stats.agent_id = completed_stats.agent_id " + - "LEFT JOIN " + - " (SELECT agent_id, " + - " SUM(CASE WHEN call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 ELSE 0 END) AS Completed_count, " + - " SUM(CASE WHEN call_status = 'REOPEN' THEN 1 ELSE 0 END) AS Reopened_count, " + - " SUM(CASE WHEN call_status = 'FOLLOWUP' THEN 1 ELSE 0 END) AS Followup_count, " + - " SUM(CASE WHEN call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 ELSE 0 END) AS Other_count " + - " FROM qaqc_upload_data_history " + - " WHERE (? IS NULL OR DATE(created_date) >= STR_TO_DATE(?, '%Y-%m-%d')) " + // Conditional date filtering - " AND (? IS NULL OR DATE(created_date) <= STR_TO_DATE(?, '%Y-%m-%d')) " + - " GROUP BY agent_id) AS call_stats ON assigned_stats.agent_id = call_stats.agent_id" - ); - - // Execute query with date range parameters - return jdbcTemplate.queryForList( - query.toString(), - startDate, startDate, endDate, endDate, // Parameters for assigned_stats - startDate, startDate, endDate, endDate, // Parameters for completed_stats - startDate, startDate, endDate, endDate // Parameters for call_stats - ); - } - - - - - public List> getAgentTaskwiseData(String agentId,String startDate, String endDate) { - - String query="WITH LatestCallLogs AS (\r\n" - + " SELECT \r\n" - + " cl.qaqc_id,\r\n" - + " cl.agent_id,\r\n" - + " cl.complaint_number,\r\n" - + " cl.call_status,\r\n" - + " cl.created_date,\r\n" - + " ROW_NUMBER() OVER (PARTITION BY cl.qaqc_id, cl.agent_id, cl.complaint_number ORDER BY cl.created_date DESC) AS row_num\r\n" - + " FROM \r\n" - + " qaqc_call_logs cl\r\n" - + ")\r\n" - + "SELECT DISTINCT \r\n" - + " qr.taskid as taskid,\r\n" - + " date(aa.created_date) as cdate,\r\n" - + " aa.data_count AS assigned,\r\n" - + " COUNT(lcl.agent_id) AS callstaken,\r\n" - + " (aa.data_count - COUNT(lcl.agent_id)) AS pending,\r\n" - + " ROUND((COUNT(lcl.agent_id) / aa.data_count) * 100, 2) AS percentage,\r\n" - + " COUNT(CASE WHEN lcl.call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 END) AS Completed,\r\n" - + " COUNT(CASE WHEN lcl.call_status = 'REOPEN' THEN 1 END) AS Reopened,\r\n" - + " COUNT(CASE WHEN lcl.call_status = 'FOLLOWUP' THEN 1 END) AS Followup,\r\n" - + " COUNT(CASE WHEN lcl.call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 END) AS Others\r\n" - + "FROM \r\n" - + " qaqc_request qr\r\n" - + "JOIN \r\n" - + " agent_assigned aa ON aa.qaqc_id = qr.qaqc_id\r\n" - + "JOIN \r\n" - + " agents_list al ON al.agent_id = aa.agent_id\r\n" - + "LEFT JOIN \r\n" - + " LatestCallLogs lcl ON qr.qaqc_id = lcl.qaqc_id AND al.agent_id = lcl.agent_id AND lcl.row_num = 1\r\n" - + "WHERE \r\n" - + " al.agent_id = ? AND DATE(qr.created_date) >= ? AND DATE(qr.created_date) <= ? \r\n" - + "GROUP BY \r\n" - + " taskid, cdate, assigned"; - - - return jdbcTemplate.queryForList(query, agentId,startDate,endDate); - - } - - - public List> getAttendedComplaintStatus( - String startDate, String endDate, String complaintNumber, String complaintMobileNumber) { - - // Base query with JOIN to include agent_name - StringBuilder query = new StringBuilder( - "SELECT qcl.*,date(qcl.created_date) as updated_date, al.agent_name " + - "FROM qaqc_call_logs qcl " + - "LEFT JOIN agents_list al ON qcl.agent_id = al.agent_id " + - "WHERE 1=1 "); - - // List to store query parameters - List params = new ArrayList<>(); - - // Add date range condition if provided - if (startDate != null && !startDate.isEmpty()) { - query.append("AND DATE(qcl.created_date) >= ? "); - params.add(startDate); - } - if (endDate != null && !endDate.isEmpty()) { - query.append("AND DATE(qcl.created_date) <= ? "); - params.add(endDate); - } - - // Add complaint number condition if provided - if (complaintNumber != null && !complaintNumber.isEmpty()) { - query.append("AND qcl.complaint_number = ? "); - params.add(complaintNumber); - } - - // Add complaint mobile number condition if provided - if (complaintMobileNumber != null && !complaintMobileNumber.isEmpty()) { - query.append("AND qcl.complaint_mobilenumber = ? "); - params.add(complaintMobileNumber); - } - - // Add ORDER BY clause - query.append("ORDER BY qcl.created_date DESC "); - - // Add LIMIT clause only if complaintNumber is provided - if (complaintNumber != null && !complaintNumber.isEmpty()) { - query.append("LIMIT 1 "); - } - - // Execute the query with dynamic parameters - return jdbcTemplate.queryForList(query.toString(), params.toArray()); - } - - -// public List> getAttendedComplainthistory( -// String startDate, String endDate, String complaintNumber, String complaintMobileNumber) { -// -// // Base query with JOIN to include agent_name -// StringBuilder query = new StringBuilder( -// "SELECT qcl.*, al.agent_name " + -// "FROM qaqc_call_logs qcl " + -// "LEFT JOIN agents_list al ON qcl.agent_id = al.agent_id " + -// "WHERE 1=1 "); -// -// // List to store query parameters -// List params = new ArrayList<>(); -// -// // Add date range condition if provided -// if (startDate != null && !startDate.isEmpty()) { -// query.append("AND DATE(qcl.created_date) >= ? "); -// params.add(startDate); -// } -// if (endDate != null && !endDate.isEmpty()) { -// query.append("AND DATE(qcl.created_date) <= ? "); -// params.add(endDate); -// } -// -// // Add complaint number condition if provided -// if (complaintNumber != null && !complaintNumber.isEmpty()) { -// query.append("AND qcl.complaint_number = ? "); -// params.add(complaintNumber); -// } -// -// // Add complaint mobile number condition if provided -// if (complaintMobileNumber != null && !complaintMobileNumber.isEmpty()) { -// query.append("AND qcl.complaint_mobilenumber = ? "); -// params.add(complaintMobileNumber); -// } -// -// // Group by qcl.id and agent_name to avoid SQL error -// query.append("GROUP BY qcl.id, al.agent_name "); -// -// // Add ordering clause -// query.append("ORDER BY qcl.created_date DESC"); -// -// // Execute the query with dynamic parameters -// return jdbcTemplate.queryForList(query.toString(), params.toArray()); -// } - - public List> getAttendedComplainthistory( - String startDate, - String endDate, - String complaintNumber, - String complaintMobileNumber) { - - StringBuilder query = new StringBuilder( - - "SELECT * FROM ( " + - - // ================= QAQC CALL LOGS ================= - "SELECT " + - "qcl.id, " + - "qcl.qaqc_id, " + - "qcl.call_category, " + - "qcl.agent_id, " + - "qcl.complaint_number, " + - "qcl.complaint_date, " + - "qcl.complaint_person_name, " + - "qcl.complaint_mobilenumber, " + - "qcl.complaint_type, " + - "qcl.complaint_mode, " + - "qcl.department, " + - "qcl.complaint_group, " + - "qcl.official_name, " + - "qcl.official_mobilenum, " + - "qcl.call_status, " + - "qcl.remainder_date, " + - "qcl.remarks, " + - "qcl.created_date, " + - "qcl.is_processed, " + - "qcl.updated_agent, " + - "al.agent_name, " + - "'QAQC' AS source_table " + - - "FROM qaqc_call_logs qcl " + - "LEFT JOIN agents_list al ON qcl.agent_id = al.agent_id " + - - "UNION ALL " + - - // ================= SOCIAL MEDIA ================= - "SELECT " + - "smc.id, " + - "NULL AS qaqc_id, " + - "NULL AS call_category, " + - "smc.updated_by AS agent_id, " + - "smc.complaint_number, " + - "smc.complaint_date, " + - "smc.complaint_person_name, " + - "smc.complaint_mobilenumber, " + - "smc.complaint_type, " + - "smc.complaint_mode, " + - "smc.department, " + - "NULL AS complaint_group, " + - "smc.official_name, " + - "smc.official_mobilenum, " + - "smc.call_status, " + - "smc.remainder_date AS remainder_date, " + - "smc.remarks, " + - "smc.created_date, " + - "smc.is_processed AS is_processed, " + - "smc.updated_by AS updated_agent, " + - "al.agent_name, " + - "'SOCIAL_MEDIA' AS source_table " + - - "FROM social_media_completed smc " + - "LEFT JOIN agents_list al ON smc.updated_by = al.agent_id " + - - ") x WHERE 1=1 " - ); - - List params = new ArrayList<>(); - - // ================= DATE FILTER ================= - if (startDate != null && !startDate.isEmpty()) { - query.append("AND DATE(x.created_date) >= ? "); - params.add(startDate); - } - - if (endDate != null && !endDate.isEmpty()) { - query.append("AND DATE(x.created_date) <= ? "); - params.add(endDate); - } - - // ================= COMPLAINT NUMBER ================= - if (complaintNumber != null && !complaintNumber.isEmpty()) { - query.append("AND x.complaint_number = ? "); - params.add(complaintNumber); - } - - // ================= MOBILE NUMBER ================= - if (complaintMobileNumber != null && !complaintMobileNumber.isEmpty()) { - query.append("AND x.complaint_mobilenumber = ? "); - params.add(complaintMobileNumber); - } - - // ================= ORDER ================= - query.append("ORDER BY x.created_date DESC"); - - return jdbcTemplate.queryForList(query.toString(), params.toArray()); - } - - public List> getAgentTaskwiseAssign(String agentId) { - String query="SELECT * FROM qaqc_upload_data_history where agent_id=? "; - return jdbcTemplate.queryForList(query, agentId); - } - - public List> getAgentName(int userId) { - String query="SELECT agent_name \r\n" - + "FROM agents_list\r\n" - + "where agent_id=?"; - return jdbcTemplate.queryForList(query, userId); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java deleted file mode 100644 index 19aeef61..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java +++ /dev/null @@ -1,391 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.time.LocalDateTime; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -@Service -@Transactional -public class QaqcCallsService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> getClosedComplaints(int agent_id) { - String query = "SELECT data_id, complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, complaint_type,official_name, official_mobilenum,complaint_mode, department,call_category " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE call_category = 'CLOSED' " + - " AND is_processed = FALSE " + // Fetch only unprocessed entries - " AND agent_id = ?"; - return jdbcTemplate.queryForList(query, agent_id); - } - - - public List> getCallCategories() - { - String query = "SELECT call_status " + - "FROM gcc_1913_qaqc.call_status WHERE call_category_id ='1' and isactive='1'"; - return jdbcTemplate.queryForList(query); - } - - - @Transactional - public int uploadComplaintDetailsInLogs(Map logDetails, String action, String complaintNumber, String remainderDate) { - //System.out.println("Complaint Details: " + logDetails); - // Extract other field values from complaintDetails - int qaqcid = (int) logDetails.get("qaqc_id"); - String ccategory = logDetails.get("call_category").toString(); - String complaintDate = logDetails.get("complaint_date").toString(); - String personName = logDetails.get("complaint_person_name").toString(); - String personMobNo = logDetails.get("complaint_mobilenumber").toString(); - String cType = logDetails.get("complaint_type").toString(); - String cMode = logDetails.get("complaint_mode").toString(); - String department = logDetails.get("department").toString(); - String cGroup = logDetails.get("complaint_group").toString(); - String officialName = logDetails.get("official_name").toString(); - String officialMobileNum = logDetails.get("official_mobilenum").toString(); - String callStatus = logDetails.get("call_status").toString(); - String remarks = logDetails.get("remarks").toString(); - int agentId = (int) logDetails.get("agent_id"); - int updated_agent=(int)logDetails.get("updated_agent"); - boolean isProcessed = (boolean)logDetails.get("is_processed"); - LocalDateTime currentDate = LocalDateTime.now(); - - // Determine which table to insert into based on the action - if (action.equals("FOLLOWUP")) { - String query = "INSERT INTO gcc_1913_qaqc.qaqc_followup_call_logs (qaqc_id, call_category, agent_id, complaint_number,complaint_date, complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, remainder_date,official_mobilenum, call_status, remarks,created_date,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?)"; - - int rowsAffected = jdbcTemplate.update(query, qaqcid, ccategory, agentId, complaintNumber, complaintDate,personName, - personMobNo, cType, cMode, department, cGroup, officialName,remainderDate, officialMobileNum,callStatus, - remarks,currentDate,updated_agent); - //System.out.println("Rows Inserted in qaqc_followup_call_logs : " + rowsAffected); - - String query1 = "INSERT INTO gcc_1913_qaqc.qaqc_call_logs (qaqc_id, call_category, agent_id, complaint_number,complaint_date, complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name,remainder_date, official_mobilenum, call_status, remarks, is_processed,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?)"; - - int rowsAffected1 = jdbcTemplate.update(query1, qaqcid, ccategory, agentId, complaintNumber, complaintDate,personName, - personMobNo, cType, cMode, department, cGroup, officialName,remainderDate, officialMobileNum, callStatus, remarks, - isProcessed,updated_agent); - //System.out.println("Rows Inserted in qaqc_call_logs : " + rowsAffected1); - - - return rowsAffected + rowsAffected1; - - } else { - String query = "INSERT INTO gcc_1913_qaqc.qaqc_call_logs (qaqc_id, call_category, agent_id, complaint_number, complaint_date,complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, call_status, remarks, is_processed,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - int rowsAffected = jdbcTemplate.update(query, qaqcid, ccategory, agentId, complaintNumber,complaintDate, personName, - personMobNo, cType, cMode, department, cGroup, officialName, officialMobileNum, callStatus, remarks, - isProcessed,updated_agent); - - //System.out.println("Rows Inserted in qaqc_call_logs: " + rowsAffected); - - return rowsAffected; - } - } - - public void updateComplaintDetails(String complaintNumber,int dataId, String action, String remarks,int updated_agent) - { - String query = "UPDATE gcc_1913_qaqc.qaqc_upload_data " + - "SET call_status = ?, " + " remarks = ?,updated_agent=?, " + - " updated_date = CURRENT_TIMESTAMP, " + " is_processed = TRUE " + - "WHERE data_id = ? " +" AND complaint_number = ? " +" AND call_category = 'CLOSED'"; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks,updated_agent, dataId,complaintNumber); - - //System.out.println("Rows Updated in upload data: " + rowsUpdated); - } - - public Map getComplaintDetails(int dataId) { - String query = "Select * from gcc_1913_qaqc.qaqc_upload_data where data_id = ?"; - return jdbcTemplate.queryForMap(query, dataId); - } - - public Map getErpnameById(Integer agentId) { - String query = "Select erp_username from agents_list where agent_id = ?"; - return jdbcTemplate.queryForMap(query, agentId); - } - -// public boolean ChangeStatusInErp(String complaintNumber, String remarks, String action,String Erpname) { -// String urlString = ""; -// -// if(remarks.isEmpty()) { -// remarks="N/A"; -// } -// -// if("COMPLETED".equals(action) || "WRONG_ASSIGN".equals(action)) { -// -// urlString="https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=UpdateComplaint&ComplaintId="+complaintNumber+"&Message="+remarks+"&UserType=Official&Status=11&erp_username="+Erpname; -// System.out.println(urlString); -// //urlencode -// try { -// -// URL url = new URL(urlString); -// URLConnection urlcon=url.openConnection(); -// InputStream stream=urlcon.getInputStream(); -// StringBuilder responseBuilder = new StringBuilder(); -// int i; -// while((i=stream.read())!=-1){ -// responseBuilder.append((char) i); -// } -// stream.close(); -// -// // Parse the response -// String response = responseBuilder.toString(); -// System.out.println("Raw Response from ERP if Completed: " + response); // Debug: Print the raw response -// -// // Check ResultStatus in the response -// if (response.contains("\"ResultStatus\": true")) { -// System.out.println("ResultStatus is true in the response."); // Debug: Positive ResultStatus -// return true; -// } -// else { -// System.out.println("ResultStatus is false or not present in the response."); // Debug: Negative or missing ResultStatus -// return false; -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// } -// -// if("REOPEN".equals(action)) { -// urlString="https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=UpdateComplaint&ComplaintId="+complaintNumber+"&Message="+remarks+"&UserType=Official&Status=9&Comp_Image=64baseString&erp_username="+Erpname; -// System.out.println(urlString); -// try { -// URL url = new URL(urlString); -// URLConnection urlcon=url.openConnection(); -// InputStream stream=urlcon.getInputStream(); -// StringBuilder responseBuilder = new StringBuilder(); -// int i; -// while((i=stream.read())!=-1){ -// responseBuilder.append((char) i); -// } -// stream.close(); -// -// // Parse the response -// String response = responseBuilder.toString(); -// System.out.println("Raw Response from ERP if Reopen: " + response); -// -// // Check ResultStatus in the response -// if (response.contains("\"ResultStatus\": true")) { -// System.out.println("ResultStatus is true in the response."); // Debug: Positive ResultStatus -// return true; -// } -// else { -// System.out.println("ResultStatus is false or not present in the response."); // Debug: Negative or missing ResultStatus -// return false; -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// } -// return false; -// -// } - -// public boolean ChangeStatusInErp(String complaintNumber, String remarks, String action, String Erpname) { -// String urlString = ""; -// -// if (remarks.isEmpty()) { -// remarks = "N/A"; -// } -// -// try { -// // Encode parameters -// String encodedComplaintNumber = URLEncoder.encode(complaintNumber, StandardCharsets.UTF_8.toString()).replace("+", "%20"); -// String encodedRemarks = URLEncoder.encode(remarks, StandardCharsets.UTF_8.toString()).replace("+", "%20"); -// String encodedErpname = URLEncoder.encode(Erpname, StandardCharsets.UTF_8.toString()).replace("+", "%20"); -// -// if ("COMPLETED".equals(action) || "WRONG_ASSIGN".equals(action)) { -// urlString = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?" -// + "serviceId=UpdateComplaint" -// + "&ComplaintId=" + encodedComplaintNumber -// + "&Message=" + encodedRemarks -// + "&UserType=Official" -// + "&Status=11" -// + "&erp_username=" + encodedErpname; -// -// System.out.println(urlString); -// -// return sendRequest(urlString); -// } -// -// if ("REOPEN".equals(action)) { -// urlString = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?" -// + "serviceId=UpdateComplaint" -// + "&ComplaintId=" + encodedComplaintNumber -// + "&Message=" + encodedRemarks -// + "&UserType=Official" -// + "&Status=9" -// + "&Comp_Image=64baseString" -// + "&erp_username=" + encodedErpname; -// -// System.out.println(urlString); -// -// return sendRequest(urlString); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// -// return false; -// } - - public boolean ChangeStatusInErp(String complaintNumber, String remarks, String action, String Erpname) { - String baseUrl = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?"; - String status = ""; - - if (remarks.isEmpty()) { - remarks = "N/A"; - } - - try { - // Encode parameters - String encodedComplaintNumber = URLEncoder.encode(complaintNumber, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - String encodedRemarks = URLEncoder.encode(remarks, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - String encodedErpname = URLEncoder.encode(Erpname, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - - // Determine status based on action - if ("COMPLETED".equals(action) || "WRONG_ASSIGN".equals(action)) { - status = "11"; - } else if ("REOPEN".equals(action)) { - status = "9"; - } else { - return false; // Invalid action, return false - } - - // Construct the URL - String urlString = baseUrl - + "serviceId=UpdateComplaint" - + "&ComplaintId=" + encodedComplaintNumber - + "&Message=" + encodedRemarks - + "&UserType=Official" - + "&Status=" + status - + "&Comp_Image=" - + "&erp_username=" + encodedErpname; - - System.out.println(urlString); - - // Send the request - return sendRequest(urlString); - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - - private boolean sendRequest(String urlString) { - try { - URL url = new URL(urlString); - URLConnection urlcon = url.openConnection(); - InputStream stream = urlcon.getInputStream(); - StringBuilder responseBuilder = new StringBuilder(); - int i; - while ((i = stream.read()) != -1) { - responseBuilder.append((char) i); - } - stream.close(); - - // Parse the response - String response = responseBuilder.toString(); - //System.out.println("Raw Response: " + response); - - // Check ResultStatus in the response - if (response.contains("\"ResultStatus\": true")) { - //System.out.println("ResultStatus is true in the response."); - return true; - } else { - System.out.println("ResultStatus is false or not present in the response."); - return false; - } - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - - public void saveMobileNumDetails(String complaintNumber, String remarks) { - String query = "insert into officer_mobileno (complaint_number,remarks) values(?,?)"; - int rowsUpdated = jdbcTemplate.update(query, complaintNumber, remarks); - //System.out.println("Rows Updated: " + rowsUpdated); - } - - public Map checkComplaintDetail(String complaintNumber) { - String query = "select id,complaint_number from qaqc_followup_call_logs where complaint_number = ?"; - try { - return jdbcTemplate.queryForMap(query, complaintNumber); - } catch (Exception e) { - System.out.println("Complaint number not found"); - return null; - } - } - - public void updateFollowupCallLogs(String complaintNumber, String action, String remarks, int followupid) { - //System.out.println(complaintNumber+action+remarks); - - String query = "update gcc_1913_qaqc.qaqc_followup_call_logs set call_status = ?,remarks = ? where complaint_number= ? and id =?"; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks, complaintNumber, followupid); - //System.out.println("Rows Updated in followup: " + rowsUpdated); - - } - - public List> getSubmitDetails(int userId) { - - String query = "SELECT complaint_number, complaint_date,complaint_person_name, complaint_mobilenumber, " + - "complaint_type, call_status, remarks " + - "FROM gcc_1913_qaqc.qaqc_upload_data " + - "WHERE agent_id = ? AND call_category = 'CLOSED' AND is_processed = '1'"; - - return jdbcTemplate.queryForList(query,userId); - - } - - public void updateComplaintHistoryDetails(String complaintNumber, int dataId, String action, String remarks,int updated_agent, - String remainderDate) { - - String query = "UPDATE gcc_1913_qaqc.qaqc_upload_data_history \r\n" - + "SET call_status = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP, remainder_date = ?,updated_agent=?\r\n" - + "WHERE data_id = ? AND complaint_number = ? AND call_category = 'CLOSED'"; - - int rowsUpdated = jdbcTemplate.update(query, action, remarks, remainderDate,updated_agent, dataId, complaintNumber); - - //System.out.println("Rows Updated in upload history: " + rowsUpdated); - - } - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcService.java deleted file mode 100644 index 0354a0eb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcService.java +++ /dev/null @@ -1,357 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class QaqcService { - - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - - public List> getFollowUpDetailsByStatus(String callStatus, LocalDate fromDate, LocalDate toDate) { - // Start the SQL query - String sql = "SELECT " + - "f.id, " + - "f.qaqc_id, " + - "f.call_category, " + - "f.complaint_number, " + - "f.agent_id, " + - "f.complaint_person_name, " + - "f.complaint_mobilenumber, " + - "f.complaint_type, " + - "f.complaint_mode, " + - "f.department, " + - "f.complaint_group, " + - "f.official_name, " + - "f.official_mobilenum, " + - "f.call_status, " + - "f.remainder_date, " + - "f.remarks, " + - "f.created_date, " + - "r.taskid " + - "FROM qaqc_followup_call_logs f " + - "LEFT JOIN qaqc_request r ON f.qaqc_id = r.qaqc_id "; - - // List to hold the query parameters - List params = new ArrayList<>(); - boolean hasCondition = false; - - // Filter by callStatus if provided - if (callStatus != null && !callStatus.isEmpty()) { - sql += " WHERE f.call_status = ?"; - params.add(callStatus); - hasCondition = true; - } - - // Filter by date range (fromDate to toDate) if both are provided - if (fromDate != null && toDate != null) { - if (hasCondition) { - sql += " AND f.remainder_date BETWEEN ? AND ?"; - } else { - sql += " WHERE f.remainder_date BETWEEN ? AND ?"; - hasCondition = true; - } - params.add(fromDate); - params.add(toDate); - } - // If only fromDate is provided - else if (fromDate != null) { - if (hasCondition) { - sql += " AND f.remainder_date >= ?"; - } else { - sql += " WHERE f.remainder_date >= ?"; - hasCondition = true; - } - params.add(fromDate); - } - // If only toDate is provided (include records with remainder_date greater than toDate) - else if (toDate != null) { - if (hasCondition) { - sql += " AND (f.remainder_date <= ? OR f.remainder_date > ?)"; - } else { - sql += " WHERE (f.remainder_date <= ? OR f.remainder_date > ?)"; - hasCondition = true; - } - params.add(toDate); // <= toDate condition - params.add(toDate); // > toDate condition - } - - // Final debugging: print the query and parameters - //System.out.println("Final SQL Query: " + sql); - //System.out.println("Query Parameters: " + params); - - // Execute the query with the dynamically added parameters - return jdbcTemplate.queryForList(sql, params.toArray()); - } - -/* - - public Map countFollowUpsByDateAndStatus(LocalDate today, String followupStatus) { - String sqlNotClosed = "SELECT COUNT(*) FROM qaqc_followup_call_logs " + - "WHERE call_status = ? AND DATE(remainder_date) = ? AND call_category NOT IN ('CLOSED')"; - - String sqlClosed = "SELECT COUNT(*) FROM qaqc_followup_call_logs " + - "WHERE call_status = ? AND DATE(remainder_date) = ? AND call_category IN ('CLOSED')"; - - long countNotClosed = jdbcTemplate.queryForObject(sqlNotClosed, new Object[]{followupStatus, today}, Long.class); - long countClosed = jdbcTemplate.queryForObject(sqlClosed, new Object[]{followupStatus, today}, Long.class); - - Map result = new HashMap<>(); - result.put("officialfollowup", countNotClosed); - result.put("publicfollowup", countClosed); - - return result; - } - */ - public Map countFollowUpsByDateAndStatus(LocalDate today, String followupStatus) { - String sqlNotClosed = "SELECT COUNT(*) FROM qaqc_followup_call_logs " + - "WHERE call_status = ? AND DATE(remainder_date) = ? AND call_category NOT IN ('CLOSED','PUBLICFOLLOWUP')"; - - String sqlClosed = "SELECT COUNT(*) FROM qaqc_followup_call_logs " + - "WHERE call_status = ? AND DATE(remainder_date) = ? AND call_category IN ('CLOSED','PUBLICFOLLOWUP')"; - - long countNotClosed = jdbcTemplate.queryForObject(sqlNotClosed, new Object[]{followupStatus, today}, Long.class); - long countClosed = jdbcTemplate.queryForObject(sqlClosed, new Object[]{followupStatus, today}, Long.class); - - Map result = new HashMap<>(); - result.put("officialfollowup", countNotClosed); - result.put("publicfollowup", countClosed); - - return result; - } - - - public List> getUnattendedlist(Integer ucount) { - - String query1="SELECT \r\n" - + " MIN(complaint_date) AS complaint_date, \r\n" - + " MIN(call_category) AS call_category, \r\n" - + " MIN(complaint_person_name) AS complaint_person_name, \r\n" - + " MIN(complaint_mobilenumber) AS complaint_mobilenumber, \r\n" - + " complaint_number AS complaint_number, \r\n" - + " MIN(complaint_group) AS complaint_group, \r\n" - + " MIN(complaint_type) AS complaint_type, \r\n" - + " MIN(complaint_mode) AS complaint_mode \r\n" - + " FROM qaqc_upload_data_history \r\n" - + " WHERE unattended_msg = 0 \r\n" - + " AND call_status = 'UNATTENDED' \r\n" - + " AND call_category IN ('CLOSED', 'PUBLICFOLLOWUP') \r\n" - + " GROUP BY complaint_number \r\n" - + " HAVING COUNT(*) >= ? \r\n" - + " LIMIT 100"; - - - // Log query and parameters for debugging - //System.out.println("Executing query: " + query1); - //System.out.println("With parameters: " + ucount); - - List> results = jdbcTemplate.queryForList(query1, ucount); - - // Log results for debugging - //System.out.println("Query results: " + results); - - return results.isEmpty() ? Collections.emptyList() : results; - } - - - - - public boolean ChangeStatusInErp(String complaintNumber,String erp_name,String remarks) { - String baseUrl = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?"; - String status = "11"; - - //String Erpname ="QAops1"; - - try { - // Encode parameters - String encodedComplaintNumber = URLEncoder.encode(complaintNumber, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - String encodedRemarks = URLEncoder.encode(remarks, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - String encodedErpname = URLEncoder.encode(erp_name, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - - //System.out.println("encodedComplaintNumber===="+encodedComplaintNumber); - //System.out.println("encodedErpname===="+encodedErpname); - //System.out.println("encodedRemarks===="+encodedRemarks); - - // Construct the URL - String urlString = baseUrl - + "serviceId=UpdateComplaint" - + "&ComplaintId=" + encodedComplaintNumber - + "&Message=" + encodedRemarks - + "&UserType=Official" - + "&Status=" + status - + "&Comp_Image=" - + "&erp_username=" + encodedErpname; - - System.out.println("ERP Hitting URL="+urlString); - - // Send the request - return sendRequest(urlString); - - //return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - - private boolean sendRequest(String urlString) { - try { - URL url = new URL(urlString); - URLConnection urlcon = url.openConnection(); - InputStream stream = urlcon.getInputStream(); - StringBuilder responseBuilder = new StringBuilder(); - int i; - while ((i = stream.read()) != -1) { - responseBuilder.append((char) i); - } - stream.close(); - - // Parse the response - String response = responseBuilder.toString(); - //System.out.println("Raw Response: " + response); - - // Check ResultStatus in the response - if (response.contains("\"ResultStatus\": true")) { - //System.out.println("ResultStatus is true in the response."); - return true; - } else { - System.out.println("ResultStatus is false or not present in the response."); - return false; - } - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - - public String getErpusernamebyId(String userId) { - - String query="SELECT erp_username FROM gcc_1913_qaqc.agents_list\r\n" - + "where calling_type='1913ADMIN' and agent_id=?"; - - //System.out.println("query"+query); - - //String erpUsername = jdbcTemplate.queryForObject(query,new Object[]{userId},String.class); - String erpUsername = jdbcTemplate.queryForObject(query,String.class,userId); - - return erpUsername; - } - - - - public int UpdateInHistoryTable(List completedComplaints) { - int totalUpdated = 0; - - for (String cnum : completedComplaints) { - String query = "UPDATE qaqc_upload_data_history SET unattended_msg = 1 WHERE complaint_number = ?"; - - // Update using JdbcTemplate and accumulate the count - int rowsUpdated = jdbcTemplate.update(query, cnum); - - // Accumulate the number of successfully updated rows - totalUpdated += rowsUpdated; - } - - return totalUpdated; // Return the total number of updated rows - } - - - - public int insertInLogs(List completedComplaints,String remarks,String userId) { - - int totalUpdated = 0; - int rowsUpdated=0; - - for (String cnum : completedComplaints) { - - List>details=getComplaintsLatestDetails(cnum); - - if(!details.isEmpty()) { - - for (Map detail : details) { - int qaqc_id = Integer.parseInt(detail.get("qaqc_id").toString()); - String call_category = "UNATTENDED"; - int agent_id = Integer.parseInt(detail.get("agent_id").toString()); - - // # id, qaqc_id, call_category, agent_id, complaint_number, complaint_date, complaint_person_name, - // complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, - // call_status, remainder_date, remarks, created_date, is_processed, updated_agent - String complaint_number = detail.get("complaint_number").toString(); - String complaint_date = detail.get("complaint_date").toString(); - String complaint_person_name = detail.get("complaint_person_name").toString(); - String complaint_mobilenumber = detail.get("complaint_mobilenumber").toString(); - String complaint_type = detail.get("complaint_type").toString(); - String complaint_mode = detail.get("complaint_mode").toString(); - String department = detail.get("department").toString(); - String complaint_group = detail.get("complaint_group").toString(); - String official_name = detail.get("official_name").toString(); - String official_mobilenum = detail.get("official_mobilenum").toString(); - String call_status = "COMPLETED"; - String upremarks=remarks; - int is_processed=1; - int updated_agent = Integer.parseInt(userId); - - String query = "INSERT INTO gcc_1913_qaqc.qaqc_call_logs (qaqc_id, call_category, agent_id, complaint_number, complaint_date,complaint_person_name, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, call_status, remarks, is_processed,updated_agent) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - rowsUpdated = jdbcTemplate.update(query, qaqc_id, call_category, agent_id, complaint_number,complaint_date, complaint_person_name, - complaint_mobilenumber, complaint_type, complaint_mode, department, complaint_group, official_name, official_mobilenum, call_status, upremarks, - is_processed,updated_agent); - - totalUpdated += rowsUpdated; - - } - - } - else { - return 0; - } - - } - - return totalUpdated; - } - - - public List> getComplaintsLatestDetails(String complaint_number){ - - String query = "SELECT * FROM qaqc_upload_data_history WHERE complaint_number = ? ORDER BY created_date DESC LIMIT 1"; - - List> getCompNumber = jdbcTemplate.queryForList(query, complaint_number); - - return getCompNumber; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcTaskListService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcTaskListService.java deleted file mode 100644 index e5e01e0c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcTaskListService.java +++ /dev/null @@ -1,291 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.util.ArrayList; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class QaqcTaskListService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - -// old overalltaskcount wise method - -// public List> getComplaintAndCallStatusCounts(String startDate, String endDate) { -// String sql = "SELECT " + -// "t1.total_tasks, " + -// "t2.total_calls, " + -// "t3.completed_calls, " + -// "t2.total_calls - t3.completed_calls AS pending_calls " + -// "FROM " + -// "( " + -// " SELECT " + -// " COUNT(qaqc_id) AS total_tasks " + -// " FROM " + -// " qaqc_request " + -// " WHERE " + -// " (? IS NULL OR created_date BETWEEN ? AND ?) " + -// ") AS t1, " + -// "( " + -// " SELECT " + -// " SUM(total_data) AS total_calls " + -// " FROM " + -// " qaqc_request " + -// " WHERE " + -// " (? IS NULL OR created_date BETWEEN ? AND ?) " + -// ") AS t2, " + -// "( " + -// " SELECT " + -// " SUM(qr.total_data) AS total_data, " + -// " COUNT(CASE WHEN qcl.qaqc_id IS NOT NULL THEN qcl.qaqc_id END) AS completed_calls " + -// " FROM " + -// " qaqc_request qr " + -// " LEFT JOIN " + -// " qaqc_call_logs qcl " + -// " ON " + -// " qr.qaqc_id = qcl.qaqc_id " + -// " WHERE " + -// " (? IS NULL OR qcl.created_date BETWEEN ? AND ?) " + -// ") AS t3;"; -// -// // Prepare the parameters for the query -// Object[] params = new Object[] { -// startDate, startDate, endDate, -// startDate, startDate, endDate, -// startDate, startDate, endDate -// }; -// -// // Execute the query and return the results as a List of Maps -// return jdbcTemplate.queryForList(sql, params); -// } - - - - //updated overalltaskcount method - public List> getComplaintAndCallStatusCounts(String startDate, String endDate) { - // Start constructing the SQL query dynamically - StringBuilder sql = new StringBuilder(); - sql.append("SELECT ") - .append("t1.total_tasks, ") - .append("t2.total_calls, ") - .append("t3.completed_calls, ") - .append("t2.total_calls - t3.completed_calls AS pending_calls, ") - .append("t4.no_of_agents ") - .append("FROM ") - .append("( ") - .append(" SELECT ") - .append(" COUNT(qaqc_id) AS total_tasks ") - .append(" FROM ") - .append(" qaqc_request qr "); - - // Adding dynamic WHERE conditions for date range if provided - if (startDate != null && endDate != null) { - sql.append("WHERE DATE(qr.created_date) >= ? AND DATE(qr.created_date) <= ? "); - } - - sql.append(") AS t1, ") - .append("( ") - .append(" SELECT ") - .append(" SUM(aa.data_count) AS total_calls ") - .append(" FROM ") - .append(" agent_assigned aa ") - .append(" INNER JOIN ") - .append(" qaqc_request qr ") - .append(" ON ") - .append(" aa.qaqc_id = qr.qaqc_id "); - - if (startDate != null && endDate != null) { - sql.append("WHERE DATE(qr.created_date) >= ? AND DATE(qr.created_date) <= ? "); - } - - sql.append(") AS t2, ") - .append("( ") - .append(" SELECT ") - .append(" SUM(qr.total_data) AS total_data, ") - .append(" COUNT(CASE WHEN qcl.call_status IS NOT NULL THEN qcl.qaqc_id END) AS completed_calls ") - .append(" FROM ") - .append(" qaqc_request qr ") - .append(" LEFT JOIN ") - .append(" qaqc_upload_data_history qcl ") - .append(" ON ") - .append(" qr.qaqc_id = qcl.qaqc_id "); - - if (startDate != null && endDate != null) { - sql.append("WHERE DATE(qcl.created_date) >= ? AND DATE(qcl.created_date) <= ? "); - } - - sql.append(") AS t3, ") - .append("( ") - .append(" SELECT ") - .append(" COUNT(DISTINCT aa.agent_id) AS no_of_agents ") - .append(" FROM ") - .append(" agent_assigned aa "); - - if (startDate != null && endDate != null) { - sql.append("WHERE DATE(aa.created_date) >= ? AND DATE(aa.created_date) <= ? "); - } - - sql.append(") AS t4;"); - - // Prepare the parameters dynamically based on the presence of the date range - List params = new ArrayList<>(); - if (startDate != null && endDate != null) { - params.add(startDate); - params.add(endDate); - params.add(startDate); - params.add(endDate); - params.add(startDate); - params.add(endDate); - params.add(startDate); - params.add(endDate); - } - - // Execute the query and return the results as a List of Maps - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - - - - //old taskwise querymethod - -// public List> getTaskwiseData(String startDate, String endDate) { -// // Base query -// StringBuilder query = new StringBuilder( -// "SELECT " + -// " qr.taskid, " + -// " MAX(qr.total_data) AS Assigned, " + -// " MAX(qr.created_date) AS TaskCreatedDate, " + -// " COUNT(CASE WHEN acl.qaqc_id IS NOT NULL THEN qr.qaqc_id END) AS TotalCompleted, " + -// " MAX(qr.total_data) - COUNT(CASE WHEN acl.qaqc_id IS NOT NULL THEN qr.qaqc_id END) AS Pending, " + // Pending calculated as Assigned - TotalCompleted -// " COUNT(CASE WHEN acl.call_status = 'COMPLETED' THEN 1 END) AS Completed, " + -// " COUNT(CASE WHEN acl.call_status = 'REOPENED' THEN 1 END) AS Reopened, " + -// " COUNT(CASE WHEN acl.call_status = 'FOLLOWUP' THEN 1 END) AS Followup " + -// "FROM qaqc_request qr " + -// "LEFT JOIN qaqc_call_logs acl " + -// "ON qr.qaqc_id = acl.qaqc_id " -// ); -// -// // Adding dynamic WHERE conditions for date range -// if (startDate != null && endDate != null) { -// query.append("WHERE qr.created_date BETWEEN ? AND ? "); -// } -// -// // Grouping by taskid -// query.append("GROUP BY qr.taskid"); -// -// // Query Execution -// if (startDate != null && endDate != null) { -// return jdbcTemplate.queryForList(query.toString(), startDate, endDate); -// } else { -// return jdbcTemplate.queryForList(query.toString()); -// } -// } - - - //updated taskwisedata query method - - public List> getTaskwiseData(String startDate, String endDate) { - // Base query with subqueries for Assigned and Pending calculations - StringBuilder query = new StringBuilder( - "SELECT " + - " qr.qaqc_id, " + - " qr.taskid, " + - " qr.call_category, " + - " qr.description, " + - " (" + - " SELECT SUM(aa.data_count) " + - " FROM agent_assigned aa " + - " WHERE aa.qaqc_id = qr.qaqc_id" + - " ) AS Assigned, " + - " MAX(DATE(qr.created_date)) AS TaskCreatedDate, " + - " COUNT(CASE WHEN acl.call_status IS NOT NULL THEN acl.qaqc_id END) AS TotalCompleted, " + - " (" + - " SELECT SUM(aa.data_count) " + - " FROM agent_assigned aa " + - " WHERE aa.qaqc_id = qr.qaqc_id" + - " ) - COUNT(CASE WHEN acl.call_status IS NOT NULL THEN acl.qaqc_id END) AS Pending, " + - " COUNT(CASE WHEN acl.call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 END) AS Completed, " + - " COUNT(CASE WHEN acl.call_status = 'REOPEN' THEN 1 END) AS Reopened, " + - " COUNT(CASE WHEN acl.call_status = 'FOLLOWUP' THEN 1 END) AS Followup, " + - " COUNT(CASE WHEN acl.call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 ELSE NULL END) AS Others " + - "FROM qaqc_request qr " + - "LEFT JOIN qaqc_upload_data_history acl " + - "ON qr.qaqc_id = acl.qaqc_id " - ); - - // Adding dynamic WHERE conditions for date range if provided - if (startDate != null && endDate != null) { - query.append("WHERE DATE(qr.created_date) >= ? AND DATE(qr.created_date) <= ? "); - } - - // Grouping by taskid and qaqc_id to calculate Assigned and Pending - query.append("GROUP BY qr.taskid, qr.qaqc_id "); - - // Adding ORDER BY clause for descending order of created_date - query.append("ORDER BY TaskCreatedDate DESC, qr.qaqc_id DESC"); - - // Query execution with parameters for start and end dates if available - if (startDate != null && endDate != null) { - return jdbcTemplate.queryForList(query.toString(), startDate, endDate); - } else { - return jdbcTemplate.queryForList(query.toString()); - } - } - - - - - - public List> getAgentwiseData(String qaqc_id) { - - String query= "SELECT DISTINCT \r\n" - + " al.agent_id,\r\n" - + " al.agent_name AS agentName,\r\n" - + " qr.taskid AS taskId,\r\n" - + " qr.fromdate AS fromdate,\r\n" - + " qr.todate AS todate,\r\n" - + " qr.description AS description,\r\n" - + " qr.call_category AS call_category,\r\n" - + " qr.complaint_region AS complaint_region,\r\n" - + " qr.complaint_group AS complaint_group,\r\n" - + " qr.complaint_type AS complaint_type,\r\n" - + " qr.complaint_mode AS complaint_mode,\r\n" - + " qr.complaint_zone AS complaint_zone,\r\n" - + " DATE(qr.created_date) AS TaskCreatedDate,\r\n" - + " aa.data_count AS assigned,\r\n" - + " COUNT(lcl.call_status) AS callstaken,\r\n" - + " (aa.data_count - COUNT(lcl.call_status)) AS pending,\r\n" - + " ROUND((COUNT(lcl.call_status) / aa.data_count) * 100, 2) AS percentage,\r\n" - + " COUNT(CASE WHEN lcl.call_status IN ('COMPLETED', 'FOLLOWUP_COMPLETED') THEN 1 END) AS Completed,\r\n" - + " COUNT(CASE WHEN lcl.call_status = 'REOPEN' THEN 1 END) AS Reopened,\r\n" - + " COUNT(CASE WHEN lcl.call_status = 'FOLLOWUP' THEN 1 END) AS Followup,\r\n" - + " COUNT(CASE WHEN lcl.call_status NOT IN ('COMPLETED', 'FOLLOWUP_COMPLETED', 'REOPEN', 'FOLLOWUP') THEN 1 END) AS Others\r\n" - + "FROM qaqc_request qr\r\n" - + "JOIN agent_assigned aa ON aa.qaqc_id = qr.qaqc_id\r\n" - + "JOIN agents_list al ON al.agent_id = aa.agent_id\r\n" - + "LEFT JOIN qaqc_upload_data_history lcl ON qr.qaqc_id = lcl.qaqc_id AND al.agent_id = lcl.agent_id \r\n" - + "WHERE qr.qaqc_id = ?\r\n" - + "GROUP BY al.agent_id, al.agent_name, aa.data_count"; - - return jdbcTemplate.queryForList(query, qaqc_id); - } - - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/ScpService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/ScpService.java deleted file mode 100644 index 2f850a20..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/ScpService.java +++ /dev/null @@ -1,361 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class ScpService { - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlScpDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - // Method to enrich report data with questions_part - public List> enrichScpReportWithQuestions(List> reportData) { - - // Step 1: Fetch all questions - String questionSql = "SELECT id AS question_id, questions AS question, answer_type, isactive, isdelete FROM questions WHERE isactive=1 AND isdelete=0"; - List> questionList = jdbcTemplate.queryForList(questionSql); - - // Step 2: Fetch all answers (master answers) - String answerSql = "SELECT question_id, answer FROM answers WHERE isactive=1 AND isdelete=0"; - List> answerList = jdbcTemplate.queryForList(answerSql); - - // Convert answerList to Map> for easy mapping - Map> answerMasterMap = new HashMap<>(); - for (Map ans : answerList) { - Integer qid = (Integer) ans.get("question_id"); - String answerVal = (String) ans.get("answer"); - answerMasterMap.computeIfAbsent(qid, k -> new ArrayList<>()).add(answerVal); - } -/* - // Step 3: Fetch all scp_report entries for these scp_ids - List scpIds = reportData.stream() - .map(d -> ((Number) d.get("id")).longValue()) - .collect(Collectors.toList()); - - // Step 4: Get existing scp_ids from scp_report - Set existingScpIds = new HashSet<>(); - if (!scpIds.isEmpty()) { - String inClause = scpIds.stream().map(id -> "?").collect(Collectors.joining(",")); - String sql = "SELECT DISTINCT scp_id FROM scp_report WHERE isactive=1 AND isdelete=0 AND scp_id IN (" + inClause + ")"; - List> existingList = jdbcTemplate.queryForList(sql, scpIds.toArray()); - for (Map row : existingList) { - existingScpIds.add(((Number) row.get("scp_id")).longValue()); - } - } - - // Step 5: Filter out already answered scp_ids - List> filteredReportData = reportData.stream() - .filter(d -> !existingScpIds.contains(((Number) d.get("id")).longValue())) - .collect(Collectors.toList()); -*/ - // Step 3: Fetch all scp_report entries for these scp_ids - List scpIds = new ArrayList(); - for (Map d : reportData) { - Object idObj = d.get("id"); - if (idObj instanceof Number) { - scpIds.add(((Number) idObj).longValue()); - } - } - - // Step 4: Get existing scp_ids from scp_report - Set existingScpIds = new HashSet(); - if (!scpIds.isEmpty()) { - // Build the IN clause placeholders - StringBuilder inClause = new StringBuilder(); - for (int i = 0; i < scpIds.size(); i++) { - if (i > 0) inClause.append(","); - inClause.append("?"); - } - - String sql = "SELECT DISTINCT scp_id FROM scp_report WHERE isactive=1 AND isdelete=0 AND scp_id IN (" - + inClause.toString() + ")"; - List> existingList = jdbcTemplate.queryForList(sql, scpIds.toArray()); - for (Map row : existingList) { - Object scpIdObj = row.get("scp_id"); - if (scpIdObj instanceof Number) { - existingScpIds.add(((Number) scpIdObj).longValue()); - } - } - } - - // Step 5: Filter out already answered scp_ids - List> filteredReportData = new ArrayList>(); - for (Map d : reportData) { - Object idObj = d.get("id"); - if (idObj instanceof Number) { - Long id = ((Number) idObj).longValue(); - if (!existingScpIds.contains(id)) { - filteredReportData.add(d); - } - } - } - - // Step 6: Attach questions only to the filtered list - for (Map report : filteredReportData) { - Long scpId = ((Number) report.get("id")).longValue(); - List> questionsPart = new ArrayList<>(); - - for (Map question : questionList) { - Integer qid = (Integer) question.get("question_id"); - - Map questionPart = new HashMap<>(); - questionPart.put("question_id", qid); - questionPart.put("question", question.get("question")); - questionPart.put("answer_type", question.get("answer_type")); - questionPart.put("answer_master", answerMasterMap.getOrDefault(qid, Collections.emptyList())); - - // Empty answers since these scp_ids don’t exist yet - Map answersMap = new HashMap<>(); - answersMap.put("scp_id", scpId); - answersMap.put("question_id", qid); - answersMap.put("answer", null); - answersMap.put("agent_id", null); - - questionPart.put("answers", answersMap); - questionsPart.add(questionPart); - } - - report.put("questions_part", questionsPart); - } - - return filteredReportData; - } - - -// public boolean saveAnswers(List> answers) { -// if (answers == null || answers.isEmpty()) return false; -// -// String sql = "INSERT INTO scp_report (scp_id, question_id, answer, agent_id, zone, ward, streetid, street_name, last_feedback_date) " -// + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; -// -// int[][] result = jdbcTemplate.batchUpdate(sql, answers, answers.size(), (ps, answer) -> { -// -// // Convert safely to String or Integer -// String scpIdStr = getSafeString(answer.get("scp_id")); -// String questionIdStr = getSafeString(answer.get("question_id")); -// String answerStr = getSafeString(answer.get("answer")); -// String agentIdStr = getSafeString(answer.get("agent_id")); -// String zone = getSafeString(answer.get("zone")); -// String ward = getSafeString(answer.get("ward")); -// String streetId = getSafeString(answer.get("street_id")); -// String streetName = getSafeString(answer.get("street_name")); -// String lastFeedback = getSafeString(answer.get("lastfeedback")); -// -// // Parse integers only if not null -// Integer scpId = (scpIdStr != null) ? Integer.parseInt(scpIdStr) : null; -// Integer questionId = (questionIdStr != null) ? Integer.parseInt(questionIdStr) : null; -// Integer agentId = (agentIdStr != null) ? Integer.parseInt(agentIdStr) : null; -// -// // Set parameters -// ps.setObject(1, scpId); -// ps.setObject(2, questionId); -// ps.setObject(3, answerStr); -// ps.setObject(4, agentId); -// ps.setObject(5, zone); -// ps.setObject(6, ward); -// ps.setObject(7, streetId); -// ps.setObject(8, streetName); -// ps.setObject(9, lastFeedback); -// }); -// -// return result.length > 0; -// } - - public String saveAnswers(List> answers) { - if (answers == null || answers.isEmpty()) return "error"; -/* - // Step 1: Extract unique scp_ids from the list - List scpIds = answers.stream() - .map(a -> { - String idStr = getSafeString(a.get("scp_id")); - return (idStr != null) ? Integer.parseInt(idStr) : null; - }) - .filter(Objects::nonNull) - .distinct() - .toList(); -*/ - // Step 1: Extract unique scp_ids from the list - List scpIds = new ArrayList(); - Set uniqueIds = new HashSet(); - - for (Map a : answers) { - Object scpIdObj = a.get("scp_id"); - String idStr = getSafeString(scpIdObj); - if (idStr != null) { - try { - Integer id = Integer.parseInt(idStr); - if (!uniqueIds.contains(id)) { - uniqueIds.add(id); - scpIds.add(id); - } - } catch (NumberFormatException e) { - // Skip invalid numbers - } - } - } - - // Step 2: Check if any of these scp_ids already exist in DB - String checkSql = "SELECT COUNT(*) FROM scp_report WHERE scp_id IN (:ids)"; - Map params = new HashMap<>(); - params.put("ids", scpIds); - - NamedParameterJdbcTemplate namedJdbc = new NamedParameterJdbcTemplate(jdbcTemplate); - Integer count = namedJdbc.queryForObject(checkSql, params, Integer.class); - - if (count != null && count > 0) { - // Duplicate found — stop processing - return "duplicate"; - } - - // Step 3: Insert new answers - String insertSql = "INSERT INTO scp_report (scp_id, question_id, answer, agent_id, zone, ward, streetid, street_name, last_feedback_date) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - int[][] result = jdbcTemplate.batchUpdate(insertSql, answers, answers.size(), (ps, answer) -> { - String scpIdStr = getSafeString(answer.get("scp_id")); - String questionIdStr = getSafeString(answer.get("question_id")); - String answerStr = getSafeString(answer.get("answer")); - String agentIdStr = getSafeString(answer.get("agent_id")); - String zone = getSafeString(answer.get("zone")); - String ward = getSafeString(answer.get("ward")); - String streetId = getSafeString(answer.get("street_id")); - String streetName = getSafeString(answer.get("street_name")); - String lastFeedback = getSafeString(answer.get("lastfeedback")); - - Integer scpId = (scpIdStr != null) ? Integer.parseInt(scpIdStr) : null; - Integer questionId = (questionIdStr != null) ? Integer.parseInt(questionIdStr) : null; - Integer agentId = (agentIdStr != null) ? Integer.parseInt(agentIdStr) : null; - - ps.setObject(1, scpId); - ps.setObject(2, questionId); - ps.setObject(3, answerStr); - ps.setObject(4, agentId); - ps.setObject(5, zone); - ps.setObject(6, ward); - ps.setObject(7, streetId); - ps.setObject(8, streetName); - ps.setObject(9, lastFeedback); - }); - - return (result.length > 0) ? "success" : "error"; - } - - - // Helper method - private String getSafeString(Object val) { - if (val == null) return null; - String s = val.toString().trim(); - return s.isEmpty() ? null : s; - } - - - public List> getZoneWiseReportData() { - String sql = "SELECT " - + "sr.zone," - + " COALESCE(COUNT(DISTINCT sr.scp_id), 0) AS Completed," - + " SUM(CASE WHEN sr.answer = 'Yes' THEN 1 ELSE 0 END) AS YesCount," - + " SUM(CASE WHEN sr.answer = 'No' THEN 1 ELSE 0 END) AS NoCount," - + " SUM(CASE WHEN sr.answer = 'Available' THEN 1 ELSE 0 END) AS AvailableCount," - + " SUM(CASE WHEN sr.answer = 'Not Available' THEN 1 ELSE 0 END) AS NotAvailableCount," - + " SUM(CASE WHEN sr.answer = 'Image Not Clear' THEN 1 ELSE 0 END) AS ImageNotClearCount," - + " SUM(CASE WHEN sr.answer = 'Yes,it is in good condition' THEN 1 ELSE 0 END) AS LidGoodYesCount," - + " SUM(CASE WHEN sr.answer = 'No,it is not in good condition' THEN 1 ELSE 0 END) AS LidGoodNoCount" - + " FROM scp_report sr" - + " WHERE sr.isactive = 1 AND sr.isdelete = 0" - + " GROUP BY sr.zone" - + " ORDER BY sr.zone"; - - return jdbcTemplate.queryForList(sql); - } - - public List> getWardWiseReportData(String zone) { - String sql = "SELECT " - + "sr.zone," - + "sr.ward," - + " COALESCE(COUNT(DISTINCT sr.scp_id), 0) AS Completed," - + " SUM(CASE WHEN sr.answer = 'Yes' THEN 1 ELSE 0 END) AS YesCount," - + " SUM(CASE WHEN sr.answer = 'No' THEN 1 ELSE 0 END) AS NoCount," - + " SUM(CASE WHEN sr.answer = 'Available' THEN 1 ELSE 0 END) AS AvailableCount," - + " SUM(CASE WHEN sr.answer = 'Not Available' THEN 1 ELSE 0 END) AS NotAvailableCount," - + " SUM(CASE WHEN sr.answer = 'Image Not Clear' THEN 1 ELSE 0 END) AS ImageNotClearCount," - + " SUM(CASE WHEN sr.answer = 'Yes,it is in good condition' THEN 1 ELSE 0 END) AS LidGoodYesCount," - + " SUM(CASE WHEN sr.answer = 'No,it is not in good condition' THEN 1 ELSE 0 END) AS LidGoodNoCount" - + " FROM scp_report sr" - + " WHERE sr.isactive = 1 AND sr.isdelete = 0 AND sr.zone= ?" - + " GROUP BY sr.zone,sr.ward" - + " ORDER BY sr.zone,sr.ward"; - - return jdbcTemplate.queryForList(sql,zone); - } - - public List> getStreetWiseReportData(String zone,String ward) { - String sql = "SELECT " - + "sr.zone," - + "sr.ward," - + "sr.streetid," - + " COALESCE(COUNT(DISTINCT sr.scp_id), 0) AS Completed," - + " SUM(CASE WHEN sr.answer = 'Yes' THEN 1 ELSE 0 END) AS YesCount," - + " SUM(CASE WHEN sr.answer = 'No' THEN 1 ELSE 0 END) AS NoCount," - + " SUM(CASE WHEN sr.answer = 'Available' THEN 1 ELSE 0 END) AS AvailableCount," - + " SUM(CASE WHEN sr.answer = 'Not Available' THEN 1 ELSE 0 END) AS NotAvailableCount," - + " SUM(CASE WHEN sr.answer = 'Image Not Clear' THEN 1 ELSE 0 END) AS ImageNotClearCount," - + " SUM(CASE WHEN sr.answer = 'Yes,it is in good condition' THEN 1 ELSE 0 END) AS LidGoodYesCount," - + " SUM(CASE WHEN sr.answer = 'No,it is not in good condition' THEN 1 ELSE 0 END) AS LidGoodNoCount" - + " FROM scp_report sr" - + " WHERE sr.isactive = 1 AND sr.isdelete = 0 AND sr.zone=? AND sr.ward=?" - + " GROUP BY sr.streetid, sr.street_name,sr.zone,sr.ward" - + " ORDER BY sr.zone,sr.ward,sr.streetid"; - - return jdbcTemplate.queryForList(sql,zone,ward); - } - - - public List> getdetailreport(String startDate, String endDate) { - - - String sql = "SELECT " - + "sr.zone," - + "sr.ward," - + "sr.street_name," - + " COALESCE(COUNT(DISTINCT sr.scp_id), 0) AS Completed," - + " SUM(CASE WHEN sr.answer = 'Yes' THEN 1 ELSE 0 END) AS YesCount," - + " SUM(CASE WHEN sr.answer = 'No' THEN 1 ELSE 0 END) AS NoCount," - + " SUM(CASE WHEN sr.answer = 'Available' THEN 1 ELSE 0 END) AS AvailableCount," - + " SUM(CASE WHEN sr.answer = 'Not Available' THEN 1 ELSE 0 END) AS NotAvailableCount," - + " SUM(CASE WHEN sr.answer = 'Image Not Clear' THEN 1 ELSE 0 END) AS ImageNotClearCount," - + " SUM(CASE WHEN sr.answer = 'Yes,it is in good condition' THEN 1 ELSE 0 END) AS LidGoodYesCount," - + " SUM(CASE WHEN sr.answer = 'No,it is not in good condition' THEN 1 ELSE 0 END) AS LidGoodNoCount" - + " FROM scp_report sr" - + " WHERE sr.isactive = 1 AND sr.isdelete = 0 AND DATE(sr.created_date) BETWEEN ? AND ?" - + " GROUP BY sr.streetid, sr.street_name,sr.zone,sr.ward" - + " ORDER BY sr.zone,sr.ward,sr.streetid"; - - return jdbcTemplate.queryForList(sql,startDate,endDate); - - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java deleted file mode 100644 index 325b41f8..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java +++ /dev/null @@ -1,822 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.HashMap; - -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.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.multipart.MultipartFile; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.vendor.service.DateTimeUtil; - -@Service -@Transactional -public class SocialMediaService { - - private final RestTemplate restTemplate; - - @Autowired - private JdbcTemplate jdbcTemplate; - - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - @Qualifier("vendorDateTimeUtil") - private DateTimeUtil dateTimeUtil; - - private final Environment environment; - - private String fileBaseUrl; - - public SocialMediaService(Environment environment,RestTemplate restTemplate) { - this.restTemplate=restTemplate; - this.environment = environment; - this.fileBaseUrl = environment.getProperty("fileBaseUrl"); - } - - @Transactional - public int uploadComplaintDetailsInLogs(Map details,String action,String remarks,int updated_agent,String remainderDate) { - //System.out.println("Complaint Details: " + details); - // Extract other field values from complaintDetails - String complaintNumber = details.get("complaintid").toString(); - String complaintDate = details.get("complaintdate").toString(); - String personName = details.get("complainantName").toString(); - String personMobNo = details.get("mobileNumber").toString(); - String cType = details.get("complaintType").toString(); - String cMode = details.get("compmode").toString(); - String department = details.get("deptname").toString(); - String officialName = details.get("Officialname").toString(); - String officialMobileNum = details.get("OfficialMobile").toString(); - String callStatus = action; - String remarksfield = remarks; - String zone = details.get("Zone").toString(); - int updated_by=updated_agent; - String cur_status = details.get("currentStatus").toString(); - - String finalremainderDate=null; - if(!remainderDate.isEmpty()) { - finalremainderDate=remainderDate; - } - - LocalDateTime currentDate = LocalDateTime.now(); - - String query = "INSERT INTO gcc_1913_qaqc.social_media_completed (complaint_number,zone,complaint_date, complaint_person_name,remarks, " - + "complaint_mobilenumber, complaint_type, complaint_mode, department, official_name,official_mobilenum, call_status,created_date,updated_by,cur_status,remainder_date) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?)"; - - int rowsAffected = jdbcTemplate.update(query, complaintNumber,zone, complaintDate,personName,remarksfield, - personMobNo, cType, cMode, department, officialName, officialMobileNum,callStatus, - currentDate,updated_by,cur_status,finalremainderDate); - //System.out.println("Rows Inserted in table : " + rowsAffected); - - return rowsAffected; - - } - - public List> getdetails(String formattedFromDate, String formattedToDate, String status, String zone) { - StringBuilder query = new StringBuilder("SELECT *,DATE_FORMAT(remainder_date, '%d/%m/%Y') as formatted_fdate FROM gcc_1913_qaqc.social_media_completed WHERE DATE(created_date) BETWEEN ? AND ? "); - List params = new ArrayList<>(); - params.add(formattedFromDate); - params.add(formattedToDate); - - if (zone != null && !zone.isEmpty()) { - query.append(" AND zone = ?"); - params.add(zone); - } - - if (status != null && !status.equals("ALL")) { - query.append(" AND call_status = ?"); - params.add(status); - } - - // Execute the query - List> results = jdbcTemplate.queryForList(query.toString(), params.toArray()); - - - return results.isEmpty() ? null : results; - } - - public String getErpusernamebyId(String userId) { - - String query="SELECT erp_username FROM gcc_1913_qaqc.agents_list " - + "where calling_type='SOCIALMEDIA' and agent_id=?"; - - //System.out.println("query====="+query); - - //String erpUsername = jdbcTemplate.queryForObject(query,new Object[]{userId},String.class); - String erpUsername = jdbcTemplate.queryForObject(query,String.class,userId); - - return erpUsername; - } - - public String get1913AdminErpusernamebyId(String userId) { - - String query="SELECT erp_username FROM gcc_1913_qaqc.agents_list " - + "where agent_id=?"; - - //System.out.println("query====="+query); - - //String erpUsername = jdbcTemplate.queryForObject(query,new Object[]{userId},String.class); - String erpUsername = jdbcTemplate.queryForObject(query,String.class,userId); - - return erpUsername; - } - - public List> getA1dropdowns() { - String sql="SELECT * FROM call_status WHERE isactive=1 AND isdelete=0 AND call_category_id=5"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception ex) { - ex.printStackTrace(); - return new ArrayList<>(); // return empty list on error - } - } - - public List> getA2dropdowns() { - String sql="SELECT * FROM call_status WHERE isactive=1 AND isdelete=0 AND call_category_id=6"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception ex) { - ex.printStackTrace(); - return new ArrayList<>(); // return empty list on error - } - } - - public List> getfiltreddetails(List> details) { - - List> followupData = getFollowupData(); - - if (followupData == null || followupData.isEmpty()) { - return details; - } - -// if(details.isEmpty()) { -// return details; -// } - - LocalDate currentDate = LocalDate.now(); - - // Store complaint_number -> followup row - Map> followupMap = new HashMap<>(); - - for (Map followup : followupData) { - - String complaintNumber = String.valueOf(followup.get("complaint_number")); - - followupMap.put(complaintNumber, followup); - } - - List> filteredDetails = new ArrayList<>(); - - for (Map detail : details) { - - String complaintNumber =String.valueOf(detail.get("Complaint Number")); - - // If complaint not in followup table - if (!followupMap.containsKey(complaintNumber)) { - - filteredDetails.add(detail); - continue; - } - - Map followupRow =followupMap.get(complaintNumber); - - String remainderDateStr =String.valueOf(followupRow.get("remainder_date")); - - LocalDate remainderDate = LocalDate.parse(remainderDateStr); - - // remainder_date <= current date - if (!remainderDate.isAfter(currentDate)) { - - // UPDATE is_processed = 0 - Integer id = (Integer) followupRow.get("id"); - - updateFollowupProcessed(id); - - filteredDetails.add(detail); - } - - // ELSE: - // remainder_date > currentDate - // skip / eliminate from frontend - } - - return filteredDetails; - } - - private void updateFollowupProcessed(Integer id) { - - String sql = - "UPDATE social_media_completed " + - "SET is_processed = 0 " + - "WHERE id = ?"; - - jdbcTemplate.update(sql, id); - } - - private List> getFollowupData() { - String sqlQuery = "select id, complaint_number,call_status, remainder_date from social_media_completed where is_processed=1 AND call_status='FOLLOWUP'"; - - return jdbcTemplate.queryForList(sqlQuery); - } - - public Map checkRegisteredComplaint(String complaintNumber) { - - Map result = new HashMap<>(); - - String sql = "SELECT is_processed " - + " FROM socialmedia_reg_completed " - + " WHERE complaint_number = ? AND isactive=1 AND isdelete=0 " - + " LIMIT 1"; - - List> list = - jdbcTemplate.queryForList(sql, complaintNumber); - - // Case 1 - if (list.isEmpty()) { - result.put("status", "NOT_FOUND"); - return result; - } - - Boolean isProcessed = (Boolean) list.get(0).get("is_processed"); - - if (!isProcessed) { - result.put("status", "PENDING_APPROVAL"); - } else { - result.put("status", "PROCESSED"); - } - - return result; - } - - public Map submitRegClosingComplaint( - String complaintNumber, - String remarks, - MultipartFile resolvedImage, - String cby) { - - Map response = new HashMap<>(); - - try { - - Integer loginId = Integer.parseInt(cby); - - String imagePath = fileUpload(resolvedImage, "resolved_img"); - - String sql = "INSERT INTO socialmedia_reg_completed " - + "(complaint_number, resolved_img, remarks, cby) " - + "VALUES (?, ?, ?, ?)"; - - int rows = jdbcTemplate.update( - sql, - complaintNumber, - imagePath, - remarks, - loginId - ); - - if (rows > 0) { - response.put("status", "SUCCESS"); - response.put("message", "Complaint submitted successfully for admin approval."); - } else { - response.put("status", "FAILED"); - response.put("message", "Unable to submit complaint."); - } - - } catch (Exception e) { - - e.printStackTrace(); - - response.put("status", "error"); - response.put("message", e.getMessage() != null - ? e.getMessage() - : "Something went wrong while submitting complaint."); - } - - return response; - } - - public String fileUpload(MultipartFile file, String name) { - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("socialmedia_1913_regcomp_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 + "_" + 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(); - - - BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); - byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50%quality - - // Write the bytes to the file - Files.write(path, bytes); - - // 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(); - } - } - - 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 Map getDetailsByComplaintNumber(String complaintNumber) { - - Map resultMap = new HashMap<>(); - - try { - String url = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=getComplaintByID&ComplaintId=" - + complaintNumber + "&imgUrlonly=yes&isQcuser=Yes&jsonResp=Yes"; - //System.out.println("Request URL: " + url); - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - String responseBody = responseEntity.getBody(); - //System.out.println("Response Body: " + responseBody); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(responseBody); - - JsonNode complaintDetails = rootNode.path(0).path("ComplaintListHistory").path(0); - - String registerDate=complaintDetails.path("complaintopendate").asText("N/A"); - //System.out.println("registerdate====="+registerDate); - - String formattedDate = "N/A"; // Default value if parsing fails - - if (!registerDate.equals("N/A") && !registerDate.isEmpty()) { - try { - // Parse the input date string - SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); - Date date = inputFormat.parse(registerDate); - - // Format the date to dd-MM-yyyy - SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy"); - formattedDate = outputFormat.format(date); - } catch (Exception e) { - e.printStackTrace(); // Log exception for debugging - } - } - - if (!complaintDetails.isMissingNode()) { - // Existing fields - resultMap.put("complaintid", complaintDetails.path("complaintid").asText("N/A")); - resultMap.put("complaintdate", formattedDate); - resultMap.put("complainantName", complaintDetails.path("CustomerName").asText("N/A")); - resultMap.put("mobileNumber", complaintDetails.path("CustomerMobile").asText("N/A")); - resultMap.put("complaintType", complaintDetails.path("complainttype").asText("N/A")); - resultMap.put("description", complaintDetails.path("complaintdetails").asText("N/A")); - resultMap.put("currentStatus", complaintDetails.path("complaintcurrentstatus").asText("N/A")); - resultMap.put("Street", complaintDetails.path("Street").asText("N/A")); - resultMap.put("Area", complaintDetails.path("Area").asText("N/A")); - resultMap.put("Landmark", complaintDetails.path("Landmark").asText("N/A")); - resultMap.put("Location", complaintDetails.path("Location").asText("N/A")); - resultMap.put("Zone", complaintDetails.path("Zone").asText("N/A")); - resultMap.put("Division", complaintDetails.path("Division").asText("N/A")); - resultMap.put("OfficialMobile", complaintDetails.path("OfficialMobile").asText("N/A")); - resultMap.put("gender", complaintDetails.path("GENDER").asText("N/A")); - resultMap.put("deptname",complaintDetails.path("DEPT_NAME").asText("N/A")); - resultMap.put("compmode", complaintDetails.path("COMP_MODE").asText("N/A")); - resultMap.put("Officialname", complaintDetails.path("Officialname").asText("N/A")); - - - } - } else { - resultMap.put("error", "Failed to retrieve complaint details."); - } - } catch (Exception e) { - e.printStackTrace(); - resultMap.put("error", "Error processing request"); - } - - return resultMap; - } - - public Map getFilteredRegComps() { - - Map response = new HashMap<>(); - - try { - - String sql = - "SELECT src.complaint_number, src.created_date,CONCAT('" + fileBaseUrl + "/gcc/files',src.resolved_img) AS img_full_path,al.agent_name as agent_name,src.remarks as remarks" + - " FROM socialmedia_reg_completed src " - + " LEFT JOIN agents_list al ON al.agent_id=src.cby " + - "WHERE src.is_processed = 0 " + - "AND src.isactive = 1 " + - "AND src.isdelete = 0"; - - List> dbList = jdbcTemplate.queryForList(sql); - - List> finalList = new ArrayList<>(); - - for (Map row : dbList) { - - String complaintNumber = - String.valueOf(row.get("complaint_number")); - - Map complaintDetails = - getDetailsByComplaintNumber(complaintNumber); - - String currentStatus = - String.valueOf( - complaintDetails.getOrDefault( - "currentStatus", - "" - ) - ); - - //System.out.println("currentStatus==="+currentStatus); - - if ("REGISTERED".equalsIgnoreCase(currentStatus) - || "FORWARDED".equalsIgnoreCase(currentStatus)) { - - Map resultRow = new HashMap<>(); - - resultRow.put("complaintnumber", complaintNumber); - //resultRow.put("submitted_date", row.get("created_date")); - Timestamp ts = (Timestamp) row.get("created_date"); - - SimpleDateFormat sdf = - new SimpleDateFormat("dd/MM/yyyy HH:mm"); - - resultRow.put("submitted_date", sdf.format(ts)); - - String img = (String) row.get("img_full_path"); - resultRow.put("img_full_path", img); - - String agent_name = (String) row.get("agent_name"); - resultRow.put("agent_name", agent_name); - - String remarks = (String) row.get("remarks"); - resultRow.put("remarks", remarks); - - finalList.add(resultRow); - - } else { - - String updateSql = - "UPDATE socialmedia_reg_completed " + - "SET updated_by = ?, " + - "updated_date = NOW(), " + - "isactive = 0, " + - "isdelete = 1 " + - "WHERE complaint_number = ?"; - - jdbcTemplate.update( - updateSql, - 0, - complaintNumber - ); - } - } - - if (finalList.isEmpty()) { - - response.put("status", "nodata"); - response.put("message", "No registered complaints found."); - - } else { - - response.put("status", "success"); - response.put("details", finalList); - } - - } catch (Exception e) { - - e.printStackTrace(); - - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - public Map approveComplaint(String complaintId, String remarks, String imgFullPath, String userid) { - - Map response = new HashMap<>(); - - try { - - Integer updated_by = Integer.parseInt(userid); - - String erp_name=get1913AdminErpusernamebyId(userid); - - boolean statusUpdated = - ChangeStatusInErp( - complaintId, - "ActionLevel1", - remarks, - erp_name, - imgFullPath); - - if (!statusUpdated) { - response.put("status", "FAILED"); - response.put("message", "Unable to move complaint to Action Level 1."); - return response; - } - - boolean statusUpdated1 = - ChangeStatusInErp( - complaintId, - "Close", - remarks, - erp_name, - ""); - - if (!statusUpdated1) { - response.put("status", "FAILED"); - response.put("message", "Unable to move complaint to Close."); - return response; - } - - String sql="UPDATE socialmedia_reg_completed " - + "SET is_processed = 1, " - + " updated_by = ?, " - + " updated_date = NOW() " - + "WHERE complaint_number = ? AND isactive=1 AND isdelete=0"; - - int rows=jdbcTemplate.update(sql,updated_by,complaintId); - - if (rows > 0) { - response.put("status", "SUCCESS"); - response.put("message", "Complaint Closed successfully."); - } else { - response.put("status", "FAILED"); - response.put("message", "Complaint Closed,Unable to insert in logs."); - } - - } catch (Exception e) { - - e.printStackTrace(); - - response.put("status", "error"); - response.put("message", e.getMessage() != null - ? e.getMessage() - : "Something went wrong while submitting complaint."); - } - - return response; - } - - public boolean ChangeStatusInErp(String complaintNumber,String action ,String remarks,String erp_name,String imgFullPath) { - String baseUrl = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice"; - String status = ""; - - - try { - - // Determine status based on action - if ("ActionLevel1".equals(action)) { - status = "5"; - } else if ("Close".equals(action)) { - status = "11"; - } else { - return false; // Invalid action, return false - } - - //String img="https://gccservices.in/gccofficialapp/files/app_icon/menu/gcc_survey_icons/Cow.png"; - - // Convert image to Base64 - String base64Image = ""; - - if (imgFullPath != null && !imgFullPath.trim().isEmpty()) { - - URL imageUrl = new URL(imgFullPath); - - try (InputStream inputStream = imageUrl.openStream()) { - - byte[] imageBytes = inputStream.readAllBytes(); - - base64Image = - Base64.getEncoder().encodeToString(imageBytes); - } - } - - String postData = - "serviceId=" + URLEncoder.encode("UpdateComplaint", "UTF-8") - + "&ComplaintId=" + URLEncoder.encode(complaintNumber, "UTF-8") - + "&Message=" + URLEncoder.encode(remarks, "UTF-8") - + "&UserType=Official" - + "&Status=" + status - + "&Comp_Image=" + URLEncoder.encode(base64Image, "UTF-8") - + "&erp_username=" + URLEncoder.encode(erp_name, "UTF-8"); - - - System.out.println("Complaint = " + complaintNumber); - System.out.println("Action = " + action); - System.out.println("Base64 Length = " + base64Image.length()); - System.out.println("Post Data Length = " + postData.length()); - - return sendRequest(baseUrl, postData); - // return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - - private boolean sendRequest(String urlString, String postData) { - - try { - URL url = new URL(urlString); - - HttpURLConnection connection = - (HttpURLConnection) url.openConnection(); - - - connection.setRequestMethod("POST"); - connection.setDoOutput(true); - - connection.setRequestProperty( - "Content-Type", - "application/x-www-form-urlencoded" - ); - - //System.out.println("Method = " + connection.getRequestMethod()); - try (OutputStream os = connection.getOutputStream()) { - - byte[] input = postData.getBytes(StandardCharsets.UTF_8); - - os.write(input, 0, input.length); - } - - int responseCode = connection.getResponseCode(); - - System.out.println("Response Code = " + responseCode); - System.out.println("Response Message = " + connection.getResponseMessage()); - - InputStream stream; - - if (responseCode >= 200 && responseCode < 300) { - stream = connection.getInputStream(); - } else { - stream = connection.getErrorStream(); - } - - StringBuilder responseBuilder = new StringBuilder(); - - if (stream != null) { - - BufferedReader reader = - new BufferedReader( - new InputStreamReader(stream)); - - String line; - - while ((line = reader.readLine()) != null) { - responseBuilder.append(line); - } - - reader.close(); - } - - String response = responseBuilder.toString(); - - System.out.println("ERP Response = " + response); - - return response.contains("\"ResultStatus\": true"); - - } catch (Exception e) { - - e.printStackTrace(); - return false; - } - } - - public Map rejectComplaint(String complaintId, String userid) { - - Map response = new HashMap<>(); - - try { - Integer updated_by = Integer.parseInt(userid); - - String sql="UPDATE socialmedia_reg_completed " - + "SET isactive=0,isdelete=1, " - + " updated_by = ?, " - + " updated_date = NOW() " - + "WHERE complaint_number = ? AND isactive=1 AND isdelete=0"; - - int rows=jdbcTemplate.update(sql,updated_by,complaintId); - - - if (rows > 0) { - response.put("status", "SUCCESS"); - response.put("message", "Complaint Rejected successfully."); - } else { - response.put("status", "FAILED"); - response.put("message", "Unable to Reject the Complaint."); - } - - } catch (Exception e) { - - e.printStackTrace(); - - response.put("status", "error"); - response.put("message", e.getMessage() != null - ? e.getMessage() - : "Something went wrong while submitting complaint."); - } - - return response; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/StatusCountService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/StatusCountService.java deleted file mode 100644 index d9caa1f8..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/StatusCountService.java +++ /dev/null @@ -1,274 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class StatusCountService { - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public StatusCountService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - public Map fetchComplaintCounts(String fromDate, String toDate, String compType, String zoneName, String compMode, String compGroup, String region) { - //https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=common_api&jsonResp=Yes&subService=dashboardAbs&fromDate=&toDate=&compType=&zoneName=&compMode=&compGroup= - String apiUrl; - if ("SOCIAL MEDIA".equalsIgnoreCase(compMode)) { - - apiUrl = appconfig.qaqcurl+"serviceId=common_api&jsonResp=Yes" - + "&subService=dashboardAbs" - + "&fromDate=" + fromDate - + "&toDate=" + toDate; - } - - else { - apiUrl = appconfig.qaqcurl+"serviceId=common_api&jsonResp=Yes" - + "&subService=dashboardAbs" - + "&fromDate=" + fromDate - + "&toDate=" + toDate - +"&excludeMode=7"; - - } - - // Append parameters based on their availability - if (!compType.isEmpty()) { - apiUrl += "&compType=" + compType; - } - - if (!zoneName.isEmpty()) { - apiUrl += "&zoneName=" + zoneName; - } - - if (!compMode.isEmpty()) { - apiUrl += "&compMode=" + compMode; - } - - if (!compGroup.isEmpty()) { - apiUrl += "&compGroup=" + compGroup; - } - - if (!region.isEmpty()) { - apiUrl += "®ion=" + region; - } - - Map counts = new HashMap<>(); - System.out.println("url: " + apiUrl); - - try { - // Get the raw response - String response = restTemplate.getForObject(apiUrl, String.class); - //System.out.println("API Response: " + response); // Log the response for debugging - - JsonNode jsonResponse = objectMapper.readTree(response); - - // Check if "ListResult" exists and is an array - JsonNode listResult = jsonResponse.path("ListResult"); - - if (listResult.isArray() && !listResult.isEmpty()) { - JsonNode resultNode = listResult.get(0); - if (resultNode != null && !resultNode.isNull()) { - counts.put("Total Complaints", resultNode.path("RECEIVED").asText("")); - counts.put("In Progress", resultNode.path("PENDING").asText("")); - counts.put("Redressed", resultNode.path("REDRESSED").asText("")); - counts.put("Reopened", resultNode.path("REOPEN").asText("")); - counts.put("Closed", resultNode.path("CLOSED").asText("")); - } - } - - //System.out.println(fromDate); - //System.out.println(toDate); - - String url="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?serviceId=ms_dashboard_details&From_date="+fromDate+"&To_date="+toDate+"&jsonResp=Yes&Status=closed&isQcuser=Yes&ComplaintType="+compType+"&ComplaintGroupId="+compGroup+"&compmode="+compMode+"&Zoneid="+zoneName+"&RegionId="+region; - System.out.println("url==="+url); - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response1 = restTemplate.getForEntity(url, String.class); - String rawResponse = response1.getBody(); - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = objectMapper.readValue(rawResponse, Map.class); - List> details = (List>) responseMap.get("Details"); - /* - long completedCount = (details == null || details.isEmpty()) ? 0 : - details.stream().filter(entry -> "Completed".equals(entry.get("Current Status"))).count(); - */ - long completedCount = 0; - - if (details != null && !details.isEmpty()) { - for (Map entry : details) { - Object statusObj = entry.get("Current Status"); - if ("Completed".equals(statusObj)) { - completedCount++; - } - } - } - - counts.put("Withdraw", String.valueOf(completedCount)); - - int closedCount = Integer.parseInt(String.valueOf(counts.getOrDefault("Closed", "0"))); - closedCount -= completedCount; // Adjust closed count - counts.put("Closed", String.valueOf(closedCount)); - - - } catch (Exception e) { - e.printStackTrace(); - } - - return counts; - - } - - - public List fetchComplaintTypes(String compGroup) { - // Construct the API URL with the compGroup parameter - String apiUrl = appconfig.qaqcurl + - "serviceId=common_api&jsonResp=Yes&subService=compTypelist&compGroup=" + compGroup; - List complaintTypes = new ArrayList<>(); - - try { - // Call the external API - ResponseEntity response = restTemplate.getForEntity(apiUrl, String.class); - - if (response.getStatusCode() == HttpStatus.OK) { - // Parse the response JSON - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode rootNode = objectMapper.readTree(response.getBody()); - - // Navigate to "ListResult" and extract "COMPLAINTTYPENAME" - JsonNode listResultNode = rootNode.path("ListResult"); - if (listResultNode.isArray()) { - for (JsonNode item : listResultNode) { - String complaintTypeName = item.path("COMPLAINTTYPENAME").asText().trim(); - complaintTypes.add(complaintTypeName); - } - } - } - } catch (Exception e) { - System.err.println("Error fetching complaint types for compGroup " + compGroup + ": " + e.getMessage()); - } - - return complaintTypes; - } - - - - - - //for complaintgroup api - public List fetchComplaintGroup() { - String apiUrl = appconfig.qaqcurl+"serviceId=common_api&jsonResp=Yes&subService=compGrouplist"; - List complaintGroup = new ArrayList(); - - try { - // Call the external API - ResponseEntity response = restTemplate.getForEntity(apiUrl, String.class); - - if (response.getStatusCode() == HttpStatus.OK) { - // Parse the response JSON - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode rootNode = objectMapper.readTree(response.getBody()); - - // Navigate to "ListResult" and extract "COMPLAINTTYPENAME" - JsonNode listResultNode = rootNode.path("ListResult"); - if (listResultNode.isArray()) { - for (JsonNode item : listResultNode) { - String complaintTypeName = item.path("COMPLAINTGROUPNAME").asText().trim(); - complaintGroup.add(complaintTypeName); - } - } - } - } catch (Exception e) { - System.err.println("Error fetching complaint types: " + e.getMessage()); - } - - return complaintGroup; - } - - - - //for modes api - public List fetchModes() { - String apiUrl = appconfig.qaqcurl+"serviceId=common_api&jsonResp=Yes&subService=compModelist"; - List modes = new ArrayList(); - - try { - // Call the external API - ResponseEntity response = restTemplate.getForEntity(apiUrl, String.class); - - if (response.getStatusCode() == HttpStatus.OK) { - // Parse the response JSON - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode rootNode = objectMapper.readTree(response.getBody()); - - // Navigate to "ListResult" and extract "COMPLAINTTYPENAME" - JsonNode listResultNode = rootNode.path("ListResult"); - if (listResultNode.isArray()) { - for (JsonNode item : listResultNode) { - String complaintModeName = item.path("COMP_MODE").asText().trim(); - modes.add(complaintModeName); - } - } - } - } catch (Exception e) { - System.err.println("Error fetching complaint types: " + e.getMessage()); - } - - return modes; - } - - - // for zones api - public List fetchZones() { - String apiUrl = appconfig.qaqcurl+"serviceId=common_api&jsonResp=Yes&subService=zoneNamelist"; - List zones = new ArrayList(); - - try { - // Call the external API - ResponseEntity response = restTemplate.getForEntity(apiUrl, String.class); - - if (response.getStatusCode() == HttpStatus.OK) { - // Parse the response JSON - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode rootNode = objectMapper.readTree(response.getBody()); - - // Navigate to "ListResult" and extract "COMPLAINTTYPENAME" - JsonNode listResultNode = rootNode.path("ListResult"); - if (listResultNode.isArray()) { - for (JsonNode item : listResultNode) { - String complaintzone = item.path("NAME").asText().trim(); - zones.add(complaintzone); - } - } - } - } catch (Exception e) { - System.err.println("Error fetching complaint types: " + e.getMessage()); - } - - return zones; - } - - - - -} - - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/WhatsappqaqcMsgService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/WhatsappqaqcMsgService.java deleted file mode 100644 index 28b73925..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/WhatsappqaqcMsgService.java +++ /dev/null @@ -1,271 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.callcenterqaqc.service; - -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -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.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class WhatsappqaqcMsgService { - - private final RestTemplate restTemplate; - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private SocialMediaService socialMediaService; - - @Autowired - private QaqcCallsService qaqcCallsService; - - - @Autowired - public void setDataSource(@Qualifier("mysql1913QAQCDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public WhatsappqaqcMsgService(RestTemplate restTemplate) { - this.restTemplate=restTemplate; - } - - public String sendMsg(String msgUrl, String tamilmsgUrl) { - StringBuilder response = new StringBuilder(); - - - response.append("English Message Response: ").append(sendWhatsAppMessage(msgUrl)).append("\n"); - - - response.append("Tamil Message Response: ").append(sendWhatsAppMessage(tamilmsgUrl)); - - return response.toString(); - } - - private String sendWhatsAppMessage(String urlString) { - String response = ""; - try { - URL url = new URL(urlString); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = String.valueOf(responseCode); - System.out.println("Response Code for URL: " + urlString + " is " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - return response; - } - - - - public String sendSMS(String SMS_Url) { - RestTemplate restTemplate = new RestTemplate(); - String response =restTemplate.getForObject(SMS_Url,String.class); - return response; - } - - public Map checkforwhatsappmsg(String complaintNumber, String action) { - - Map response = new HashMap<>(); - - boolean result = false; - - if ("COMPLETED".equalsIgnoreCase(action)) { - - String sql = - "SELECT call_status " + - "FROM qaqc_upload_data_history " + - "WHERE complaint_number=? AND call_category='CLOSED' " + - "ORDER BY id DESC " + - "LIMIT 20"; - - List statuses = - jdbcTemplate.queryForList( - sql, - String.class, - complaintNumber); - - if (!statuses.isEmpty() - && "COMPLETED".equalsIgnoreCase(statuses.get(0))) { - - int unattendedCount = 0; - - for (int i = 1; i < statuses.size(); i++) { - - if ("UNATTENDED".equalsIgnoreCase(statuses.get(i))) { - unattendedCount++; - } else { - break; - } - } - - result = unattendedCount >= 5; - } - } - - else if ("UNATTENDED".equalsIgnoreCase(action)) { - - String sql = - "SELECT call_status " + - "FROM qaqc_upload_data_history " + - "WHERE complaint_number=? AND call_category='CLOSED' " + - "ORDER BY id DESC " + - "LIMIT 5"; - - List statuses = - jdbcTemplate.queryForList( - sql, - String.class, - complaintNumber); - - int unattendedCount = 0; - - for (String status : statuses) { - - if ("UNATTENDED".equalsIgnoreCase(status)) { - unattendedCount++; - } else { - break; - } - } - - result = unattendedCount >= 3; - } - - response.put("action", action); - response.put("status", result); - - return response; - } - - - public String getErpusername() { - - String query="SELECT erp_username FROM agents_list " - + "where calling_type='WHATSAPP_MSG'"; - - return jdbcTemplate.queryForObject(query,String.class); - } - - public String getclosefromuser(String complaintNumber) { - - try { - - Map complaintDetails =socialMediaService.getDetailsByComplaintNumber(complaintNumber); - String currentStatus = - String.valueOf( - complaintDetails.getOrDefault( - "currentStatus", - "" - ) - ); - - - - String Erpname=getErpusername(); - - System.out.println("Erpname="+Erpname); - - if ("Action Taken - Level 2".equalsIgnoreCase(currentStatus)) { - - boolean statusUpdated=qaqcCallsService.ChangeStatusInErp(complaintNumber, "COMPLAINT CLOSED BY WHATSAPP MESSAGE", "COMPLETED",Erpname); - if (statusUpdated) - { - return "Your "+complaintNumber+ " PGR Complaint has been closed Successfully.\n If you need further assistance,\n Please contact GCC 1913 Helpline."; - } - else { - return "We are unable to process your request at the moment.\n Please try again later."; - } - } - else { - if("FINAL_CLOSURE".equalsIgnoreCase(currentStatus)){ - - return "Your " + complaintNumber + " complaint has already been closed.\n\n" - + "If you need further assistance, please contact GCC 1913 Helpline."; - - } - else if("REOPENED".equalsIgnoreCase(currentStatus)) { - return "Your "+complaintNumber+" complaint has already been reopened. Once it is resolved, we will reach you by GCC’s 1913 helpline. If you need further assistance, please contact GCC 1913 Helpline."; - } - else { - return "Your "+complaintNumber+" complaint is Under Progress.\n Once it is resolved, \n we will reach you by GCC’s 1913 helpline."; - } - } - - - } catch (Exception e) { - e.printStackTrace(); - return "We are unable to process your request at the moment.\n Please try again later."; - } - - - } - - - public String getreopenfromuser(String complaintNumber) { - - try { - - Map complaintDetails =socialMediaService.getDetailsByComplaintNumber(complaintNumber); - String currentStatus = - String.valueOf( - complaintDetails.getOrDefault( - "currentStatus", - "" - ) - ); - - String Erpname=getErpusername(); - - System.out.println("Erpname="+Erpname); - - if ("Action Taken - Level 2".equalsIgnoreCase(currentStatus)) { - - boolean statusUpdated=qaqcCallsService.ChangeStatusInErp(complaintNumber, "COMPLAINT REOPENED BY WHATSAPP MESSAGE", "REOPEN",Erpname); - if (statusUpdated) - { - return "Your "+complaintNumber+ " PGR complaint has been reopened Successfully.\n Once it is resolved , we will reach you by GCC’s 1913 helpline.If you need further assistance , please contact GCC 1913 Helpline."; - } - else { - return "We are unable to process your request at the moment.\n Please try again later."; - } - } - else { - - if("FINAL_CLOSURE".equalsIgnoreCase(currentStatus)){ - - return "Your " + complaintNumber + " complaint has already been closed.\n\n" - + "If you need further assistance, please contact GCC 1913 Helpline."; - } - else if("REOPENED".equalsIgnoreCase(currentStatus)) { - return "Your "+complaintNumber+" complaint has already been reopened. Once it is resolved, we will reach you by GCC’s 1913 helpline. If you have any further assistance, please contact GCC 1913 Helpline."; - } - else { - return "Your "+complaintNumber+" complaint is Under Progress.\n Once it is resolved, \n we will reach you by GCC’s 1913 helpline."; - } - } - - - } catch (Exception e) { - e.printStackTrace(); - return "We are unable to process your request at the moment.\n Please try again later."; - } - - - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/DumpRegistrationAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/DumpRegistrationAPIController.java deleted file mode 100644 index cd42e598..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/DumpRegistrationAPIController.java +++ /dev/null @@ -1,174 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwaste.controller; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.cdwaste.service.OfficerService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - - -@RestController -@RequestMapping("/gcc/api/dumpregistration") -public class DumpRegistrationAPIController { - - - @Autowired - private OfficerService officerService; - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public DumpRegistrationAPIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - - - @GetMapping("/wastecollectorlist") - public ResponseEntity getWasteCollectorList( - @RequestParam(required = false) Long mobileNo, - @RequestParam(required = false) Long refId) { - - StringBuilder apiUrl = new StringBuilder(appConfig.dumpregister + "/dumpregistration/api/wastecollectorlist"); - - // If at least one param is present, append '?' - if (mobileNo != null || refId != null) { - apiUrl.append("?"); - } - - // Append parameters - List params = new ArrayList<>(); - if (mobileNo != null) { - params.add("mobileNo=" + mobileNo); - } - if (refId != null) { - params.add("refId=" + refId); - } - - apiUrl.append(String.join("&", params)); - - try { - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl.toString(), String.class); - return ResponseEntity.ok(responseEntity.getBody()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to fetch data: " + e.getMessage()); - } - } - - @GetMapping("/getallcharges") - public ResponseEntity getpaymentcharges() { - String apiUrl = appConfig.dumpregister + "/dumpregistration/dropdown/api/getallcharges"; - - try { - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return ResponseEntity.ok(responseEntity.getBody()); // Return the real response, not a fixed string - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to fetch data: " + e.getMessage()); - } - } - - - - @PostMapping("/saveWasteRequest") - public ResponseEntity saveWasteRequest(@RequestBody Map payload) { - try { - officerService.saveRequestDetails(payload); - return ResponseEntity.ok("Saved successfully"); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error saving request"); - } - } - - - - - @GetMapping("/getless1tonlist") - public ResponseEntity getWasteCollectorLess1TonList() { - StringBuilder apiUrl = new StringBuilder(appConfig.dumpregister + "/dumpregistration/api/getless1tonlist"); - - try { - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl.toString(), String.class); - return ResponseEntity.ok(responseEntity.getBody()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to fetch data: " + e.getMessage()); - } - } - - @GetMapping("/getless1tonlistbyId") - public ResponseEntity getWasteCollectorLess1TonListbyId(@RequestParam(required = true) Long refId) { - if (refId == null) { - return ResponseEntity.badRequest().body("refId is required"); - } - - try { - String apiUrl = appConfig.dumpregister + "/dumpregistration/api/getless1tonlistbyid?refId=" + refId; - - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return ResponseEntity.ok(responseEntity.getBody()); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to fetch data: " + e.getMessage()); - } - } - - - - @GetMapping("/getAllDetails") - public ResponseEntity getAllRequestDetails( - @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, - @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate, - @RequestParam(required = false) String wastequantity, - @RequestParam(required = false) String zone) { - try { - - List> response = officerService.getAllRequestDetails(fromDate, toDate, wastequantity, zone); - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to fetch data: " + e.getMessage())); - } - } - - - @GetMapping("/getquantity") - public List> getwastequantity() { - return officerService.getAllwastequantity(); - } - -//fetch all zones - - @GetMapping("/getzones") - public ResponseEntity getAllZones() { - try { - List> response = officerService.getZonesList(); - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to fetch data: " + e.getMessage())); - } - } - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/MainController.java deleted file mode 100644 index e0863767..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/MainController.java +++ /dev/null @@ -1,75 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwaste.controller; - - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; - - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/dumpregistration") -@Controller("dumpregistrationMainController") -public class MainController { - - private final LoginUserInfo loginUserInfo; - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate,LoginUserInfo loginUserInfo, - AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - this.loginUserInfo = loginUserInfo; - } - - @GetMapping("/officer") - public String viewOfficer(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - - return "modules/cdwastecollect/officer"; - } - - - - @GetMapping("/lessthanoneton") - public String viewLessoneTonList(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/cdwastecollect/lessoneton"; - } - - - @GetMapping("/overallreport") - public String wasteCollectionReports(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - return "modules/cdwastecollect/reports"; - } - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/OfficerService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/OfficerService.java deleted file mode 100644 index 60dcb54a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/OfficerService.java +++ /dev/null @@ -1,195 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwaste.service; - -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -@Service -public class OfficerService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private RestTemplate restTemplate; - - @Autowired - private SMSService smsService; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysqlCDManagerSystemDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - - @Transactional - public void saveRequestDetails(Map payload) { - double actualWeight = Double.parseDouble(payload.get("actualWeight").toString()); - String paymentType = payload.get("paymentType").toString(); - /* - * double processingCharge = - * Double.parseDouble(payload.get("processingCharge").toString()); double - * wasteCharge = Double.parseDouble(payload.get("wasteCharge").toString()); - */ - - double processingCharge = payload.get("processingCharge") != null - ? Double.parseDouble(payload.get("processingCharge").toString()) - : 0.0; - - double wasteCharge = payload.get("wasteCharge") != null - ? Double.parseDouble(payload.get("wasteCharge").toString()) - : 0.0; - double totalCharge = Double.parseDouble(payload.get("totalCharge").toString()); - String paymentMobNo = payload.get("paymentMobileNo") != null ? payload.get("paymentMobileNo").toString() : null; - String refId = payload.get("refId") != null ? payload.get("refId").toString() : null; - - // ✅ Check if record exists - String checkSql = "SELECT COUNT(*) FROM waste_collectors_request WHERE refid = ?"; - Integer count = jdbcTemplate.queryForObject(checkSql, new Object[]{refId}, Integer.class); - - if (count != null && count > 0) { - // ✅ Update the existing record - String updateSql = "UPDATE waste_collectors_request SET actual_weight = ?, payment_type = ?, processing_charge = ?, waste_collection_charge = ?, total_charge = ?, payment_mobile_no = ? WHERE refid = ?"; - jdbcTemplate.update(updateSql, actualWeight, paymentType, processingCharge, wasteCharge, totalCharge, paymentMobNo, refId); - - // ✅ Send WhatsApp message if payment type is 'generateLink' and mobile number is provided - if ("generateLink".equalsIgnoreCase(paymentType) && paymentMobNo != null && !paymentMobNo.isBlank()) { - sendWhatsappMessage(refId, actualWeight, totalCharge, paymentMobNo); - } - } else { - throw new RuntimeException("No request found for Ref ID: " + refId); - } - } - - - -// public void sendWhatsappMessage(String refId, double actualWeight, double totalCharge, String mobileNumber) { -// try { -// String message = String.format( -// "Your request (Request ID: *%s*) has been processed. Please proceed with the payment.\n\nActual Weight: *%.0f kg*\nAmount Payable: *%.0f*", -// refId, actualWeight, totalCharge -// ); -// -// String encodedMessage = URLEncoder.encode(message, StandardCharsets.UTF_8); -// String encodedHeader = URLEncoder.encode("C&D Waste Collection – Payment Request", StandardCharsets.UTF_8); -// String encodedFooter = URLEncoder.encode("Greater Chennai Corporation", StandardCharsets.UTF_8); -// -// String redirectUrlParam = URLEncoder.encode("dumpregistration/paymentform?requestId=" + refId, StandardCharsets.UTF_8); -// -// String apiUrl = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507" + -// "&password=h2YjFNcJ" + -// "&send_to=" + mobileNumber + -// "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE" + -// "&msg=" + encodedMessage + -// "&isTemplate=true" + -// "&header=" + encodedHeader + -// "&footer=" + encodedFooter + -// "&buttonUrlParam=" + redirectUrlParam; -// -// // Optional: log URL before hitting for debugging -// System.out.println("WhatsApp API URL: " + apiUrl); -// -// // Make API call -// // restTemplate.getForObject(apiUrl, String.class); -// smsService.sendMsg(apiUrl); -// } catch (Exception e) { -// e.printStackTrace(); -// // Optionally log or alert failure -// } -// } - - - public void sendWhatsappMessage(String refId, double actualWeight, double totalCharge, String mobileNumber) { - try { - - String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd"; - String from = "919445061913"; - String placeholders = ""; - String button_placeholder=""; - -// String apiUrl ="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+mobileNumber+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Thank+you%21+Your+request+has+been+successfully+submitted.%0ARequest+Id+%3A+"+refId+"&isTemplate=true&header=C%26D+Waste+Collection+Request+Registered&footer=Greater+Chennai+Corporation"; - -// placeholders = URLEncoder.encode(refId, "UTF-8"); - - placeholders = URLEncoder.encode(refId + "|~|" + actualWeight + "|~|" + totalCharge, "UTF-8"); - - button_placeholder=URLEncoder.encode(refId, "UTF-8"); - - String whatsappMsg = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=" + apikey + "&from=" - + from + "&to=91" + mobileNumber + "" - + "&type=template&templateid=3037264&placeholders=" + placeholders + "" - + "&button_placeholder=dumpregistration/paymentform?requestId=" +button_placeholder + "" ; - - - - System.out.println("WhatsApp API URL: " + whatsappMsg); - smsService.sendMsg(whatsappMsg); - - - }catch (Exception e) { - - e.printStackTrace(); - } - } - - - public List> getAllRequestDetails(LocalDate fromDate, LocalDate toDate, String wastequantity, String zone) { - StringBuilder query = new StringBuilder( - "SELECT wcr.id, wcr.name, wcr.mobile_no, wcr.area, wcr.zone, qm.quantity, " + - "wtm.waste_type, dl.location, wcr.actual_weight, wcr.payment_status,wcr.waste_collection_charge, " + - "wcr.processing_charge, wcr.total_charge, DATE_FORMAT(wcr.cdate, '%d-%m-%Y') AS request_date, wcr.refid " + - "FROM waste_collectors_request wcr " + - "JOIN dumping_location dl ON wcr.dump_location_id = dl.id " + - "JOIN waste_type_master wtm ON wcr.waste_type_id = wtm.id " + - "JOIN quantity_master qm ON wcr.waste_quantity_id = qm.id " + - "WHERE wcr.cdate BETWEEN ? AND ?"); - - LocalDateTime fromDateTime = fromDate.atStartOfDay(); - LocalDateTime toDateTime = toDate.atTime(LocalTime.MAX); - - List params = new ArrayList<>(); - params.add(fromDateTime); - params.add(toDateTime); - - if (wastequantity != null && !wastequantity.isEmpty()) { - query.append(" AND qm.quantity = ?"); - params.add(wastequantity); - } - - if (zone != null && !zone.isEmpty()) { - query.append(" AND wcr.zone = ?"); - params.add(zone); - } - - return jdbcTemplate.queryForList(query.toString(), params.toArray()); - } - - - - - public List> getAllwastequantity() { - String sql = " SELECT id,quantity FROM quantity_master where is_active = 1 "; - return jdbcTemplate.queryForList(sql); - } - - - public List> getZonesList() { - String sql = " SELECT id,zone_name from zones where is_active = 1 "; - return jdbcTemplate.queryForList(sql); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/SMSService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/SMSService.java deleted file mode 100644 index a7e5a136..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/SMSService.java +++ /dev/null @@ -1,40 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwaste.service; - - -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import java.net.HttpURLConnection; -import java.net.URL; - -@Service -public class SMSService { - public String sendMsg(String msgUrl) { - System.out.println("Whatsapp URL :-"+msgUrl); - - String response =""; - try{ - HttpURLConnection connection =null; - - URL url = new URL(msgUrl); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response=responseCode+""; - System.out.println("Response Code: " + responseCode); - - }catch (Exception e){ - e.printStackTrace(); - } - - return response; - } - - public String sendSMS(String SMS_Url) { - System.out.println("SMS URL:- "+ SMS_Url); - RestTemplate restTemplate = new RestTemplate(); - String response =restTemplate.getForObject(SMS_Url,String.class); - return response; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/.DS_Store deleted file mode 100644 index 09aadd77..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/ApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/ApiController.java deleted file mode 100644 index add48aa8..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/ApiController.java +++ /dev/null @@ -1,111 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.controller; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.core.env.Environment; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -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.client.RestTemplate; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.service.RegistrationService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -@RestController("cdapiController") -@RequestMapping("/gcc/api/registration") -public class ApiController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public ApiController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private Environment environment; - - @GetMapping("/pending") - public String getUserDetails(){ - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/getuserdetails"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - - @GetMapping("/pendingbyid") - public String getUserDetailsById(@RequestParam("registerId") Long registerId){ - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/getuserbyid"+"?registerId="+ registerId; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - - -// @PostMapping("/acceptbyid") -// public String acceptRegistration(@RequestParam("registerId") Long registerId) { -// // Your logic to accept the registration -// String apiUrl = appConfig.cdwastecollectors +"/volunteer/wastecollector/api/accept"+"?registerId="+ registerId; -// ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); -// return responseEntity.getBody(); -// } - - @PostMapping("/acceptbyid") - public ResponseEntity acceptRegistration(@RequestParam("registerId") Long registerId) { - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/accept?registerId=" + registerId; - ResponseEntity responseEntity = restTemplate.postForEntity(apiUrl, null, String.class); - return ResponseEntity.ok("Registration Accepted for ID: " + registerId); - } - - - - @PostMapping("/rejectbyid") - public ResponseEntity rejectRegistration( - @RequestParam("registerId") Long registerId, - @RequestParam("reason") String reason) { - - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/reject?registerId=" + registerId + "&reason=" + reason; - ResponseEntity responseEntity = restTemplate.postForEntity(apiUrl, null, String.class); - return ResponseEntity.ok("Registration Rejected for ID: " + registerId); - } - - @GetMapping("/approvallist") - public String getApprovalDetails(){ - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/approvedlist"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - - @GetMapping("/rejectedlist") - public String getRejectedDetails(){ - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/rejectedlist"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - - -} - - - - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/MainController.java deleted file mode 100644 index 7fe939d6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/MainController.java +++ /dev/null @@ -1,142 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.controller; - -import java.util.Collections; -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.service.RegistrationService; -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import org.springframework.http.MediaType; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - - - -@RequestMapping("/gcc/cdwaste") -@Controller("cdcontroller") -public class MainController { - - private final LoginUserInfo loginUserInfo; - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate,LoginUserInfo loginUserInfo, - AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - this.loginUserInfo = loginUserInfo; - } - - @Autowired - private RegistrationService registrationservice; - - @GetMapping("/registration") - public String SavecdRegistraion(Model model){ - return "modules/cdwaste/registration"; - } - - @GetMapping("/pending") - public String Pendinglist(Model model) throws JsonMappingException, JsonProcessingException { - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/getuserdetails"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - - // Get the response body - String responseBody = responseEntity.getBody(); - - ObjectMapper objectMapper = new ObjectMapper(); - - if (responseBody != null && !responseBody.isEmpty()) { - // Check if the response is an object or an array - if (responseBody.trim().startsWith("{")) { // Single object case - Map userDetails = objectMapper.readValue(responseBody, new TypeReference>() {}); - model.addAttribute("userDetails", List.of(userDetails)); // Convert to a list for consistency - } else { // It's expected to be an array - List> userDetails = objectMapper.readValue(responseBody, new TypeReference>>() {}); - model.addAttribute("userDetails", userDetails); // Add the list directly - } - } else { - // If response is null or empty, pass an empty list to the model - model.addAttribute("userDetails", Collections.emptyList()); - } - - return "modules/cdwaste/pending"; // Return the view - } - - - @GetMapping("/approval") - public String approvalList(Model model) throws JsonMappingException, JsonProcessingException { - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/approvedlist"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - - // Get the response body - String responseBody = responseEntity.getBody(); - - ObjectMapper objectMapper = new ObjectMapper(); - - if (responseBody != null && !responseBody.isEmpty()) { - // Check if the response is an object or an array - if (responseBody.trim().startsWith("{")) { // Single object case - Map approvalDetails = objectMapper.readValue(responseBody, new TypeReference>() {}); - model.addAttribute("approvalDetails", List.of(approvalDetails)); // Convert to list - } else { // It's an array - List> approvalDetails = objectMapper.readValue(responseBody, new TypeReference>>() {}); - model.addAttribute("approvalDetails", approvalDetails); - } - } else { - model.addAttribute("approvalDetails", Collections.emptyList()); - } - - return "modules/cdwaste/approval"; // Return the appropriate view - } - - @GetMapping("/rejected") - public String rejectedList(Model model) throws JsonMappingException, JsonProcessingException { - String apiUrl = appConfig.cdwastecollectors + "/volunteer/wastecollectors/api/rejectedlist"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - - // Get the response body - String responseBody = responseEntity.getBody(); - - ObjectMapper objectMapper = new ObjectMapper(); - - if (responseBody != null && !responseBody.isEmpty()) { - // Check if the response is an object or an array - if (responseBody.trim().startsWith("{")) { // Single object case - Map rejectedDetails = objectMapper.readValue(responseBody, new TypeReference>() {}); - model.addAttribute("rejectedDetails", List.of(rejectedDetails)); // Convert to list - } else { // It's an array - List> rejectedDetails = objectMapper.readValue(responseBody, new TypeReference>>() {}); - model.addAttribute("rejectedDetails", rejectedDetails); - } - } else { - model.addAttribute("rejectedDetails", Collections.emptyList()); - } - - return "modules/cdwaste/rejected"; // Return the appropriate view - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/WhatsappControllerCD.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/WhatsappControllerCD.java deleted file mode 100644 index e30b8123..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/controller/WhatsappControllerCD.java +++ /dev/null @@ -1,29 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.controller; - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.service.WhatsappMsgService; - - - -@RestController("whatsappconCD") -@RequestMapping("/gcc/api/cd/whatsapp") -public class WhatsappControllerCD { - - @Autowired - private WhatsappMsgService whatsappMsgService; - - @PostMapping("/send-whatsapp-message") - public ResponseEntity sendWhatsAppMessage(@RequestParam String msgUrl) { - String response = whatsappMsgService.sendMsg(msgUrl); - return ResponseEntity.ok(response); - } - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/service/RegistrationService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/service/RegistrationService.java deleted file mode 100644 index 19757276..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/service/RegistrationService.java +++ /dev/null @@ -1,33 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.service; - -import java.io.File; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -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.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -@Service -public class RegistrationService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - -} - - - - - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/service/WhatsappMsgService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/service/WhatsappMsgService.java deleted file mode 100644 index 38b82126..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/cdwastecollectorregistrations/service/WhatsappMsgService.java +++ /dev/null @@ -1,41 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.cdwastecollectorregistrations.service; - -import java.net.HttpURLConnection; - -import java.net.URL; - -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service("whatsappServiceCD") -public class WhatsappMsgService { - - - public String sendMsg(String msgUrl) { - - String response =""; - try{ - HttpURLConnection connection =null; - - URL url = new URL(msgUrl); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response=responseCode+""; - System.out.println("Response Code: " + responseCode); - - }catch (Exception e){ - e.printStackTrace(); - } - - return response; - } - - - public String sendSMS(String SMS_Url) { - RestTemplate restTemplate = new RestTemplate(); - String response =restTemplate.getForObject(SMS_Url,String.class); - return response; - } - } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Controller/ChildrenSurveyController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Controller/ChildrenSurveyController.java deleted file mode 100644 index bea12774..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Controller/ChildrenSurveyController.java +++ /dev/null @@ -1,428 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.childrensurvey.Controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.childrensurvey.Service.ChildrenSurveyService; - -@RestController -@RequestMapping("/gcc/api/children-survey") -public class ChildrenSurveyController { - - @Autowired - private ChildrenSurveyService service; - - @GetMapping("/gender") - public List> getGender() { - return service.getGender(); - } - - @GetMapping("/location") - public List> getLocation() { - return service.getLocation(); - } - - @GetMapping("/education") - public List> getEducation() { - return service.getEducation(); - } - - @GetMapping("/list") - public List> getSurveyList( - @RequestParam(required = false) String name, - @RequestParam(required = false) String gender, - @RequestParam(required = false) String age, - @RequestParam(required = false) String area, - @RequestParam(required = false) String education, - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate) { - return service.getSurveyList(name, gender, age, area, education, fromDate, toDate); - } - - @GetMapping("/details") - public Map getSurveyDetails( - @RequestParam String surveyId) { - return service.getSurveyDetails(surveyId); - } - - @GetMapping("/getSurveyorsList") - @ResponseBody - public List> getSurveyorsList( - - @RequestParam(required = false) String name, - @RequestParam(required = false) String area, - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate) { - - return service.getSurveyorsList( - name, - area, - fromDate, - toDate); - } - - @GetMapping("/survey-breakup") - @ResponseBody - public List> getSurveyBreakup( - - @RequestParam(required = false) String loginId, - @RequestParam(required = false) String locationId, - @RequestParam(required = false) String surveyDate) { - - return service.getSurveyBreakup(loginId, locationId, surveyDate); - } - - @GetMapping("/dashboard") - public Map dashboard() { - - return service.getDashboardData(); - } - - @GetMapping("/educationmasterlist") - public List> list() { - - return service.getEducationList(); - } - - @PostMapping("/save") - public String save( - @RequestBody Map req) { - - service.saveEducation(req); - - return "SUCCESS"; - } - - @PostMapping("/status") - public String updateStatus( - @RequestBody Map req) { - - service.updateStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/locationmasterlist") - public List> getLocationList() { - return service.getLocationList(); - } - - @PostMapping("/locationsave") - public String saveLocation( - @RequestBody Map req) { - - service.saveLocation(req); - - return "SUCCESS"; - } - - @PostMapping("/location-status") - public String updateLocationStatus( - @RequestBody Map req) { - - service.updateLocationStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/gendermasterlist") - public List> getGenderList() { - return service.getGenderList(); - } - - @PostMapping("/gendersave") - public String saveGender( - @RequestBody Map req) { - - service.saveGender(req); - - return "SUCCESS"; - } - - @PostMapping("/gender-status") - public String updateGenderStatus( - @RequestBody Map req) { - - service.updateGenderStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/castemasterlist") - public List> getCasteList() { - return service.getCasteList(); - } - - @PostMapping("/savecaste") - public String saveCaste( - @RequestBody Map req) { - - service.saveCaste(req); - - return "SUCCESS"; - } - - @PostMapping("/caste-status") - public String updateCasteStatus( - @RequestBody Map req) { - - service.updateCasteStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/livingmasterlist") - public List> getLivingList() { - return service.getLivingList(); - } - - @PostMapping("/livingsave") - public String saveLiving( - @RequestBody Map req) { - - service.saveLiving(req); - - return "SUCCESS"; - } - - @PostMapping("/living-status") - public String updateLivingStatus( - @RequestBody Map req) { - - service.updateLivingStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/documentcreationmasterlist") - public List> getDocumentCreationList() { - return service.getDocumentCreationList(); - } - - @PostMapping("/documentcreationsave") - public String saveDocumentCreation( - @RequestBody Map req) { - - service.saveDocumentCreation(req); - - return "SUCCESS"; - } - - @PostMapping("/documentcreationstatus") - public String updateDocumentCreationStatus( - @RequestBody Map req) { - - service.updateDocumentCreationStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/dropoutreasonmasterlist") - public List> getDropoutReasonList() { - return service.getDropoutReasonList(); - } - - @PostMapping("/dropoutreasonsave") - public String saveDropoutReason( - @RequestBody Map req) { - - service.saveDropoutReason(req); - - return "SUCCESS"; - } - - @PostMapping("/dropoutreasonstatus") - public String updateDropoutReasonStatus( - @RequestBody Map req) { - - service.updateDropoutReasonStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/incomemasterlist") - public List> getIncomeList() { - return service.getIncomeList(); - } - - @PostMapping("/incomesave") - public String saveIncome( - @RequestBody Map req) { - - service.saveIncome(req); - - return "SUCCESS"; - } - - @PostMapping("/incomemasterstatus") - public String updateIncomeStatus( - @RequestBody Map req) { - - service.updateIncomeStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/interestfieldmasterlist") - public List> getInterestFieldList() { - return service.getInterestFieldList(); - } - - @PostMapping("/interestfieldsave") - public String saveInterestField( - @RequestBody Map req) { - - service.saveInterestField(req); - - return "SUCCESS"; - } - - @PostMapping("/interestfieldmaster-status") - public String updateInterestFieldStatus( - @RequestBody Map req) { - - service.updateInterestFieldStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/ownermasterlist") - public List> getOwnerList() { - return service.getOwnerList(); - } - - @PostMapping("/ownermastersave") - public String saveOwner( - @RequestBody Map req) { - - service.saveOwner(req); - - return "SUCCESS"; - } - - @PostMapping("/ownermasterstatus") - public String updateOwnerStatus( - @RequestBody Map req) { - - service.updateOwnerStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/religionmasterlist") - public List> getReligionList() { - return service.getReligionList(); - } - - @PostMapping("/religionsave") - public String saveReligion( - @RequestBody Map req) { - - service.saveReligion(req); - - return "SUCCESS"; - } - - @PostMapping("/religion-status") - public String updateReligionStatus( - @RequestBody Map req) { - - service.updateReligionStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/vulnerabilitymasterlist") - public List> getVulnerabilityList() { - return service.getVulnerabilityList(); - } - - @PostMapping("/vulnerabilitysave") - public String saveVulnerability( - @RequestBody Map req) { - - service.saveVulnerability(req); - - return "SUCCESS"; - } - - @PostMapping("/vulnerabilitymasterstatus") - public String updateVulnerabilityStatus( - @RequestBody Map req) { - - service.updateVulnerabilityStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/whereaboutmasterlist") - public List> getWhereaboutList() { - return service.getWhereaboutList(); - } - - @PostMapping("/whereaboutsave") - public String saveWhereabout( - @RequestBody Map req) { - - service.saveWhereabout(req); - - return "SUCCESS"; - } - - @PostMapping("/whereaboutstatus") - public String updateWhereaboutStatus( - @RequestBody Map req) { - - service.updateWhereaboutStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/documentreasonmasterlist") - public List> getDocumentReasonList() { - return service.getDocumentReasonList(); - } - - @PostMapping("/documentreasonmaster") - public String saveDocumentReason( - @RequestBody Map req) { - - service.saveDocumentReason(req); - - return "SUCCESS"; - } - - @PostMapping("/documentreasonmasterstatus") - public String updateDocumentReasonStatus( - @RequestBody Map req) { - - service.updateDocumentReasonStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/nonsurveyed/list") - public ResponseEntity>> getNonSurveyedChildList( - - @RequestParam(required = false) String area, - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate) { - - return ResponseEntity.ok( - service.getNonSurveyedChildList( - area, - fromDate, - toDate)); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Controller/MainController.java deleted file mode 100644 index 74f8a2dc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Controller/MainController.java +++ /dev/null @@ -1,102 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.childrensurvey.Controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller("ChildrenSurveyController") -@RequestMapping("/gcc/childrensurvey") -public class MainController { - - @GetMapping("/surveylist") - public String surveylist() { - return "modules/childrensurvey/surveylist"; - } - - @GetMapping("/childlist/surveyedlist") - public String surveyedlist() { - return "modules/childrensurvey/childlist"; - } - - @GetMapping("/childlist/nonsurveyedlist") - public String nonsurveyedlist() { - return "modules/childrensurvey/nonchildlist"; - } - - @GetMapping("/surveyorsreports") - public String surveyorsreports() { - return "modules/childrensurvey/surveyorsreports"; - } - - @GetMapping("/mastersubmenu/educationmaster") - public String educationmaster() { - return "modules/childrensurvey/educationmaster"; - } - - @GetMapping("/mastersubmenu/locationmaster") - public String locationmaster() { - return "modules/childrensurvey/locationmaster"; - } - - @GetMapping("/mastersubmenu/gendermaster") - public String gendermaster() { - return "modules/childrensurvey/gendermaster"; - } - - @GetMapping("/mastersubmenu/castemaster") - public String castemaster() { - return "modules/childrensurvey/castemaster"; - } - - @GetMapping("/mastersubmenu/livingmaster") - public String livingmaster() { - return "modules/childrensurvey/livingmaster"; - } - - // documentation - @GetMapping("/mastersubmenu/documentcorrectionmaster") - public String documentcorrectionmaster() { - return "modules/childrensurvey/documentcorrectionmaster"; - } - - @GetMapping("/mastersubmenu/dropoutreasonmaster") - public String dropoutreasonmaster() { - return "modules/childrensurvey/dropoutreasonmaster"; - } - - @GetMapping("/mastersubmenu/incomemaster") - public String incomemaster() { - return "modules/childrensurvey/incomemaster"; - } - - @GetMapping("/mastersubmenu/religionmaster") - public String religionmaster() { - return "modules/childrensurvey/religionmaster"; - } - - @GetMapping("/mastersubmenu/interestfieldmaster") - public String interestfieldmaster() { - return "modules/childrensurvey/interestfieldmaster"; - } - - @GetMapping("/mastersubmenu/ownershipmaster") - public String ownermaster() { - return "modules/childrensurvey/ownermaster"; - } - - @GetMapping("/mastersubmenu/vulnerabilitymaster") - public String vulnerabilitymaster() { - return "modules/childrensurvey/vulnerabilitymaster"; - } - - @GetMapping("/mastersubmenu/whereaboutmaster") - public String whereaboutmaster() { - return "modules/childrensurvey/whereaboutmaster"; - } - - @GetMapping("/mastersubmenu/documentreasonmaster") - public String documentreasonmaster() { - return "modules/childrensurvey/documentreasonmaster"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Service/ChildrenSurveyService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Service/ChildrenSurveyService.java deleted file mode 100644 index 1b124f9b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/childrensurvey/Service/ChildrenSurveyService.java +++ /dev/null @@ -1,3411 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.childrensurvey.Service; - -import java.nio.file.Path; -import java.sql.PreparedStatement; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; -import java.nio.file.Files; -import javax.sql.DataSource; -import java.nio.file.Paths; -import java.awt.image.BufferedImage; -import javax.imageio.ImageIO; -import java.io.ByteArrayInputStream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -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.web.multipart.MultipartFile; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.stream.ImageOutputStream; -import java.sql.Statement; -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; -import in.gov.chennaicorporation.gccoffice.nulm.repository.NulmRepository; - -@Service -public class ChildrenSurveyService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlChildrenSurveyDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> getGender() { - - String sql = "SELECT id, english_name FROM gender_master"; - - return jdbcTemplate.queryForList(sql); - } - - public List> getLocation() { - return jdbcTemplate.queryForList( - "SELECT id, english_name FROM location_master"); - } - - public List> getEducation() { - return jdbcTemplate.queryForList( - "SELECT id, english_name FROM education_master"); - } - - public List> getSurveyList( - String name, - String gender, - String age, - String area, - String education, - String fromDate, - String toDate) { - System.out.println("name: " + name); - System.out.println("gender: " + gender); - System.out.println("age: " + age); - System.out.println("area: " + area); - System.out.println("education: " + education); - System.out.println("fromDate: " + fromDate); - System.out.println("toDate: " + toDate); - - StringBuilder sql = new StringBuilder(""" - SELECT - csr.survey_id, - - MAX(CASE WHEN cqm.field_name = 'q6' THEN csr.answer END) AS child_name, - MAX( - CASE - WHEN cqm.field_name = 'q7' - THEN CASE - WHEN csr.others_answer IS NOT NULL - AND TRIM(csr.others_answer) <> '' - THEN csr.others_answer - ELSE gm.english_name - END - END - ) AS gender, - - MAX(CASE WHEN cqm.field_name = 'q10' THEN csr.answer END) AS age, - MAX(CASE WHEN cqm.field_name = 'q24' THEN csr.answer END) AS mobile_number, - MAX(CASE WHEN cqm.field_name = 'q1' THEN lm.english_name END) AS area, - MAX(CASE WHEN cqm.field_name = 'q25' THEN em.english_name END) AS education, - MAX(csr.cby) AS cby, - DATE(MAX(csr.cdate)) AS survey_date - - FROM child_survey_response csr - - INNER JOIN child_survey_questions_master cqm - ON csr.qid = cqm.qid - - LEFT JOIN gender_master gm - ON gm.id = csr.answer AND cqm.field_name = 'q7' - - LEFT JOIN location_master lm - ON lm.id = csr.answer AND cqm.field_name = 'q1' - - LEFT JOIN education_master em - ON em.id = csr.answer AND cqm.field_name = 'q25' - - WHERE csr.isactive = 1 - AND csr.isdelete = 0 - """); - - List params = new ArrayList<>(); - // MAX(CASE WHEN cqm.field_name = 'q7' THEN gm.english_name END) AS gender, - - // 🔍 NAME - if (name != null && !name.isEmpty()) { - sql.append( - " AND csr.survey_id IN (SELECT survey_id FROM child_survey_response WHERE answer LIKE ?)"); - params.add("%" + name + "%"); - } - - // 🔍 GENDER - if (gender != null && !gender.isEmpty()) { - sql.append( - " AND csr.survey_id IN (SELECT survey_id FROM child_survey_response WHERE qid = 7 AND answer = ?)"); - params.add(gender); - } - - // 🔍 AREA - if (area != null && !area.isEmpty()) { - sql.append( - " AND csr.survey_id IN (SELECT survey_id FROM child_survey_response WHERE qid = 1 AND answer = ?)"); - params.add(area); - } - - // 🔍 EDUCATION - if (education != null && !education.isEmpty()) { - sql.append( - " AND csr.survey_id IN (SELECT survey_id FROM child_survey_response WHERE qid = 25 AND answer = ?)"); - params.add(education); - } - - // 🔍 AGE RANGE - if (age != null && !age.isEmpty()) { - - String[] range = age.split("-"); - - sql.append(""" - AND csr.survey_id IN ( - SELECT survey_id - FROM child_survey_response - WHERE qid = 10 - AND CAST(answer AS UNSIGNED) BETWEEN ? AND ? - ) - """); - - params.add(Integer.parseInt(range[0])); - params.add(Integer.parseInt(range[1])); - } - - // 🔍 DATE FILTER - if (fromDate != null && toDate != null && !fromDate.isEmpty() && !toDate.isEmpty()) { - sql.append(" AND DATE(csr.cdate) BETWEEN ? AND ?"); - params.add(fromDate); - params.add(toDate); - } - - sql.append(" GROUP BY csr.survey_id ORDER BY MAX(csr.cdate) DESC"); - // sql.append(" GROUP BY csr.survey_id ORDER BY csr.survey_id "); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - public Map getSurveyDetails(String surveyId) { - - String sql = """ - SELECT - csr.qid, - csr.answer, - csr.others_answer, - csr.cby, - csr.survey_id, - - cqm.q_english, - cqm.question_type, - cqm.master_table_name, - cqm.field_name, cqm.Flag - - - FROM child_survey_response csr - - INNER JOIN child_survey_questions_master cqm - ON csr.qid = cqm.qid - - WHERE csr.isactive = 1 - AND csr.isdelete = 0 - AND csr.survey_id = ? - - ORDER BY cqm.orderby - """; - - List> responseList = jdbcTemplate.queryForList(sql, surveyId); - - Map finalResponse = new LinkedHashMap<>(); - - Map personalInfo = new LinkedHashMap<>(); - Map locationInfo = new LinkedHashMap<>(); - Map educationInfo = new LinkedHashMap<>(); - Map documentInfo = new LinkedHashMap<>(); - Map healthInfo = new LinkedHashMap<>(); - Map vulnerabilityInfo = new LinkedHashMap<>(); - - for (Map row : responseList) { - - Integer qid = row.get("qid") != null - ? Integer.parseInt(row.get("qid").toString()) - : 0; - String flag = row.get("Flag") != null - ? row.get("Flag").toString() - : ""; - - String question = row.get("q_english") != null - ? row.get("q_english").toString() - : ""; - - String questionType = row.get("question_type") != null - ? row.get("question_type").toString() - : ""; - - String masterTable = row.get("master_table_name") != null - ? row.get("master_table_name").toString() - : ""; - - String rawAnswer = row.get("answer") != null - ? row.get("answer").toString() - : ""; - String othersAnswer = row.get("others_answer") != null - ? row.get("others_answer").toString().trim() - : ""; - - String finalAnswer = resolveAnswer( - qid, - questionType, - masterTable, - rawAnswer, - othersAnswer); - - // PERSONAL INFORMATION - /* - * if (qid >= 6 && qid <= 24) { - * - * personalInfo.put(question, finalAnswer); - * } - * - * // LOCATION DETAILS - * else if (qid >= 1 && qid <= 5) { - * - * locationInfo.put(question, finalAnswer); - * } - * - * // EDUCATION DETAILS - * else if (qid >= 25 && qid <= 38) { - * - * educationInfo.put(question, finalAnswer); - * } - * - * // HEALTH - * else if (qid >= 39 && qid <= 40) { - * - * healthInfo.put(question, finalAnswer); - * } - * - * // DOCUMENT - * else if (qid >= 41 && qid <= 47) { - * - * documentInfo.put(question, finalAnswer); - * } - * - * // VULNERABILITY - * else if (qid >= 48 && qid <= 52) { - * - * vulnerabilityInfo.put(question, finalAnswer); - * } - */ - if ("A".equalsIgnoreCase(flag)) { - - locationInfo.put(question, finalAnswer); - } - - // PERSONAL INFORMATION - else if ("P".equalsIgnoreCase(flag)) { - - personalInfo.put(question, finalAnswer); - } - - // EDUCATION DETAILS - else if ("E".equalsIgnoreCase(flag)) { - - educationInfo.put(question, finalAnswer); - } - - // HEALTH DETAILS - else if ("H".equalsIgnoreCase(flag)) { - - healthInfo.put(question, finalAnswer); - } - - // DOCUMENT DETAILS - else if ("D".equalsIgnoreCase(flag)) { - - documentInfo.put(question, finalAnswer); - } - - // VULNERABILITY DETAILS - else if ("V".equalsIgnoreCase(flag)) { - - vulnerabilityInfo.put(question, finalAnswer); - } - } - - finalResponse.put("locationDetails", locationInfo); - finalResponse.put("personalInformation", personalInfo); - finalResponse.put("educationDetails", educationInfo); - finalResponse.put("healthDetails", healthInfo); - finalResponse.put("documentDetails", documentInfo); - finalResponse.put("vulnerabilityDetails", vulnerabilityInfo); - - return finalResponse; - } - - private String resolveAnswer( - Integer qid, - String questionType, - String masterTable, - String rawAnswer, - String othersAnswer) { - - try { - - if (othersAnswer != null - && !othersAnswer.trim().isEmpty()) { - - return othersAnswer; - } - if (rawAnswer == null || rawAnswer.trim().isEmpty()) { - return ""; - } - - // TEXT TYPES - if ("text".equalsIgnoreCase(questionType) - || "textarea".equalsIgnoreCase(questionType) - || "number".equalsIgnoreCase(questionType) - || "number_text".equalsIgnoreCase(questionType) - || "number_mobile".equalsIgnoreCase(questionType) - || "number_aadhar".equalsIgnoreCase(questionType) - || "date".equalsIgnoreCase(questionType)) { - - return rawAnswer; - } - - boolean isNumeric = rawAnswer.matches("\\d+(,\\d+)*"); - - // RADIO - if ("radio".equalsIgnoreCase(questionType)) { - - if (!isNumeric) { - return rawAnswer; - } - - String sql = """ - SELECT english_name - FROM child_survey_answer_master - WHERE aid = ? - """; - - return jdbcTemplate.queryForObject( - sql, - String.class, - Integer.parseInt(rawAnswer)); - } - - // MULTICHECK - // ================= MULTICHECK ================= - if ("multicheck".equalsIgnoreCase(questionType)) { - - if (!isNumeric) { - return rawAnswer; - } - - String[] ids = rawAnswer.split(","); - - List values = new ArrayList<>(); - - // ====================================== - // FIRST CHECK child_survey_answer_master - // ====================================== - - String childSql = """ - SELECT english_name - FROM child_survey_answer_master - WHERE qid = ? - AND aid = ? - LIMIT 1 - """; - - // ====================================== - // MASTER TABLE SQL - // ====================================== - - String dynamicSql = null; - - if (masterTable != null && !masterTable.trim().isEmpty()) { - - dynamicSql = "SELECT english_name FROM " - + masterTable - + " WHERE id = ?"; - } - - for (String id : ids) { - - Integer answerId = Integer.parseInt(id.trim()); - - // CHECK child answer first - List> childResult = jdbcTemplate.queryForList( - childSql, - qid, - answerId); - - if (!childResult.isEmpty()) { - - values.add( - childResult.get(0) - .get("english_name") - .toString()); - - } else if (dynamicSql != null) { - - // CHECK MASTER TABLE - List> masterResult = jdbcTemplate.queryForList( - dynamicSql, - answerId); - - if (!masterResult.isEmpty()) { - - values.add( - masterResult.get(0) - .get("english_name") - .toString()); - } - } - } - - return String.join(", ", values); - } - // DROPDOWN - if ("dropdown".equalsIgnoreCase(questionType)) { - - if (!isNumeric) { - return rawAnswer; - } - - Integer answerId = Integer.parseInt(rawAnswer); - - // FIRST CHECK child_survey_answer_master - String childSql = """ - SELECT english_name - FROM child_survey_answer_master - WHERE qid = ? - AND aid = ? - LIMIT 1 - """; - - List> childResult = jdbcTemplate.queryForList( - childSql, - qid, - answerId); - - if (!childResult.isEmpty()) { - - return childResult.get(0) - .get("english_name") - .toString(); - } - - // MASTER TABLE CHECK - if (masterTable != null - && !masterTable.trim().isEmpty()) { - - String dynamicSql = "SELECT english_name FROM " - + masterTable - + " WHERE id = ?"; - - List> masterResult = jdbcTemplate.queryForList( - dynamicSql, - answerId); - - if (!masterResult.isEmpty()) { - - return masterResult.get(0) - .get("english_name") - .toString(); - } - } - } - - } catch (Exception e) { - - e.printStackTrace(); - } - - return rawAnswer; - } - - private String resolveAnswer1( - String questionType, - String masterTable, - String rawAnswer) { - - try { - - if (rawAnswer == null || rawAnswer.trim().isEmpty()) { - return ""; - } - - // DIRECT TEXT TYPES - if ("text".equalsIgnoreCase(questionType) - || "textarea".equalsIgnoreCase(questionType) - || "number".equalsIgnoreCase(questionType) - || "number_text".equalsIgnoreCase(questionType) - || "number_mobile".equalsIgnoreCase(questionType) - || "number_aadhar".equalsIgnoreCase(questionType) - || "date".equalsIgnoreCase(questionType)) { - - return rawAnswer; - } - - // CHECK WHETHER VALUE IS NUMERIC - boolean isNumeric = rawAnswer.matches("\\d+(,\\d+)*"); - - // RADIO - if ("radio".equalsIgnoreCase(questionType)) { - - // Already stored as text - if (!isNumeric) { - return rawAnswer; - } - - String sql = """ - SELECT english_name - FROM child_survey_answer_master - WHERE aid = ? - """; - - return jdbcTemplate.queryForObject( - sql, - String.class, - Integer.parseInt(rawAnswer)); - } - - // MULTICHECK - if ("multicheck".equalsIgnoreCase(questionType)) { - - // Already stored as text - if (!isNumeric) { - return rawAnswer; - } - - String[] ids = rawAnswer.split(","); - - List values = new ArrayList<>(); - - String sql = """ - SELECT english_name - FROM child_survey_answer_master - WHERE aid = ? - """; - - for (String id : ids) { - - String value = jdbcTemplate.queryForObject( - sql, - String.class, - Integer.parseInt(id.trim())); - - values.add(value); - } - - return String.join(", ", values); - } - - // DROPDOWN - if (masterTable != null - && !masterTable.isEmpty()) { - - // Already stored as text - if (!isNumeric) { - return rawAnswer; - } - - String dynamicSql = "SELECT english_name FROM " - + masterTable - + " WHERE id = ?"; - - return jdbcTemplate.queryForObject( - dynamicSql, - String.class, - Integer.parseInt(rawAnswer)); - } - - } catch (Exception e) { - - e.printStackTrace(); - } - - return rawAnswer; - } - - /* - * public Map getSurveyDetails(String surveyId) { - * - * String sql = """ - * SELECT - * csr.qid, - * csr.answer, - * csr.others_answer, - * csr.cby, - * csr.survey_id, - * - * cqm.q_english, - * cqm.question_type, - * cqm.master_table_name, - * cqm.field_name - * - * FROM child_survey_response csr - * - * INNER JOIN child_survey_questions_master cqm - * ON csr.qid = cqm.qid - * - * WHERE csr.isactive = 1 - * AND csr.isdelete = 0 - * AND csr.survey_id = ? - * - * ORDER BY cqm.orderby - * """; - * - * List> responseList = jdbcTemplate.queryForList(sql, - * surveyId); - * - * Map finalResponse = new LinkedHashMap<>(); - * - * for (Map row : responseList) { - * - * String question = row.get("q_english") != null - * ? row.get("q_english").toString() - * : ""; - * - * String questionType = row.get("question_type") != null - * ? row.get("question_type").toString() - * : ""; - * - * String masterTable = row.get("master_table_name") != null - * ? row.get("master_table_name").toString() - * : ""; - * - * String rawAnswer = row.get("answer") != null - * ? row.get("answer").toString() - * : ""; - * - * String finalAnswer = resolveAnswer( - * questionType, - * masterTable, - * rawAnswer); - * - * finalResponse.put(question, finalAnswer); - * } - * - * return finalResponse; - * } - */ - - // ========================================= - // ANSWER RESOLVER - // ========================================= - - /* - * private String resolveAnswer( - * String questionType, - * String masterTable, - * String rawAnswer) { - * - * try { - * - * if (rawAnswer == null || rawAnswer.isEmpty()) { - * return ""; - * } - * - * // TEXT - * if ("text".equalsIgnoreCase(questionType) - * || "textarea".equalsIgnoreCase(questionType) - * || "number".equalsIgnoreCase(questionType)) { - * - * return rawAnswer; - * } - * - * // RADIO - * if ("radio".equalsIgnoreCase(questionType)) { - * - * String sql = """ - * SELECT english_name - * FROM child_survey_answer_master - * WHERE aid = ? - * """; - * - * return jdbcTemplate.queryForObject( - * sql, - * String.class, - * Integer.parseInt(rawAnswer)); - * } - * - * // MULTICHECK - * if ("multicheck".equalsIgnoreCase(questionType)) { - * - * String[] ids = rawAnswer.split(","); - * - * List values = new ArrayList<>(); - * - * String sql = """ - * SELECT english_name - * FROM child_survey_answer_master - * WHERE aid = ? - * """; - * - * for (String id : ids) { - * - * String value = jdbcTemplate.queryForObject( - * sql, - * String.class, - * Integer.parseInt(id.trim())); - * - * values.add(value); - * } - * - * return String.join(", ", values); - * } - * - * // DROPDOWN - * if (masterTable != null - * && !masterTable.isEmpty()) { - * - * String dynamicSql = "SELECT english_name FROM " - * + masterTable - * + " WHERE id = ?"; - * - * return jdbcTemplate.queryForObject( - * dynamicSql, - * String.class, - * Integer.parseInt(rawAnswer)); - * } - * - * } catch (Exception e) { - * - * e.printStackTrace(); - * } - * - * return rawAnswer; - * } - */ - /* - * public List> getSurveyorsList( - * String name, - * String area, - * String fromDate, - * String toDate) { - * // ld.survey_id AS surveyor_id, - * StringBuilder sql = new StringBuilder(""" - * - * SELECT - * - * - * d.user_name, - * d.mobile_no, - * ld.loginId, - * lm.id as location_id, - * - * - * MAX(lm.english_name) AS area, - * - * COUNT(DISTINCT ld.survey_id) AS total_survey_done, - * - * DATE(MAX(sr.cdate)) AS survey_date - * - * FROM login_details d - * - * INNER JOIN surveyor_location_details ld - * ON d.uid = ld.loginId - * - * INNER JOIN child_survey_response sr - * ON sr.survey_id = ld.survey_id - * - * LEFT JOIN child_survey_response csr - * ON csr.survey_id = ld.survey_id - * AND csr.qid = 1 - * - * LEFT JOIN location_master lm - * ON lm.id = csr.answer - * - * WHERE sr.isactive = 1 - * AND sr.isdelete = 0 - * - * """); - * - * List params = new ArrayList<>(); - * - * // NAME FILTER - * if (name != null && !name.isEmpty()) { - * - * sql.append(""" - * AND d.user_name LIKE ? - * """); - * - * params.add("%" + name + "%"); - * } - * - * // AREA FILTER - * if (area != null && !area.isEmpty()) { - * - * sql.append(""" - * AND csr.answer = ? - * """); - * - * params.add(area); - * } - * - * // DATE FILTER - * if (fromDate != null - * && toDate != null - * && !fromDate.isEmpty() - * && !toDate.isEmpty()) { - * - * sql.append(""" - * AND DATE(sr.cdate) BETWEEN ? AND ? - * """); - * - * params.add(fromDate); - * params.add(toDate); - * } - * // ld.survey_id, - * sql.append(""" - * - * GROUP BY - * - * d.user_name, - * d.mobile_no, - * ld.loginId, - * lm.id - * - * ORDER BY - * MAX(sr.cdate) DESC - * - * """); - * - * return jdbcTemplate.queryForList( - * sql.toString(), - * params.toArray()); - * } - */ - public List> getSurveyorsList( - String name, - String area, - String fromDate, - String toDate) { - - StringBuilder sql = new StringBuilder(""" - - SELECT - - d.user_name, - d.mobile_no, - ld.loginId, - lm.id AS location_id, - - MAX(lm.english_name) AS area, - - COUNT(DISTINCT ld.survey_id) AS total_survey_done, - - DATE(sr.cdate) AS survey_date - - FROM login_details d - - INNER JOIN surveyor_location_details ld - ON d.uid = ld.loginId - - INNER JOIN ( - SELECT DISTINCT - survey_id, - DATE(cdate) AS cdate - FROM child_survey_response - WHERE isactive = 1 - AND isdelete = 0 - ) sr - ON sr.survey_id = ld.survey_id - - LEFT JOIN child_survey_response csr - ON csr.survey_id = ld.survey_id - AND csr.qid = 1 - - LEFT JOIN location_master lm - ON lm.id = csr.answer - - WHERE 1 = 1 - - - - """); - - List params = new ArrayList<>(); - - // NAME FILTER - if (name != null && !name.isEmpty()) { - - sql.append(""" - AND d.user_name LIKE ? - """); - - params.add("%" + name + "%"); - } - - // AREA FILTER - if (area != null && !area.isEmpty()) { - - sql.append(""" - AND csr.answer = ? - """); - - params.add(area); - } - - // DATE FILTER - if (fromDate != null - && toDate != null - && !fromDate.isEmpty() - && !toDate.isEmpty()) { - - sql.append(""" - AND DATE(sr.cdate) BETWEEN ? AND ? - """); - - params.add(fromDate); - params.add(toDate); - } - - sql.append(""" - - GROUP BY - - d.user_name, - d.mobile_no, - ld.loginId, - lm.id, - DATE(sr.cdate) - - ORDER BY - DATE(sr.cdate) DESC - - """); - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray()); - } - - public List> getSurveyBreakup(String loginId, String locationId, String surveyDate) { - System.out.println("......................................................."); - System.out.println(loginId + " " + locationId + " " + surveyDate); - System.out.println("......................................................."); - System.out.println("surveyDate=" + surveyDate); - System.out.println("locationId=" + locationId); - System.out.println("loginId=" + loginId); - String sql = """ - - SELECT - - sr.survey_id, - - MAX(CASE - WHEN cqm.field_name = 'q6' - THEN csr.answer - END) AS child_name, - MAX( - CASE - WHEN cqm.field_name = 'q7' - THEN CASE - WHEN csr.others_answer IS NOT NULL - AND TRIM(csr.others_answer) <> '' - THEN csr.others_answer - ELSE gm.english_name - END - END - ) AS gender, - - - - - MAX(CASE - WHEN cqm.field_name = 'q10' - THEN csr.answer - END) AS age, - - MAX(CASE - WHEN cqm.field_name = 'q24' - THEN csr.answer - END) AS mobile_number, - - MAX(CASE - WHEN cqm.field_name = 'q1' - THEN lm.english_name - END) AS area, - - MAX(CASE - WHEN cqm.field_name = 'q25' - THEN em.english_name - END) AS education, - - DATE(MAX(sr.cdate)) AS survey_date - - FROM surveyor_location_details sld - - INNER JOIN child_survey_response sr - ON sr.survey_id = sld.survey_id - - INNER JOIN child_survey_response csr - ON csr.survey_id = sr.survey_id - - INNER JOIN child_survey_questions_master cqm - ON cqm.qid = csr.qid - - LEFT JOIN gender_master gm - ON gm.id = csr.answer - AND cqm.field_name = 'q7' - - LEFT JOIN location_master lm - ON lm.id = csr.answer - AND cqm.field_name = 'q1' - - LEFT JOIN education_master em - ON em.id = csr.answer - AND cqm.field_name = 'q25' - - where sld.loginId = ? - AND sr.survey_id IN ( - - SELECT survey_id - FROM child_survey_response - WHERE qid = 1 - AND answer = ? - - - - ) - and DATE(sr.cdate) = ? - - - AND sr.isactive = 1 - AND sr.isdelete = 0 - - GROUP BY sr.survey_id - - ORDER BY MAX(sr.cdate) DESC - - """; - - return jdbcTemplate.queryForList(sql, loginId, locationId, surveyDate); - /* - * MAX(CASE - * WHEN cqm.field_name = 'q7' - * THEN gm.english_name - * END) AS gender, - */ - } - - // dashboard - - public Map getDashboardData() { - - Map response = new LinkedHashMap<>(); - - // TOTAL CHILDREN - - String totalSql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE isactive = 1 - AND isdelete = 0 - """; - - Integer totalChildren = jdbcTemplate.queryForObject(totalSql, Integer.class); - - response.put("totalChildren", totalChildren); - - // AREAS COVERED - - String areaCountSql = """ - SELECT COUNT(*) - FROM location_master - """; - - Integer areasCovered = jdbcTemplate.queryForObject(areaCountSql, Integer.class); - - response.put("areasCovered", areasCovered); - - // MALE - - String maleSql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 7 - AND answer = 1 - """; - - response.put( - "maleCount", - jdbcTemplate.queryForObject(maleSql, Integer.class)); - - // FEMALE - - String femaleSql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 7 - AND answer = 2 - """; - - response.put( - "femaleCount", - jdbcTemplate.queryForObject(femaleSql, Integer.class)); - - // OTHERS - - String othersSql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 7 - AND answer = 3 - """; - - response.put( - "othersCount", - jdbcTemplate.queryForObject(othersSql, Integer.class)); - - // CURRENTLY STUDYING - - /* - * String studyingSql = """ - * SELECT COUNT(DISTINCT survey_id) - * FROM child_survey_response - * WHERE qid = 25 - * AND answer = 1 - * """; - * - * response.put( - * "currentlyStudying", - * jdbcTemplate.queryForObject(studyingSql, Integer.class)); - */ - String studyingSql = """ - - SELECT - - ROUND( - ( - COUNT(DISTINCT CASE - WHEN qid = 25 - AND answer = 9 - THEN survey_id - END) - * 100.0 - ) - / - COUNT(DISTINCT survey_id), - 0) AS studying_percentage - - FROM child_survey_response - - WHERE isactive = 1 - AND isdelete = 0 - - """; - - response.put( - "currentlyStudying", - jdbcTemplate.queryForObject( - studyingSql, - Integer.class)); - - // AGE 4-8 - - String age4to8Sql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 10 - AND CAST(answer AS UNSIGNED) BETWEEN 4 AND 8 - """; - - response.put( - "age4to8", - jdbcTemplate.queryForObject(age4to8Sql, Integer.class)); - - // AGE 9-13 - - String age9to13Sql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 10 - AND CAST(answer AS UNSIGNED) BETWEEN 9 AND 13 - """; - - response.put( - "age9to13", - jdbcTemplate.queryForObject(age9to13Sql, Integer.class)); - - // AGE 14-18 - - String age14to18Sql = """ - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 10 - AND CAST(answer AS UNSIGNED) BETWEEN 14 AND 18 - """; - - response.put( - "age14to18", - jdbcTemplate.queryForObject(age14to18Sql, Integer.class)); - - // AREA WISE - - String areaWiseSql = """ - SELECT - - lm.english_name AS area, - - COUNT(DISTINCT csr.survey_id) AS total_children - - FROM location_master lm - - LEFT JOIN child_survey_response csr - ON lm.id = csr.answer - AND csr.qid = 1 - AND csr.isactive = 1 - AND csr.isdelete = 0 - - GROUP BY lm.id, lm.english_name - - ORDER BY lm.orderby - """; - - response.put( - "areaWise", - jdbcTemplate.queryForList(areaWiseSql)); - - // VULNERABILITY - - String vulnerabilitySql = """ - SELECT - - vm.english_name AS vulnerability, - - COUNT(DISTINCT csr.survey_id) AS total - - FROM vulnerability_master vm - - LEFT JOIN child_survey_response csr - ON FIND_IN_SET(vm.id, csr.answer) - AND csr.qid = 48 - AND csr.isactive = 1 - AND csr.isdelete = 0 - - GROUP BY vm.id, vm.english_name - - ORDER BY vm.orderby - """; - - response.put( - "vulnerability", - jdbcTemplate.queryForList(vulnerabilitySql)); - - // EDUCATION STATUS - - // EDUCATION STATUS - - String educationSql = """ - SELECT - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 25 - AND answer = 1 - AND isactive = 1 - AND isdelete = 0 - ) AS currently_studying, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 25 - AND answer = 2 - AND isactive = 1 - AND isdelete = 0 - ) AS not_studying, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 34 - AND answer = 1 - AND isactive = 1 - AND isdelete = 0 - ) AS continue_education_intent - """; - - response.put( - "educationStatus", - jdbcTemplate.queryForMap(educationSql)); - // HEALTH OVERVIEW - - String healthSql = """ - - SELECT - - CASE - - WHEN LOWER(cam.english_name) = 'yes' - THEN 'Health Issue' - - WHEN LOWER(cam.english_name) = 'no' - THEN 'No Health Issue' - - ELSE cam.english_name - - END AS status, - - COUNT(DISTINCT csr.survey_id) AS total - - FROM child_survey_response csr - - INNER JOIN child_survey_answer_master cam - ON cam.aid = csr.answer - AND csr.qid = 39 - - WHERE csr.qid = 39 - AND csr.isactive = 1 - AND csr.isdelete = 0 - - GROUP BY status - - """; - - response.put( - "healthOverview", - jdbcTemplate.queryForList(healthSql)); - - // CERTIFICATE DETAILS - - String certificateSql = """ - - SELECT - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 42 - AND answer = 1 - AND isactive = 1 - AND isdelete = 0 - ) AS aadhar_yes, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 42 - AND answer = 2 - AND isactive = 1 - AND isdelete = 0 - ) AS aadhar_no, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 44 - AND answer = 1 - AND isactive = 1 - AND isdelete = 0 - ) AS community_yes, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 44 - AND answer = 2 - AND isactive = 1 - AND isdelete = 0 - ) AS community_no, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 45 - AND answer = 1 - AND isactive = 1 - AND isdelete = 0 - ) AS birth_yes, - - ( - SELECT COUNT(DISTINCT survey_id) - FROM child_survey_response - WHERE qid = 45 - AND answer = 2 - AND isactive = 1 - AND isdelete = 0 - ) AS birth_no - - """; - - response.put( - "certificateDetails", - jdbcTemplate.queryForMap(certificateSql)); - - return response; - } - - public List> getEducationList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM education_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveEducation(Map req) { - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE education_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM education_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO education_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - - } - - public void saveEducation1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM education_master - """, - Integer.class); - - String sql = """ - INSERT INTO education_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE education_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getLocationList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM location_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveLocation(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE location_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM location_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO location_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveLocation1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM location_master - """, - Integer.class); - - String sql = """ - INSERT INTO location_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateLocationStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE location_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getGenderList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM gender_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveGender(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE gender_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM gender_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO gender_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - /* - * public void saveGender(Map req) { - * - * Integer nextOrder = jdbcTemplate.queryForObject( - * """ - * SELECT IFNULL(MAX(orderby),0) + 1 - * FROM gender_master - * """, - * Integer.class); - * - * String sql = """ - * INSERT INTO gender_master - * ( - * english_name, - * orderby, - * cdate, - * isactive, - * isdelete - * ) - * VALUES - * ( - * ?, - * ?, - * NOW(), - * 1, - * 0 - * ) - * """; - * - * jdbcTemplate.update( - * sql, - * req.get("english_name"), - * nextOrder); - * } - */ - - public void updateGenderStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE gender_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getCasteList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM caste_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveCaste(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE caste_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM caste_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO caste_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveCaste1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM caste_master - """, - Integer.class); - - String sql = """ - INSERT INTO caste_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateCasteStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE caste_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getLivingList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM child_living_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveLiving(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE child_living_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM child_living_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO child_living_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveLiving1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM child_living_master - """, - Integer.class); - - String sql = """ - INSERT INTO child_living_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateLivingStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE child_living_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDocumentCreationList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM document_correction_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDocumentCreation(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE document_correction_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM document_correction_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO document_correction_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveDocumentCreation1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM document_correction_master - """, - Integer.class); - - String sql = """ - INSERT INTO document_correction_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateDocumentCreationStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE document_correction_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDropoutReasonList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM dropout_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDropoutReason(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE dropout_reason_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM dropout_reason_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO dropout_reason_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveDropoutReason1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM dropout_reason_master - """, - Integer.class); - - String sql = """ - INSERT INTO dropout_reason_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateDropoutReasonStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE dropout_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getIncomeList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM income_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveIncome(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE income_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM income_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO income_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveIncome1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM income_master - """, - Integer.class); - - String sql = """ - INSERT INTO income_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateIncomeStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE income_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getInterestFieldList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM interest_field_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveInterestField(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE interest_field_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM interest_field_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO interest_field_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveInterestField1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM interest_field_master - """, - Integer.class); - - String sql = """ - INSERT INTO interest_field_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateInterestFieldStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE interest_field_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getOwnerList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM ownership_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveOwner(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE ownership_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM ownership_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO ownership_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveOwner1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM ownership_master - """, - Integer.class); - - String sql = """ - INSERT INTO ownership_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateOwnerStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE ownership_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getReligionList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM religion_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveReligion(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE religion_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM religion_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO religion_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveReligion1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM religion_master - """, - Integer.class); - - String sql = """ - INSERT INTO religion_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateReligionStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE religion_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getVulnerabilityList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM vulnerability_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveVulnerability(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE vulnerability_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM vulnerability_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO vulnerability_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveVulnerability1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM vulnerability_master - """, - Integer.class); - - String sql = """ - INSERT INTO vulnerability_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateVulnerabilityStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE vulnerability_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getWhereaboutList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM where_about_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveWhereabout(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE where_about_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM where_about_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO where_about_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveWhereabout1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM where_about_master - """, - Integer.class); - - String sql = """ - INSERT INTO where_about_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateWhereaboutStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE where_about_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDocumentReasonList() { - - String sql = """ - SELECT - id, - english_name, - isactive, - isdelete - FROM document_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDocumentReason(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - UPDATE document_reason_master - SET english_name = ? - WHERE id = ? - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM document_reason_master - """, - Integer.class); - - String insertSql = """ - INSERT INTO document_reason_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void saveDocumentReason1(Map req) { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - SELECT IFNULL(MAX(orderby),0) + 1 - FROM document_reason_master - """, - Integer.class); - - String sql = """ - INSERT INTO document_reason_master - ( - english_name, - orderby, - cdate, - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - NOW(), - 1, - 0 - ) - """; - - jdbcTemplate.update( - sql, - req.get("english_name"), - nextOrder); - } - - public void updateDocumentReasonStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - UPDATE document_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - // non surveyed child list - public List> getNonSurveyedChildList( - String area, - String fromDate, - String toDate) { - - StringBuilder sql = new StringBuilder(""" - - SELECT - - pr.survey_id, - - DATE(MAX(pr.cdate)) AS survey_date, - - MAX( - CASE - WHEN pm.qid = 1 - THEN psm.english_name - END - ) AS reason, - - MAX( - CASE - WHEN pm.qid = 2 - THEN lm.english_name - END - ) AS area, - - MAX( - CASE - WHEN pm.qid = 3 - THEN pr.answer - END - ) AS house_no, - - MAX( - CASE - WHEN pm.qid = 4 - THEN pr.answer - END - ) AS block_no - - FROM child_survey_participate_response pr - - INNER JOIN child_survey_participate_master pm - ON pm.qid = pr.qid - - LEFT JOIN participate_survey_master psm - ON pm.qid = 1 - AND psm.id = pr.answer - - LEFT JOIN location_master lm - ON pm.qid = 2 - AND lm.id = pr.answer - - WHERE pr.isactive = 1 - AND pr.isdelete = 0 - - """); - - List params = new ArrayList<>(); - - // AREA FILTER - if (area != null && !area.isEmpty()) { - - sql.append(""" - - AND ( - pr.survey_id IN ( - SELECT survey_id - FROM child_survey_participate_response - WHERE qid = 2 - AND answer = ? - ) - ) - - """); - - params.add(area); - } - - // DATE FILTER - if (fromDate != null - && toDate != null - && !fromDate.isEmpty() - && !toDate.isEmpty()) { - - sql.append(""" - - AND DATE(pr.cdate) BETWEEN ? AND ? - - """); - - params.add(fromDate); - params.add(toDate); - } - - sql.append(""" - - GROUP BY pr.survey_id - - ORDER BY MAX(pr.cdate) DESC - """); - // ORDER BY pr.survey_id - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray()); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/APIController.java deleted file mode 100644 index 667fdddb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/APIController.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.circular.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -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.gccoffice.circular.service.CircularMaster; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/circular") -@RestController("circularRest") // Circular Rest -public class APIController { - private CircularMaster circularMaster; - - @Autowired - public APIController(CircularMaster circularMaster) { - this.circularMaster = circularMaster; - } - - @GetMapping(value="/getCircularTypes") - public List getCircularTypeList() { - return circularMaster.getCircularType(); - } - - @GetMapping(value="/getDeprtmentList") - public List getDepartmentList() { - return circularMaster.getDepartment(); - } - - @GetMapping(value="/getCircularList") - public List getCircularList() { - return circularMaster.getCircular(); - } - - @PostMapping(value="/saveCircular") - public String savePetition( - @RequestParam("createdBy") String createdBy, - @RequestParam("doc_cat") String circularCategory, - @RequestParam("circularType") String circularType, - @RequestParam("department") String department, - @RequestParam("Date") String Date, - @RequestParam("subject") String subject, - @RequestParam("scan_page1") MultipartFile scan_file1) { - - return circularMaster.saveCircular(createdBy,circularCategory,circularType,department,Date,subject,scan_file1); - } - - @GetMapping(value="/getReport") - public List getReport() { - return circularMaster.getReport(); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/MainController.java deleted file mode 100644 index 7c9e6f64..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/MainController.java +++ /dev/null @@ -1,61 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.circular.controller; - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/circular") -@Controller("CircularController") -public class MainController { - private final RestTemplate restTemplate; - private Environment environment; - private String BasePath = "modules/circular/"; - - @Autowired - public MainController(RestTemplate restTemplate,Environment environment) { - this.restTemplate = restTemplate; - this.environment = environment; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"index"; - } - - @GetMapping({"/new"}) - public String newCircular(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_circular"; - } - - @GetMapping("/list") - public String inbox(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("cir_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - model.addAttribute("uploadDirectory",uploadDirectory); - return BasePath+"inbox"; - } - - @GetMapping("/report") - public String report(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"report"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/package-info.java deleted file mode 100644 index 0fc1a760..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.circular.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/circular/package-info.java deleted file mode 100644 index 03744e2e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.circular; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/service/CircularMaster.java b/src/main/java/in/gov/chennaicorporation/gccoffice/circular/service/CircularMaster.java deleted file mode 100644 index 8fb85464..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/service/CircularMaster.java +++ /dev/null @@ -1,223 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.circular.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.List; -import java.util.Map; - -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.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.m_petition.data.ComplaintType; - -@Service("CircularMaster") -public class CircularMaster { - private JdbcTemplate jdbcTemplate; - private Environment environment; - private JdbcTemplate appjdbcTemplate; - - @Autowired - public void setDataSource(Environment environment, - @Qualifier("mysqlCircularDataSource") DataSource dataSource, - @Qualifier("mysqlAppDataSource") DataSource appdataSource) { - this.environment = environment; - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.appjdbcTemplate = new JdbcTemplate(appdataSource); - } - - @Transactional(readOnly = true) - public List> getCircularType(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `circular_types` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional(readOnly = true) - public List> getDepartment(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `departments` WHERE `isactive`=1 AND `isdelete`=0 Order By name"; - - List> result = appjdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional(readOnly = true) - public List> getCircular(){ - String SqlQuery = ""; - - SqlQuery = "SELECT cd.*, cf.*, CASE WHEN cf.cid IS NOT NULL THEN 'true' ELSE 'false' END AS file_exits, gcc_apps.departments.name as department_name, circular_types.name as circular_type_name FROM circular_data cd LEFT JOIN circular_files cf ON cd.cid = cf.cid, gcc_apps.departments, circular_types where gcc_apps.departments.did=department AND circular_types.tid=circular_type ORDER BY cd.cid Desc"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional - public String saveCircular( - String createdBy, - String circularCategory, - String circularType, - String department, - String Date, - String subject, - MultipartFile scan_file1) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `circular_data` " - + "(`createdBy`,`category`, `circular_type`, `department`, " - + "`Date`, `subject`) " - + "VALUES (?, ?, ?, ?, ?, ?)"; - - try { - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, circularCategory); - ps.setString(3, circularType); - ps.setString(4, department); - ps.setString(5, Date); - ps.setString(6, subject); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - String lastInsertId_txt = String.valueOf(lastInsertId); - - // Add Petition Scan File in the database - addCircularFile(createdBy, lastInsertId, scan_file1); - - return lastInsertId_txt; // If no exception, query executed successfully - - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - String sqlQuery2 = "UPDATE `circular_data` SET `isactive`=0, `isdelete`=1 WHERE `cid`="+lastInsertId+" LIMIT 1"; - jdbcTemplate.update(sqlQuery2); - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public String addCircularFile(String createdBy, - int cid, - MultipartFile page1) { - - String fileName=""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("cir_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = cid + "_" + fileName + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `circular_files` ( `cid`, `created_by`, `file_name`, `file_size`, `file_type`) " - + "VALUES ('"+cid+"', '"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - @Transactional(readOnly = true) - public List> getReport(){ - String SqlQuery = ""; - String dynamic_query =""; - SqlQuery = "SELECT * FROM `circular_types` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `tid`"; - - List> circular_types_result = jdbcTemplate.queryForList(SqlQuery); - - for(Map type : circular_types_result) { - String typeId = type.get("tid").toString(); - String typeName = type.get("name").toString(); - dynamic_query += "SUM(CASE WHEN ct.tid = '" + typeId + "' THEN 1 ELSE 0 END) AS `dynamic_" + typeName + "`, "; - } - - // Remove the trailing comma and space from dynamic_query - dynamic_query = dynamic_query.substring(0, dynamic_query.length() - 2); - - // Construct the SQL query with the dynamic part - SqlQuery = "SELECT " - + " d.name, " - + "SUM(CASE WHEN ct.tid != '0' THEN 1 ELSE 0 END) as total, " - + dynamic_query + " " - + "FROM " - + "gcc_apps.departments d " - + "LEFT JOIN circular.circular_data cd ON cd.department = d.did " - + "LEFT JOIN circular.circular_types ct ON cd.circular_type = ct.tid " - + "GROUP BY d.name"; - System.out.println(SqlQuery); - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/circular/service/package-info.java deleted file mode 100644 index ca59e684..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/circular/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.circular.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/.DS_Store deleted file mode 100644 index e75b5443..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/APIController.java deleted file mode 100644 index 641e1a9a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/APIController.java +++ /dev/null @@ -1,219 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.controller; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.springframework.security.core.Authentication; - -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -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.gccoffice.com_petition.service.Petition; -import in.gov.chennaicorporation.gccoffice.com_petition.service.PetitionMaster; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/com_petition") -@RestController("commpRest") // Mayor Petition Rest -public class APIController { - private PetitionMaster petitionMaster; - private Petition petition; - - @Autowired - public APIController(PetitionMaster petitionMaster,Petition petition) { - this.petitionMaster = petitionMaster; - this.petition = petition; - } - - @GetMapping(value="/getComplaintTypes") - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @GetMapping(value="/getOfficerList") - public List getOfficerList() { - return petitionMaster.getOfficerList(); - } - - @GetMapping(value="/getPetitionTypes") - public List getPetitionTypes() { - return petitionMaster.getPetitionTypes(); - } - - @GetMapping(value="/getPetitionList") - public List getPetitionList() { - return petition.getPetitionList(); - } - - @GetMapping(value="/getUnmapPetitionList") - public List getUnmapPetitionList() { - return petition.getUnmapPetitionList(); - } - - @GetMapping(value="/getPetitionDetails") - public List getPetitionDetails(@RequestParam("petitionNo") String petitionNo) { - return petition.getPetitionDetails(petitionNo); - } - - @PostMapping(value="/savePetition") - public String savePetition( - @RequestParam("createdBy") String createdBy, - @RequestParam("petitionType") String petitionType, - @RequestParam("petitionerName") String petitionerName, - @RequestParam("petitionerMobile") String petitionerMobile, - @RequestParam("complaintType") String petitionerComplaint, - @RequestParam("san_page1") MultipartFile page1, - @RequestParam("san_page2") MultipartFile page2, - @RequestParam("san_page3") MultipartFile page3, - @RequestParam("san_page4") MultipartFile page4) { - - return petition.savePetition(petitionType, createdBy, petitionerName, petitionerMobile, petitionerComplaint, page1, page2, page3, page4); - } - - @PostMapping(value="/updatePetition") - public Boolean updatePetition( - @RequestParam("petitionType") String petitionType, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam("petitionerName") String petitionerName, - @RequestParam("petitionerMobile") String petitionerMobile, - @RequestParam("petitionerAddress") String petitionerAddress, - @RequestParam("petitionerPincode") String petitionerPincode, - @RequestParam("complaintType") String petitionerComplaint, - @RequestParam("complaintNature") String complaintNature, - @RequestParam("remarks") String remarks) { - - return petition.updatePetition(petitionNo, petitionType, createdBy, petitionerName, petitionerMobile, petitionerAddress, petitionerPincode, petitionerComplaint, complaintNature, remarks); - } - - @PostMapping(value="/mapComplientToOfficer") - public Boolean updatePetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String mapOfficers) { - - String com_mapping = mapOfficers; - - // First before Mapping need to unmaps old list - petition.unmapComplient(petitionId, petitionNo); - - if(com_mapping!=null) { - String[] com_mapping_parts = com_mapping.split(","); - for (String values : com_mapping_parts) { - String[] com_mapping_val = values.split("_"); - if (com_mapping_val.length > 0) { - String complientId = com_mapping_val[0]; - String offcierId = com_mapping_val[1]; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - } - } - } - return true; - } - - - @GetMapping(value="/getComplaintMappingDetails") - public List getComplaintMappingDetails( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("complaintTypeId") String complaintTypeId) { - return petition.getComplaintMappingDetails(petitionNo,petitionId,complaintTypeId); - } - - @GetMapping(value="/getComplaintList") - public List getComplaintList(@RequestParam("loginId") String loginId) { - return petition.getComplaintList(loginId); - } - - @GetMapping(value="/getComplaintListByPetitionId") - public List getComplaintListByPetitionId(@RequestParam("petitionId") String petitionId) { - return petition.getComplaintListByPetitionId(petitionId); - } - - @GetMapping(value="/getComplaintDetails") - public List getComplaintDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintDetails(mapId); - } - - @GetMapping(value="/getComplaintActionDetails") - public List getComplaintActionDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintActionDetails(mapId); - } - - @PostMapping(value="/saveComplanitStatus") - public String saveComplanitStatus( - @RequestParam("createdBy") String createdBy, - @RequestParam("mapId") String mapId, - @RequestParam("complaintStatus") String complaintStatus, - @RequestParam("complaintActionText") String complaintActionText, - @RequestParam("action_san_page1") MultipartFile actionPage1, - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo) { - - return petition.saveComplanitStatus(createdBy, mapId, complaintStatus, complaintActionText, actionPage1, petitionId, petitionNo); - } - - @PostMapping(value="/insertForwardLog") - public String insertForwardLog( - @RequestParam("offidto") String offidto, - @RequestParam("comments") String comments, - @RequestParam("mapid") String mapid) { - - // Get the petition details from the database - List> eventsPetitionMappingList = petition.getComplaintDetails(mapid); - - // Check if the list is not empty and contains only one item - if (!eventsPetitionMappingList.isEmpty()) { - if (eventsPetitionMappingList.size() == 1) { - // Get the first element from the list (it’s a Map) - Map petitionMapping = eventsPetitionMappingList.get(0); - - // Extract values from the map using the correct keys - String offId = ""+petitionMapping.get("off_id"); - String petitionNumber = ""+petitionMapping.get("petition_no"); - String petitionId = ""+petitionMapping.get("petition_id"); - String complaintTypeId = ""+petitionMapping.get("complaint_typeid"); - - String[] com_mapping_val = offidto.split("_"); - if (com_mapping_val.length > 0) { - String complientId = com_mapping_val[0]; - String offcierId = com_mapping_val[1]; - - // Insert the forward log with the extracted data - petition.insertForwardLog( - offId, - offcierId, - petitionNumber, - petitionId, - complaintTypeId, - mapid, - comments - ); - } - } - } - return "success"; // Return success when completed - } - - @GetMapping("/getReportList") - public List> getReportList( - @RequestParam(value = "fromDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate, - - @RequestParam(value = "toDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate, - - @RequestParam(value = "petitionType", required = false) String petitionType) { - - return petition.getReportList(fromDate, toDate, petitionType); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/MainController.java deleted file mode 100644 index 48be276c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/MainController.java +++ /dev/null @@ -1,137 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.controller; - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/com_petition") -@Controller("ComPetitionController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/com_petition/"; - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"index"; - } - - @GetMapping({"/new_petition"}) - public String newPetition(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_petition"; - } - - @GetMapping("/petition-ack/{petitionNo}") - public String petitionAck(Model model,@PathVariable("petitionNo") String petitionNo) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_ack"; - } - - @GetMapping("/petition-list") - public String petitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_list"; - } - - @GetMapping("/unmapped-petition-list") - public String unMappedPetitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_not_mapped_list"; - } - - @GetMapping("/update-petition") - public String petitionUpadte(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/view-petition") - public String petitionView(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view"; - } - - @GetMapping("/view-petition-modal") - public String petitionViewModal(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view_modal_page"; - } - - @GetMapping("/search-petition") - public String petitionSearch(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - //model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/complaint-list") - public String complaintList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"complaint_list"; - } - - @GetMapping("/report/list") - public String reportList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"pending_list"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/package-info.java deleted file mode 100644 index 86a3ebb3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/data/ComplaintType.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/data/ComplaintType.java deleted file mode 100644 index d81475cd..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/data/ComplaintType.java +++ /dev/null @@ -1,21 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.data; - -import java.util.Map; - -public class ComplaintType { - private int complaintTypeId; - private String complaintType; - - public ComplaintType(Map map) { - this.complaintTypeId = (int) map.get("complaint_typeid"); - this.complaintType = (String) map.get("complaint_type"); - } - - public int getComplaintTypeId() { - return complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/data/package-info.java deleted file mode 100644 index afa4a2a3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/package-info.java deleted file mode 100644 index f11e606f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ -/** - * - */ -package in.gov.chennaicorporation.gccoffice.com_petition; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/Petition.java deleted file mode 100644 index 8fb5a15a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/Petition.java +++ /dev/null @@ -1,812 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.transaction.annotation.Transactional; -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.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.com_petition.data.ComplaintType; -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.GetMappingUserDetails; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -@Service("commissionerPetition") -public class Petition { - private JdbcTemplate jdbcTemplate; - private final Environment environment; - private PetitionMaster petitionMaster; - private GetMappingUserDetails getMappingUserDetails; - - @Autowired - public Petition(Environment environment,PetitionMaster petitionMaster,GetMappingUserDetails getMappingUserDetails) { - this.environment = environment; - this.petitionMaster = petitionMaster; - this.getMappingUserDetails = getMappingUserDetails; - } - - - @Autowired - public void setDataSource(@Qualifier("mysqlCommissionerPetitionDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - /* - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - return complaintTypeMaps.stream() - .map(ComplaintType::new) - .collect(Collectors.toList()); - } - */ - - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - List complaintTypes = new ArrayList<>(); - for (Map complaintTypeMap : complaintTypeMaps) { - complaintTypes.add(new ComplaintType(complaintTypeMap)); - } - return complaintTypes; - } - - @Transactional(readOnly = true) - // Method to map complaint type IDs to their respective complaint types - public static String mapComplaintTypes(List complaintTypes, String complaint) { - String[] complaintIds = complaint.split(","); - StringBuilder complaintTxtBuilder = new StringBuilder(); - - for (String complaintId : complaintIds) { - int id = Integer.parseInt(complaintId); - for (ComplaintType type : complaintTypes) { - if (type.getComplaintTypeId() == id) { - if (complaintTxtBuilder.length() > 0) { - complaintTxtBuilder.append(","); - } - complaintTxtBuilder.append(type.getComplaintType()); - break; - } - } - } - - return complaintTxtBuilder.toString(); - } - - @Transactional(readOnly = true) - public List> getPetitionList() { - try { - //String sqlQuery = "SELECT * FROM petition WHERE (`isactive`=1 AND `isdelete`=0)"; - String sqlQuery = "SELECT p.* , pt.name petition_type_name FROM petition p, petition_master.petition_types pt " - + "WHERE (p.`isactive`=1 AND p.`isdelete`=0) AND p.petition_type = pt.petition_type_id"; - List> result = jdbcTemplate.queryForList(sqlQuery); - Base64Util.encodeBase64(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getUnmapPetitionList() { - try { - String sqlQuery = "SELECT " - + " p.* , pt.name petition_type_name " - + "FROM " - + " `petition` p, petition_master.petition_types pt " - + "WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) AND (p.petition_type = pt.petition_type_id)" - + " AND NOT EXISTS (" - + " SELECT 1 " - + " FROM `petition_mapping` pm " - + " WHERE (p.`petition_id` = pm.`petition_id`) AND (pm.`isactive` = 1 AND pm.`isdelete` = 0 ) " - + " )"; - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - - @Transactional(readOnly = true) - public List> getPetitionDetails(String petitionNo) { - try { - String sqlQuery = "SELECT * FROM petition WHERE petition_no = ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - //System.out.println("SELECT * FROM petition WHERE petition_no = '"+petitionNo+"' AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"); - List> result = jdbcTemplate.queryForList(sqlQuery, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String savePetition( - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerComplaint, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition` " - + "(`petition_type`,`created_by`, `petitioner_name`, `petitioner_mobile`, " - + "`petitioner_complaint`, `petitioner_complaint_txt`) " - + "VALUES (?, ?, ?, ?, ?, ?)"; - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, petitionType); - ps.setString(2, createdBy); - ps.setString(3, petitionerName); - ps.setString(4, petitionerMobile); - ps.setString(5, petitionerComplaint); - ps.setString(6, petitionerComplaint_txt); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - - // Get the value of mp_ackno from application.properties - String ackno = environment.getProperty("com_ackno"); - String ackno_prefix = environment.getProperty("com_ackno_prefix"); - - // Convert ackno to int if needed - int acknoInt = Integer.parseInt(ackno); - - // Calculate the petition number - int petitionNo = (int) (lastInsertId + acknoInt); - - // Construct the petition number string - String petitionNoString = ackno_prefix + petitionNo; - - // Update the petition number in the database - updatePetitionNumber(lastInsertId, petitionNoString); - - // Add Petition Scan File in the database - addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return petitionNoString; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionNumber(int petitionId,String petitionNoString) { - String sqlQuery = "UPDATE `petition` SET `petition_no`='"+petitionNoString+"' WHERE `petition_id`='"+petitionId+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String addPetitionFile(String createdBy, - int petitionId, - String petitionNoString, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - String fileName=""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - case 2: - file = page2; - fileName = "Scan2"; - break; - case 3: - file = page3; - fileName = "Scan3"; - break; - case 4: - file = page4; - fileName = "Scan4"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("com_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = petitionId + "_" + fileName + "_" + petitionNoString + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"','"+petitionNoString+"','"+petitionId+"')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - @Transactional - public boolean updatePetition( - String petitionNo, - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerAddress, - String petitionerPincode, - String petitionerComplaint, - String complaintNature, - String remarks) { - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - /* - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type`='"+petitionType+"', `created_by`='"+createdBy+"', `petitioner_name`='"+petitionerName+"', `petitioner_mobile`='"+petitionerMobile+"', " - + "`petitioner_address`='"+petitionerAddress+"', `petitioner_pincode`='"+petitionerPincode+"'," - + "`petitioner_complaint`='"+petitionerComplaint+"', `petitioner_complaint_txt`='"+petitionerComplaint_txt+"', `complaint_nature`='"+complaintNature+"', `remarks`='"+remarks+"' " - + "WHERE (`petition_no`='"+petitionNo+"') LIMIT 1"; - System.out.println(sqlQuery); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(sqlQuery);*/ - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type` = ?, `created_by` = ?, `petitioner_name` = ?, `petitioner_mobile` = ?, " - + "`petitioner_address` = ?, `petitioner_pincode` = ?, `petitioner_complaint` = ?, " - + "`petitioner_complaint_txt` = ?, `complaint_nature` = ?, `remarks` = ? " - + "WHERE `petition_no` = ? LIMIT 1"; - - int rowsUpdated = jdbcTemplate.update(sqlQuery, - petitionType, - createdBy, - petitionerName, - petitionerMobile, - petitionerAddress, - petitionerPincode, - petitionerComplaint, - petitionerComplaint_txt, // Safely includes single quotes - complaintNature, - remarks, - petitionNo - ); - - // Add Petition Scan File in the database - //addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return true; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return false; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionStatus(String petitionId,String petitionNo) { - String status_value = "close"; - List> petitionMappingDetails = getPetitionMappingDetails(petitionNo, petitionId); - - for (Map mapping : petitionMappingDetails) { - // Access values from the map using keys - Object status = mapping.get("status"); - // Check if status is "close" - if (!"close".equals(status)) { - status_value = "partial"; - } - - } - - String sqlQuery = "UPDATE `petition` SET `status`='"+status_value+"' WHERE `petition_no`='"+petitionNo+"' AND `petition_id`='"+petitionId+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails(String petitionNo, String petitionId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public boolean unmapComplient(String petitionId, String petitionNo) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `petition_id`='"+petitionId+"' AND `petition_no`='"+petitionNo+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public boolean mapComplientToOfficer( - String createdBy, String petitionId, String petitionNo, String complaintId, String officerId) { - String sqlQuery = "INSERT INTO `petition_mapping`" - + "(`created_by`, `off_id`, `petition_no`, `complaint_typeid`, `petition_id`) " - + "VALUES (?, ?, ?, ?, ?)"; - jdbcTemplate.update(sqlQuery, createdBy, officerId, petitionNo, complaintId, petitionId); - return true; - } - - @Transactional - public boolean updateMapComplientStatus(String mapId,String status) { - String sqlQuery = "UPDATE `petition_mapping` SET `status`=? WHERE `mapid`=? LIMIT 1"; - jdbcTemplate.update(sqlQuery, status, mapId); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getComplaintMappingDetails(String petitionNo, String petitionId, String complaintTypeId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND `complaint_typeid`= ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo,complaintTypeId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintList(String loginId) { - String sqlQuery = ""; - try { - sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `petition` p, `petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - - String officerMaster = getMappingUserDetails.getOfficerMaster(loginId); - - if (officerMaster != null && !officerMaster.isEmpty()) { - sqlQuery = sqlQuery + "AND (pm.off_id IN("+officerMaster+"))"; - } - - System.out.println(sqlQuery); - - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintListByPetitionId(String petitionId) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, p.`status` petition_status, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status` complaint_status, pm.`cdate` mappedOn, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `commissioner_petition`.`petition` p,`commissioner_petition`.`petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`petition_id` = '"+petitionId+"' AND p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintDetails(String mapid) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm`, ctype.`complaint_type`, " - + " COALESCE(pf.`mtm_pet_file_id`, 'No file available') AS mtm_pet_file_id, " - + " COALESCE(pf.`cdate`, '') AS file_cdate, " - + " COALESCE(pf.`created_by`, 'N/A') AS file_created_by, " - + " COALESCE(pf.`file_name`, 'No file available') AS file_name, " - + " COALESCE(pf.`file_size`, 0) AS file_size, " - + " COALESCE(pf.`file_type`, 'Unknown') AS file_type, " - + " COALESCE(pf.`isactive`, 0) AS file_isactive, " - + " COALESCE(pf.`isdelete`, 0) AS file_isdelete " - + " FROM " - + " `petition` p " - + " JOIN `petition_mapping` pm ON p.`petition_id` = pm.`petition_id` " - + " JOIN `petition_master`.`officer_master` om ON om.`off_id` = pm.`off_id` " - + " JOIN `petition_master`.`complaint_types` ctype ON ctype.`complaint_typeid` = pm.`complaint_typeid` " - + " LEFT JOIN `pentition_files` pf ON p.`petition_id` = pf.`petition_id` " - + " WHERE " - + " pm.`mapid` = '" + mapid + "' " - + " AND p.`isactive` = 1 AND p.`isdelete` = 0 " - + " AND pm.`isactive` = 1 AND pm.`isdelete` = 0 " - + " AND om.`isactive` = 1 AND om.`isdelete` = 0 "; - - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintActionDetails(String mapId) { - try { - String sqlQuery = "SELECT * FROM `petition_action_taken` WHERE (`mapid`= ? AND `isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, mapId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String saveComplanitStatus( - String createdBy, - String mapId, - String complaintStatus, - String complaintActionText, - MultipartFile actionPage1, - String petitionId, - String petitionNo) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition_action_taken` " - + "(`created_by`, `off_id`, `mapid`, `status`, " - + "`comments`) " - + "VALUES (?, ?, ?, ?, ?)"; - - try { - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, createdBy); - ps.setString(3, mapId); - ps.setString(4, complaintStatus); - ps.setString(5, complaintActionText); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int)keyHolder.getKey().longValue(); - String actionID = "error"; - if(lastInsertId>0) { - // Update Complaint Status - updateMapComplientStatus(mapId,"close"); - // Update Petition Status - updatePetitionStatus(petitionId,petitionNo); - // Add Action Scan File in the database - addActionFile(mapId,lastInsertId, actionPage1); - actionID = ""+lastInsertId; - } - - return actionID; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public String addActionFile( String mapId, int solmapid, - MultipartFile page1) { - - MultipartFile file = page1; - String fileName = "Scan1_"+solmapid; - - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("com_foldername"); - String serviceActionFolderName = environment.getProperty("com_action_Foldername"); - - uploadDirectory = uploadDirectory + serviceFolderName +"/"+ serviceActionFolderName; - - // File name - fileName = mapId + "_" + fileName + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "UPDATE `petition_action_taken` SET " - + "`file_name`='"+fileName+"', " - + "`file_size`='"+fileSize+"', " - + "`file_type`='"+fileType+"' " - + "WHERE `solmapid`='"+solmapid+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - return "success"; - } - - @Transactional - public String insertForwardLog( - String offId, - String offidto, - String petitionNumber, - String petitionId, - String complaintTypeId, - String mapid, - String comments) { - // Save the file path to a database - String sqlQuery = "INSERT INTO `petition_forward_log`(`off_id`, `off_id_to`, `petition_no`, `complaint_typeid`,`petition_id`,`mapid`,`comments`) " - + "VALUES ('"+offId+"','"+offidto+"','"+petitionNumber+"','"+complaintTypeId+"','"+petitionId+"','"+mapid+"','"+comments+"')"; - jdbcTemplate.update(sqlQuery); - - sqlQuery = "UPDATE`petition_mapping` SET `off_id`=? WHERE `mapid`=? LIMIT 1"; - jdbcTemplate.update(sqlQuery,offidto,mapid); - - return "success"; - } - - //Report List - @Transactional(readOnly = true) - public List> getReportList(Date fromDate, Date toDate, String petitionType) { - try { - StringBuilder sql = new StringBuilder( - "SELECT p.petition_no, p.petitioner_name, pt.name AS petition_type, \r\n" + - "p.petitioner_mobile, p.complaint_nature, zh.off_nm AS officer_name, \r\n" + - "zh.off_id AS officer_id, pm.status \r\n" + - "FROM commissioner_petition.petition_mapping pm \r\n" + - "LEFT JOIN commissioner_petition.petition p \r\n" + - "ON p.petition_id = pm.petition_id \r\n" + - "LEFT JOIN petition_master.officer_master_zh zh \r\n" + - "ON zh.off_id = pm.off_id \r\n" + - "LEFT JOIN petition_master.petition_types pt \r\n" + - "ON pt.petition_type_id = p.petition_type \r\n" - ); - - List params = new ArrayList<>(); - List conditions = new ArrayList<>(); - - if (fromDate != null && toDate != null) { - // Ensure toDate includes full day - Calendar cal = Calendar.getInstance(); - cal.setTime(toDate); - cal.set(Calendar.HOUR_OF_DAY, 23); - cal.set(Calendar.MINUTE, 59); - cal.set(Calendar.SECOND, 59); - cal.set(Calendar.MILLISECOND, 999); - Date toDateEnd = cal.getTime(); - - conditions.add("date(pm.cdate) BETWEEN ? AND ?"); - params.add(fromDate); - params.add(toDateEnd); - } - - if (petitionType != null && !petitionType.trim().isEmpty()) { - conditions.add("pt.petition_type_id = ?"); - params.add(petitionType); - } - - if (!conditions.isEmpty()) { - sql.append("WHERE ").append(String.join(" AND ", conditions)); - } - - List> result = jdbcTemplate.queryForList( - sql.toString(), params.toArray() - ); - - for (Map map : result) { - String petitionNo = (String) map.get("petition_no"); - if (petitionNo != null) { - map.put("petitionNoEncode", Base64Util.encodeBase64(petitionNo)); - } - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/PetitionMaster.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/PetitionMaster.java deleted file mode 100644 index c68078ac..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/PetitionMaster.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("ComPetitionMaster") -public class PetitionMaster { - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPetitionMasterDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getComplaintType(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `complaint_types` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getOfficerList(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `officer_master` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getPetitionTypes(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `petition_types` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby` ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/package-info.java deleted file mode 100644 index 7cb81204..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.com_petition.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java deleted file mode 100644 index 8693e49d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.configuration; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; -import org.springframework.core.env.Environment; - -@Configuration -public class AppConfig { - - @Autowired - private Environment env; - - public String qrAssetFeedback = "http://117.232.67.158:8063"; - public String mtm = "http://117.232.67.158:8060"; - public String petRegistration = "http://117.232.67.158:8061"; - public String garbageCollection = "http://117.232.67.158:8067"; //117.232.67.158 - public String cdwastecollectors = "https://gccservices.in"; - public String qaqcurl="https://erp.chennaicorporation.gov.in/pgr/newmobileservice?"; - public String attendanceReport = "http://117.232.67.158:8076"; - public String dumpregister = "https://gccservices.in"; - public String mobileservice="https://gccservices.in"; - public String gccappsMysqlPassword = ""; - public String domesticurl="https://gccservices.in/gccofficialapp/api/domesticwaste"; - - public String otpUrl = "https://tmegov.onex-aura.com/api/sms?"; - - public String getOtpUrl() { - return otpUrl; - } - - public void setOtpUrl(String otpUrl) { - this.otpUrl = otpUrl; - } - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java deleted file mode 100644 index 5bcb8cf7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java +++ /dev/null @@ -1,466 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.configuration; - -import org.hibernate.jpa.HibernatePersistenceProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import in.gov.chennaicorporation.gccoffice.repository.AppUserRepository; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; -import java.util.Properties; - -@Configuration -@EnableTransactionManagement -public class DataSourceConfig { - -// private static String host = "localhost:3306"; -// private static String dbpassword = "root"; - - // private static String dbpassword = "gccroot"; - - // AWS - private static String host = "gcc-facial-db-instance-1.cf48eqcciziq.ap-south-1.rds.amazonaws.com:3306"; - private static String dbpassword = "gcc-facial-password"; - - ////////////////////////////// (For GCC APP) //////////////////////// - @Configuration - @EnableTransactionManagement - @EnableJpaRepositories(entityManagerFactoryRef = "appEntityManagerFactory", transactionManagerRef = "appTransactionManager", basePackages = { - "in.gov.chennaicorporation.gccoffice.repository" }) - - public static class MysqlAppDataSourceConfig { - @Primary - @Bean(name = "mysqlAppDataSource") - public DataSource mysqlAppDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_apps"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - /* - * @Bean(name = "mysqlAppJdbcTemplate") - * public JdbcTemplate mysqlAppJdbcTemplate(@Qualifier("mysqlAppDataSource") - * DataSource dataSource) { - * return new JdbcTemplate(dataSource); - * } - */ - @Primary - @Bean(name = "appEntityManagerFactory") - public LocalContainerEntityManagerFactoryBean entityManagerFactory( - @Qualifier("mysqlAppDataSource") DataSource dataSource) { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); - entityManagerFactoryBean.setDataSource(dataSource); - entityManagerFactoryBean.setPackagesToScan("in.gov.chennaicorporation.gccoffice.entity"); - entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class); - Properties properties = new Properties(); - properties.setProperty("hibernate.hbm2ddl.auto", "update"); - entityManagerFactoryBean.setJpaProperties(properties); - - return entityManagerFactoryBean; - } - - @Primary - @Bean(name = "appTransactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("appEntityManagerFactory") EntityManagerFactory entityManagerFactory) { - return new JpaTransactionManager(entityManagerFactory); - } - } - - ////////////////////////////// (For Tax Collection 1913) - ////////////////////////////// //////////////////////// - @Configuration - @EnableTransactionManagement - @EnableJpaRepositories(entityManagerFactoryRef = "taxEntityManagerFactory", transactionManagerRef = "taxTransactionManager", basePackages = { - "in.gov.chennaicorporation.gccoffice.taxcollection.repository" }) - public static class MysqlTaxCollectionDataSourceConfig { - - @Bean(name = "mysqlTaxCollectionDataSource") - public DataSource mysqlTaxCollectionDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_tax_collection"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - @Bean(name = "taxEntityManagerFactory") - public LocalContainerEntityManagerFactoryBean taxEntityManagerFactory( - @Qualifier("mysqlTaxCollectionDataSource") DataSource dataSource) { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); - entityManagerFactoryBean.setDataSource(dataSource); - entityManagerFactoryBean.setPackagesToScan("in.gov.chennaicorporation.gccoffice.taxcollection.entity"); - entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class); - Properties properties = new Properties(); - properties.setProperty("hibernate.hbm2ddl.auto", "update"); - entityManagerFactoryBean.setJpaProperties(properties); - - return entityManagerFactoryBean; - } - - @Bean(name = "taxTransactionManager") - public PlatformTransactionManager taxTransactionManager( - @Qualifier("taxEntityManagerFactory") EntityManagerFactory taxEntityManagerFactory) { - return new JpaTransactionManager(taxEntityManagerFactory); - } - } - - ////////////////////////////// (For Mayor Petition) //////////////////////// - @Bean(name = "mysqlMayorPetitionDataSource") - public DataSource mysqlMayorPetitionDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/mayor_petition"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Commissioner Petition) - ////////////////////////////// //////////////////////// - @Bean(name = "mysqlCommissionerPetitionDataSource") - public DataSource mysqlCommissionerPetitionDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/commissioner_petition"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Petition Master) //////////////////////// - @Bean(name = "mysqlPetitionMasterDataSource") - public DataSource mysqlPetitionMasterDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/petition_master"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Councillor Petition) - ////////////////////////////// //////////////////////// - @Bean(name = "mysqlCouncillorPetitionDataSource") - public DataSource mysqlCouncillorPetitionDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/councillor_petition"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For PGR Master) //////////////////////// - @Bean(name = "mysqlPGRMasterDataSource") - public DataSource mysqlPGRMasterDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/erp_pgr"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Circular Petition) //////////////////////// - @Bean(name = "mysqlCircularDataSource") - public DataSource mysqlCircularDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/circular"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For NULM Staff) //////////////////////// - @Bean(name = "mysqlNulmDataSource") - public DataSource mysqlNulmDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_nulm"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Zero Hours Petition) - ////////////////////////////// //////////////////////// - @Bean(name = "mysqlZeroHoursDataSource") - public DataSource mysqlZeroHoursDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/zerohours_petition"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Ward Sabha) //////////////////////// - @Bean(name = "mysqlWardSabhaDataSource") - public DataSource mysqlWardSabhaDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/ward_sabha"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For 1913 Campaign) //////////////////////// - @Bean(name = "mysql1913CampaignDataSource") - public DataSource mysql1913CampaignDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_1913_campaign"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For 1913 QAQC) //////////////////////// - @Bean(name = "mysql1913QAQCDataSource") - public DataSource mysql1913QAQCDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_1913_qaqc"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For SOS) //////////////////////// - @Bean(name = "mysqlGccSOSDataSource") - public DataSource mysqlGccSOSDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_sos"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Kural) //////////////////////// - @Bean(name = "mysqlKuralDataSource") - public DataSource mysqlKuralDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/Kural"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For WORKS) //////////////////////// - @Bean(name = "mysqlWorksDataSource") - public DataSource mysqlWorksDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_works_status"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For Ward Sabha) //////////////////////// - @Bean(name = "mysqlWardShabaDataSource") - public DataSource mysqlWardShabaDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/ward_sabha"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For V-Track (jTrack)) //////////////////////// - @Bean(name = "mysqlVehiclTrackingDataSource") - public DataSource mysqlVehiclTrackingDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_vtrack"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For school) //////////////////////// - @Bean(name = "mysqlSchoolDataSource") - public DataSource mysqlSchoolDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_schools_web"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For dump registration) //////////////////////// - @Bean(name = "mysqlFlagPoleManagerSystemDataSource") - public DataSource mysqlFlagPoleManagerSystemDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_flag_pole"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For gcc_c_d_waste_web) //////////////////////// - @Bean(name = "mysqlCDManagerSystemDataSource") - public DataSource mysqlCDManagerSystemDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_c_d_waste_web"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For gcc_c_d_waste_web) //////////////////////// - @Bean(name = "mysqlPensionerDataSource") - public DataSource mysqlPensionerDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_pensioner"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For gcc_c_d_waste_web) //////////////////////// - @Bean(name = "mysqlGccStreetVendorDataSource") - public DataSource mysqlGccStreetVendorDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_street_vendor"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// (For vending committe) //////////////////////// - @Bean(name = "mysqlVendingCommitteDataSource") - public DataSource mysqlVendingCommitteDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/vendingcommitte"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - /////////////// Domestic Waste ///////////////////// - @Bean(name = "mysqlDomesticWasteDataSource") - public DataSource mysqlDomesticWasteDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/domestic_waste_management"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - /////////////// Green committee ///////////////////// - @Bean(name = "mysqlGreenCommitteeDataSource") - public DataSource mysqlGreenCommitteeDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/green_committee"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - /////////////// SCP ///////////////////// - @Bean(name = "mysqlScpDataSource") - public DataSource mysqlScpDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_1913_siltcatchpit"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - @Bean(name = "mysqlChildrenSurveyDataSource") - public DataSource mysqlChildrenSurveyDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_children_survey"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - /////////////// Road War ///////////////////// - @Bean(name = "mysqlRoadWarDataSource") - public DataSource mysqlRoadWarDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_roadwar_web"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - // homeles - @Bean(name = "mysqlHomelessSurveyDataSource") - public DataSource mysqlHomelessSurveyDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_homeless_survey"); - // dataSource.setUrl("jdbc:mysql://" + host + "/gcc_homeless_survey_live"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - /////////////// Bulk Waste Generator ///////////////////// - @Bean(name = "mysqlBulkWasteDataSource") - public DataSource mysqlBulkWasteDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/bulk_waste"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - //////////////////////////////(For GCC USER) //////////////////////// - @Bean(name = "mysqlGCCUserDataSource") - public DataSource mysqlGCCUserDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://" + host + "/gcc_users"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; - } - - ////////////////////////////// ORACLE //////////////////////// - @Bean(name = "oracleDataSource") - public DataSource oracleDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("oracle.jdbc.OracleDriver"); - dataSource.setUrl("jdbc:oracle:thin:@10.1.0.14:1521:chncorp"); - dataSource.setUsername("FAS"); - dataSource.setPassword("FAS"); - return dataSource; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/JacksonConfiguration.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/JacksonConfiguration.java deleted file mode 100644 index 291a83b3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/JacksonConfiguration.java +++ /dev/null @@ -1,20 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.configuration; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -@Configuration -public class JacksonConfiguration { - - @Bean - public ObjectMapper objectMapper() { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during serialization - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Serialize dates as Strings - objectMapper.registerModule(new JavaTimeModule()); // Register JavaTimeModule for Java 8 Date/Time support - return objectMapper; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java deleted file mode 100644 index 1397aa5d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java +++ /dev/null @@ -1,88 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.configuration; - -import javax.persistence.Basic; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -import in.gov.chennaicorporation.gccoffice.service.CustomUserDetailsService; - - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - private final CustomUserDetailsService customUserDetailsService; - - - @Autowired - public SecurityConfig(CustomUserDetailsService customUserDetailsService) { - this.customUserDetailsService = customUserDetailsService; - } - - @Override - public void configure(WebSecurity web) throws Exception { - web - .ignoring() - .antMatchers("/static/**", "/assets/**", "/api/**","/images/**","/gcc/static/**", "/gcc/assets/**", "/gcc/api/**","/gcc/images/**","/gcc/files/**","/gcc/dumpregistration/api/**"); - //.antMatchers("/gcc/static/**", "/gcc/assets/**", "/gcc/api/**","/gcc/images/**"); - //.antMatchers("/assets/**", "/css/**", "/js/**", "/images/**", "/fonts/**"); // Add the paths to your static resources here - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); - } - - // Configure authorization (URL-based access control) - @Override - protected void configure(HttpSecurity http) throws Exception { - - http - .cors().and() // Enable CORS - .csrf().disable() // Disable CSRF protection for simplicity (Enable if needed) - .authorizeRequests() - .antMatchers("/gcc/error").permitAll() - .antMatchers("/gcc/login").permitAll() // Add the login URL - .antMatchers("/gcc/admin/**").hasRole("ADMIN") // Add the admin URLs - .antMatchers("/gcc/**").hasAnyRole("ADMIN","USER") // Add other URLs - //.anyRequest().authenticated() - .and() - .formLogin() - .loginPage("/gcc/login") // Customize the login page URL - .defaultSuccessUrl("/gcc") // Include the success URL - .permitAll() - .and() - .logout() - .logoutUrl("/gcc/logout") // Include the logout URL - .logoutSuccessUrl("/gcc/login") // Include the success logout URL - .permitAll() - .and() - .sessionManagement() - .sessionFixation() - .migrateSession(); // or .none(), .newSession() - - /* - // Print role values - http.authorizeRequests().anyRequest().authenticated().and().formLogin().successHandler((request, response, authentication) -> { - System.out.println("User Roles: "); - authentication.getAuthorities().forEach(authority -> System.out.println(authority.getAuthority())); - System.out.println(); - response.sendRedirect("/gcc"); - }); - */ - } - - - @Basic - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/ThymeleafConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/ThymeleafConfig.java deleted file mode 100644 index a48ddd72..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/ThymeleafConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.configuration; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.thymeleaf.spring5.SpringTemplateEngine; -import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; -import org.thymeleaf.templatemode.TemplateMode; -import org.thymeleaf.templateresolver.ITemplateResolver; - -@Configuration -public class ThymeleafConfig { - @Bean - public ITemplateResolver templateResolver() { - SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); - templateResolver.setPrefix("classpath:/templates/"); // Set your Thymeleaf templates prefix here - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode(TemplateMode.HTML); - templateResolver.setCacheable(false); // Disable template caching for development environment - return templateResolver; - } - - @Bean - public SpringTemplateEngine templateEngine() { - SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - return templateEngine; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/WebMvcConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/WebMvcConfig.java deleted file mode 100644 index 02bb9809..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/WebMvcConfig.java +++ /dev/null @@ -1,72 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.configuration; - -//import java.nio.file.Paths; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import in.gov.chennaicorporation.gccoffice.interceptor.AppInterceptor; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemRepository; - -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - private final String uploadDirectory; - private AppModuleAccessRepository appModuleAccessRepository; - private MenuItemAccessRepository menuItemAccessRepository; - private SubMenuItemAccessRepository subMenuItemAccessRepository; - - private AppModuleRepository appModuleRepository; - private MenuItemRepository menuItemRepository; - private SubMenuItemRepository subMenuItemRepository; - - private final Environment environment; - - @Autowired - public WebMvcConfig( - @Value("${file.upload.directory}") String uploadDirectory, - AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository, - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - Environment environment) { - this.uploadDirectory = uploadDirectory; - this.appModuleAccessRepository = appModuleAccessRepository; - this.menuItemAccessRepository = menuItemAccessRepository; - this.subMenuItemAccessRepository = subMenuItemAccessRepository; - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - this.environment = environment; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - - registry.addInterceptor(new AppInterceptor( - appModuleAccessRepository, - menuItemAccessRepository, - subMenuItemAccessRepository, - appModuleRepository, - menuItemRepository, - subMenuItemRepository, - environment)); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadDirectory +"/"); - } -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/APIController.java deleted file mode 100644 index ade7c25d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/APIController.java +++ /dev/null @@ -1,467 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import java.util.Base64; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -import org.springframework.beans.factory.annotation.Autowired; -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 in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppUserEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.UserActivityLog; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppUserRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.UserActivityLogRepository; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; - -@RequestMapping("/gcc/api") -@RestController -public class APIController { - - List getAppUserEntities; - - @Autowired - private HttpServletRequest request; - - @Autowired - private AppUserRepository appUserRepository; - - @Autowired - private LoginUserInfo loginUserInfo; - - List getActivityLogs; - @Autowired - private UserActivityLogRepository userActivityLogRepository; - - List getAppModuleAccessEntities; - List getMenuItemAccessEntities; - List getSubMenuItemAccessEntities; - - @Autowired - private AppModuleAccessRepository appModuleAccessRepository; - @Autowired - private MenuItemAccessRepository menuItemAccessRepository; - @Autowired - private SubMenuItemAccessRepository subMenuItemAccessRepository; - - List getAppModuleEntities; - List getMenuItemEntities; - List getSubMenuItemEntities; - - @Autowired - private AppModuleRepository appModuleRepository; - @Autowired - private MenuItemRepository menuItemRepository; - @Autowired - private SubMenuItemRepository subMenuItemRepository; - - @Autowired - public APIController( - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository, - UserActivityLogRepository userActivityLogRepository) { - - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - - this.appModuleAccessRepository = appModuleAccessRepository; - this.menuItemAccessRepository = menuItemAccessRepository; - this.subMenuItemAccessRepository = subMenuItemAccessRepository; - this.userActivityLogRepository = userActivityLogRepository; - - } - - // Encode to Base64 - @GetMapping(value="/encodeBase64") - public static String encodeBase64(@RequestParam String string) { - String value=string; - byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes()); - return new String(encodedBytes); - } - - // Decode from Base64 - @GetMapping(value="/decodeBase64") - public static String decodeBase64(@RequestParam String string) { - String encodedValue=string; - byte[] decodedBytes = Base64.getDecoder().decode(encodedValue); - return new String(decodedBytes); - } - - @GetMapping(value="/getAccessTree") - public String getAccessTreeHTML(@RequestParam String groupId,@RequestParam String groupName) { - - getAppModuleEntities = appModuleRepository.showAll(); - - String accessHTML = ""; - String accessTableHTML = ""; - //String MenuHTML = ""; - String isSelected = ""; - //String subMenuHTML = ""; - - String groupNameHTML = ""+groupName+""; - for (AppModuleEntity moduleName : getAppModuleEntities) { - - // ID to check - Integer desiredId = moduleName.getId(); - - // Check if the ID exists in the list of entities - getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId,desiredId.toString()); - // Check Module Id Access - if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; } - - accessHTML = accessHTML+"
  •  "; - - - getMenuItemEntities = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); - - String subMenuHTML = ""; - for (MenuItemEntity menuItem : getMenuItemEntities) { - - String mmid = desiredId+"_"+menuItem.getId(); - // Check if the ID exists in the list of entities - getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString()); - // Check Module Id Access - if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; } - - if(menuItem.getHasSub()) { - - getSubMenuItemEntities = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getSubMenuItemEntities) { - String isSelected2 = ""; - String smid = desiredId+"_"+menuItem.getId()+"_"+subMenuItem.getId(); - // Check if the ID exists in the list of entities - getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString(),subMenuItem.getId().toString()); - // Check Module Id Access - if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { isSelected2 = "checked"; } else { isSelected2 = ""; } - - subSubMenuHTML = subSubMenuHTML+"
  •  
  • "; - } - if(subSubMenuHTML.equals("")) - { - subMenuHTML = subMenuHTML+"
  •  
  • "; - } - else { - subMenuHTML = subMenuHTML+"
  •  
      "+subSubMenuHTML+"
  • "; - } - - } - else { - subMenuHTML = subMenuHTML+"
  •  
  • "; - } - } - - accessHTML = accessHTML+"
      "+subMenuHTML+"
    "; - subMenuHTML = ""; - - } - - accessTableHTML = groupNameHTML+"
      "+accessHTML+"
    "; - - return accessTableHTML; - } - - @PostMapping("/saveGroupAccessData") - public String saveGroupAccessData(@RequestBody Map requestBody) { - @SuppressWarnings("unchecked") - List checkedData = (List) requestBody.get("checkedData"); - String groupId = (String) requestBody.get("groupId"); - String dataType[]= {"","", "module","menu","submenu"}; - if (groupId != null) { - System.out.println("groupid value: " + groupId); - - // Set isActive = false based on groupId - appModuleAccessRepository.updateActiveStatus(false,groupId); - menuItemAccessRepository.updateActiveStatus(false,groupId); - subMenuItemAccessRepository.updateActiveStatus(false,groupId); - - // Now update as per input data - if (checkedData != null) { - for (String data : checkedData) { - System.out.println(data); - - // m_x -> Module Value (moduleId) -> 2 - // mm_x_x -> Menu Value (moduleId,menuId) ->3 - // sm_x_x_x -> SubMenu Value (moduleId, menuId, submenuId) ->4 - - String[] dataValue = data.split("_"); - Integer dataLength = dataValue.length; - System.out.println(dataLength +" ==> "+dataType[dataLength]); - - if(dataValue.length==2) { // Module - // Check if the ID exists in the list of entities - getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, dataValue[1]); - if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { - appModuleAccessRepository.update(true,groupId,dataValue[1]); - } - else { - appModuleAccessRepository.insert(groupId,dataValue[1]); - } - } - else if(dataValue.length==3) { // Menu - // Check if the ID exists in the list of entities - getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2]); - if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { - menuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2]); - } - else { - menuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2]); - } - } - else if(dataValue.length==4) { // SubMenu - // Check if the ID exists in the list of entities - getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2], dataValue[3]); - if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { - subMenuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2],dataValue[3]); - } - else { - subMenuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2],dataValue[3]); - } - } - - } - } - - } - - return ""; - } - - @GetMapping(value="/getUserProfileBasic") - public String getUserProfileBasic(@RequestParam String userId) { - //String userHtml =""; - String userProfileHtml =""; - //String userProfileTimelineHtml =""; - getAppUserEntities = appUserRepository.showById(userId); - for (AppUserEntity appUserEntity : getAppUserEntities) { - - userProfileHtml = "" - + " " - + "
    " - + "
    " - + "
    " - + " \n" - + "

    "+appUserEntity.getUserid().getName()+"

    \n" - + "

    Front End Developer

    \n" - + "
    \n" - + "
    " - + "
    \n" - + "
    \n" - + " Email address \n" - + " "+appUserEntity.getUserid().getEmail()+" \n" - + " Phone\n" - + " "+appUserEntity.getUserid().getPhone()+" \n" - + " Role\n" - + " "+appUserEntity.getRoles()+"\n" - + " Access Group\n" - + " "+appUserEntity.getUsergroup_id().getName()+"\n" - + "
    \n" - + "
    \n" - + " "; - - } - - return userProfileHtml; - } - - @GetMapping(value="/getUserProfile") - public String getUserProfile(@RequestParam String userId) { - String userHtml =""; - String userProfileHtml =""; - String userProfileTimelineHtml =""; - String userIp = getUserIP(); - getAppUserEntities = appUserRepository.showById(userId); - for (AppUserEntity appUserEntity : getAppUserEntities) { - - userProfileHtml = "" - + "
    " - + "
    " - + "
    " - + "
    " - + " \n" - + "

    "+appUserEntity.getUserid().getName()+"

    \n" - + "

    Front End Developer

    \n" - + "

    "+userIp+"

    \n" - + "
    \n" - + "
    " - + "
    \n" - + "
    \n" - + " Email address \n" - + " "+appUserEntity.getUserid().getEmail()+" \n" - + " Phone\n" - + " "+appUserEntity.getUserid().getPhone()+" \n" - + " Role\n" - + " "+appUserEntity.getRoles()+"\n" - + " Access Group\n" - + " "+appUserEntity.getUsergroup_id().getName()+"\n" - + "
    \n" - + "
    \n" - + "
    "; - - userProfileTimelineHtml = "" - + "
    " - + "
    " - + " " - + "
    " - + "
    " - + userTimeLine(appUserEntity.getUserid().getUserid().toString(),appUserEntity.getUserid().getName(),"user.jpg") - + "
    " - + "
    " - + "
    " - + "
    "; - - userHtml ="
    " + userProfileHtml + userProfileTimelineHtml + "
    "; - - } - - return userHtml; - } - - - public String userTimeLine(String userid, String userName, String img) { - - - String userTimeLineHTML = ""; - - getActivityLogs = userActivityLogRepository.findByUserIdOrderByTimestampDesc(userid); - for (UserActivityLog userActivityLog : getActivityLogs) { - userTimeLineHTML += "" - + "
    " - + "
    " - + " user " - + "
    " - + "
    " - + "
    " - + " "+userName+" " - + " "+dateFormat(userActivityLog.getTimestamp().toString())+"" - + "
    " - + " "+userActivityLog.getActivityType() - + "
    " - + "
    " - + "
    " - + "

    "; - } - userTimeLineHTML = "" - + "
    " - + "
    " - + userTimeLineHTML - + "
    " - + "
    "; - - return userTimeLineHTML; - } - - - public String dateFormat(String timestampString) { - //String timestampString = "2023-12-28T16:21:24"; - LocalDateTime timestamp = LocalDateTime.parse(timestampString, DateTimeFormatter.ISO_DATE_TIME); - - // Define the desired date-time format - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a"); - - // Format the timestamp - String formattedTimestamp = timestamp.format(formatter); - - //System.out.println(formattedTimestamp); - return formattedTimestamp.toUpperCase(); - } - - public String getUserIP() { - String ipAddress = request.getHeader("X-Forwarded-For"); - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("WL-Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("HTTP_CLIENT_IP"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getRemoteAddr(); - } - return ipAddress; - } - - @GetMapping(value="/passwordGenerator") - public String passwordGenerator(@RequestParam(value = "password", required = false) String password) { - BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - String rawPassword = password; - String encodedPassword = passwordEncoder.encode(rawPassword); - return encodedPassword; - } - - @PostMapping(value="/resetPassword") - public String resetPassword( - @RequestParam(value = "", required = false) String userid, - @RequestParam(value = "", required = false) String oldpassword, - @RequestParam(value = "", required = false) String newpassword - ) { - - System.out.println(userid+" : "+oldpassword+" : "+newpassword); - - String oldPasswordTxt=oldpassword; //passwordGenerator(oldpassword); - String newPasswordTxt=newpassword; //passwordGenerator(newpassword); - String rawPasswordTxt=newpassword; - - System.out.println(oldPasswordTxt+" : "+newPasswordTxt+" : "+rawPasswordTxt); - - String response = loginUserInfo.resetPassword(userid,oldPasswordTxt,newPasswordTxt,rawPasswordTxt); - return response; - } - - @PostMapping(value="/userCheck") - public List> userCheck( - @RequestParam(value = "", required = false) String usernametxt, - @RequestParam(value = "", required = false) String passwordtxt - ) { - - System.out.println("HRM Service : "+usernametxt+" : "+passwordtxt); - - List> response = loginUserInfo.userCheck(usernametxt,passwordtxt); - return response; - } - - @GetMapping(value="/getDailyKural") - public List getDailyKural() { - return loginUserInfo.getDailyContent(); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/APIMobileCotroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/APIMobileCotroller.java deleted file mode 100644 index e8c5a2ac..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/APIMobileCotroller.java +++ /dev/null @@ -1,115 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemRepository; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/api/mobile") -@RestController -public class APIMobileCotroller { - private JdbcTemplate jdbcTemplate; - - private AppModuleRepository appModuleRepository; - private MenuItemRepository menuItemRepository; - private SubMenuItemRepository subMenuItemRepository; - - private AppModuleAccessRepository appModuleAccessRepository; - private MenuItemAccessRepository menuItemAccessRepository; - private SubMenuItemAccessRepository subMenuItemAccessRepository; - - @Autowired - public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource dataSource, - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.appModuleRepository =appModuleRepository; - this.menuItemRepository =menuItemRepository; - this.subMenuItemRepository =subMenuItemRepository; - this.appModuleAccessRepository =appModuleAccessRepository; - this.menuItemAccessRepository =menuItemAccessRepository; - this.subMenuItemAccessRepository =subMenuItemAccessRepository; - - } - @GetMapping(value="/getMenu") - public List getMenu(@RequestParam String groupId){ - String SqlQuery = ""; - - List getAppModuleAccessEntities; - List getAppModuleEntities; - - getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(groupId); - - String[] checkModuleId = new String[getAppModuleAccessEntities.size()]; - int i=0; - for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) { - checkModuleId[i]=accessEntity.getModuleId().getId().toString(); - i++; - } - getAppModuleEntities = appModuleRepository.showAllById(checkModuleId); - - return getAppModuleEntities; - } - - @GetMapping(value="/getSubMenu") - public List getSubMenu(@RequestParam String groupId, @RequestParam Integer menuId ){ - String SqlQuery = ""; - - List getMenuItems; - - List getMenuItemAccess = menuItemAccessRepository.findByUserGroupID(groupId, menuId.toString()); - - String[] checkMenuId = new String[getMenuItemAccess.size()]; - int j=0; - for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) { - checkMenuId[j]=menuAccessEntity.getMenuItemId().getId().toString(); - j++; - } - getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(menuId,checkMenuId); - - return getMenuItems; - } - - @GetMapping(value="/getSubSubMenu") - public List getSubSubMenu(@RequestParam String groupId, @RequestParam Integer menuId, @RequestParam Integer submenuId ){ - String SqlQuery = ""; - - List getSubMenuItemAccess = subMenuItemAccessRepository.findByUserGroupIDAccess(groupId, menuId.toString(), submenuId.toString()); - - String[] checkSubMenuId = new String[getSubMenuItemAccess.size()]; - int k=0; - for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) { - checkSubMenuId[k]=subMenuItemAccessEntity.getSubMenuItemId().getId().toString(); - k++; - } - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(submenuId,checkSubMenuId); - - return getMenuSubItems; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/AdminController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/AdminController.java deleted file mode 100644 index 1f3d6b1b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/AdminController.java +++ /dev/null @@ -1,150 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -//import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppUserEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppUserGroupEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppUserGroupRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppUserRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemRepository; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/admin") -@Controller("gccAdminController") -public class AdminController { - - - private final AppUserRepository appUserRepository; - private final AppUserGroupRepository appUserGroupRepository; - - private final AppModuleRepository appModuleRepository; - private final MenuItemRepository menuItemRepository; - private final SubMenuItemRepository subMenuItemRepository; - - - - @Autowired - public AdminController( - AppUserRepository appUserRepository, - AppUserGroupRepository appUserGroupRepository, - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository) { - - this.appUserRepository = appUserRepository; - this.appUserGroupRepository = appUserGroupRepository; - - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - - } - - @GetMapping({"", "/", "/index"}) - public String main(Model model) { - String userId = LoginUserInfo.getLoginUserId(); - if (userId != null && !userId.isEmpty()) { - System.out.println("String UserID: " + userId); - } - return "modules/admin/index"; - } - - @GetMapping("/user-list") - public String userList(Model model) { - model.addAttribute("userlist",getUser()); - return "modules/admin/user-list"; - } - - @GetMapping("/user-group-list") - public String userGroupList(Model model) { - model.addAttribute("userGroupList",getUserGroup()); - return "modules/admin/user-group-list"; - } - - @GetMapping("/user-group-access") - public String userGroupAccess(Model model) { - String accessTableHTML = getAccessTreeHTML(); - model.addAttribute("userGroupList",getUserGroup()); - model.addAttribute("accessHTML",accessTableHTML); - return "modules/admin/user-group-access"; - } - - - - //////////////////////////////////////// (Functions) //////////////////////////////////////// - - public List getUser() { - List appUserEntities; - appUserEntities = appUserRepository.showAll(); - return appUserEntities; - } - - public List getUserGroup() { - List appUserGroupEntities; - appUserGroupEntities = appUserGroupRepository.findAll(); - return appUserGroupEntities; - } - - public String getAccessTreeHTML() { - - //List getAppModuleAccessEntities; - List getAppModuleEntities; - - getAppModuleEntities = appModuleRepository.showAll(); - - String accessHTML = ""; - String accessTableHTML = ""; - //String MenuHTML = ""; - //String subMenuHTML = ""; - for (AppModuleEntity moduleName : getAppModuleEntities) { - - accessHTML = accessHTML+"
  •  "; - - List getMenuItems; - getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); - - String subMenuHTML = ""; - for (MenuItemEntity menuItem : getMenuItems) { - - if(menuItem.getHasSub()) { - - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - subSubMenuHTML = subSubMenuHTML+"
  • "; - } - if(subSubMenuHTML.equals("")) - { - subMenuHTML = subMenuHTML+"
  • "; - } - else { - subMenuHTML = subMenuHTML+"
    • "+subSubMenuHTML+"
  • "; - } - - } - else { - subMenuHTML = subMenuHTML+"
  • "; - } - } - - accessHTML = accessHTML+"
      "+subMenuHTML+"
    "; - subMenuHTML = ""; - } - - accessTableHTML = "
      "+accessHTML+"
    "; - - return accessTableHTML; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/CustomErrorController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/CustomErrorController.java deleted file mode 100644 index 40c19e95..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/CustomErrorController.java +++ /dev/null @@ -1,126 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import in.gov.chennaicorporation.gccoffice.modeldata.ErrorResponse; - -@Controller -public class CustomErrorController implements ErrorController { - - private static final String ERROR_PATH = "/error"; - private static final Map PAGE_NAME_MAP = new HashMap<>(); - - public String getPageName(Integer statusCode) { - if (statusCode != null) { - return PAGE_NAME_MAP.getOrDefault(statusCode, "errorPage"); - } else { - return "errorPage"; - } - } - - // Handle errors for web applications, return HTML error pages - @RequestMapping(value = ERROR_PATH, produces = "text/html") - public String handleWebError(HttpServletRequest request, Model model) { - // Retrieve error information from the request - // HttpStatus status = HttpStatus.valueOf((Integer) request.getAttribute("javax.servlet.error.status_code")); - //Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); - - // Retrieve error information from the request - Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); - if (statusCode == null) { - // Add the error message to the model - model.addAttribute("errorStatus", "Error 403"); - model.addAttribute("errorError", "403 - Access Denied"); - model.addAttribute("errorMessage", "Oops, You don`t have permission to access this page."); - // Handle the case where the status code is null - // You may choose to set default values or redirect to a generic error page - return "error-403"; - } - - HttpStatus status = (statusCode != null) ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR; - Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); - - // Add custom error handling logic for web applications here - String errorPage = "error"; - Integer errorStatus = 404; - String errorError = "Internal Server Error"; - String errorMessage = "An error occurred"; // Default error message - - String pageName = new CustomErrorController().getPageName(status.value()); - - // Print error information to the console - if (status != null) { - errorStatus = status.value(); - errorError = status.getReasonPhrase(); - - System.err.println("HTTP Status: " + status +"\n" - +"Status Code: "+status.value()+"\n"+ "Status Error: " - +status.getReasonPhrase() - +"Page Name: "+pageName); - - // Check if the status code - if (status == HttpStatus.NOT_FOUND) { - errorPage = "error-404"; // 400 Error Page - } - else if (status == HttpStatus.INTERNAL_SERVER_ERROR) { - errorPage = "error-500"; // 500 Error page - } - else { - errorPage = "error"; //// Other Error page - } - } - if (throwable != null) { - // Retrieve the exception message - errorMessage = throwable.getMessage(); - throwable.printStackTrace(); - } - - // Add the error message to the model - model.addAttribute("errorStatus", errorStatus); - model.addAttribute("errorError", errorError); - model.addAttribute("errorMessage", errorMessage); - - - return errorPage; // Return the name of your custom HTML error page (without the .html extension) - } - - // Handle errors for RESTful APIs, return JSON error responses - @RequestMapping(value = ERROR_PATH, produces = "application/json") - @ResponseBody - public ResponseEntity handleApiError(HttpServletRequest request) { - // Retrieve error information from the request - HttpStatus status = HttpStatus.valueOf((Integer) request.getAttribute("javax.servlet.error.status_code")); - Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); - - // Create an error response - ErrorResponse errorResponse = new ErrorResponse(); - errorResponse.setStatus(status.value()); - errorResponse.setError(status.getReasonPhrase()); - errorResponse.setMessage("An error occurred"); - - if (throwable != null) { - errorResponse.setException(throwable.getMessage()); - } - - // Return a ResponseEntity with the custom JSON error response and HTTP status - return ResponseEntity.status(status).body(errorResponse); - } - - - @GetMapping(ERROR_PATH) - public String handleError() { - return "error-404"; // Return the name of your custom error page (without the .html extension) - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/DateTimeUtil.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/DateTimeUtil.java deleted file mode 100644 index 40a2b0e1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/DateTimeUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -@Service -public class DateTimeUtil { - public static String getCurrentDateTime() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentYear() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentMonth() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentDay() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentDateTimeMysql() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/FileController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/FileController.java deleted file mode 100644 index 795c6939..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/FileController.java +++ /dev/null @@ -1,73 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.core.io.UrlResource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.servlet.HandlerMapping; - -import java.nio.file.Path; -import java.nio.file.Paths; - -import javax.servlet.http.HttpServletRequest; - -@Controller -public class FileController { - - @Value("${file.upload.directory}") - private String uploadDirectory; - - @GetMapping("/gcc/files/{directoryPath}/**") - public ResponseEntity serveFile(@PathVariable String directoryPath, HttpServletRequest request) { - String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); - System.out.println(fullPath.toString()+"\n"+directoryPath.length()+"\n directoryPath:"+directoryPath); - //String relativePath = fullPath.substring(directoryPath.length() + 1); // Adding 1 for the trailing '/' - String relativePath = fullPath.replace("/gcc/files", ""); - String filePath = uploadDirectory + "/" + relativePath; - Path path = Paths.get(filePath).normalize(); - System.out.println(path.toString()); - Resource resource; - try { - resource = new UrlResource(path.toUri()); - if (resource.exists() || resource.isReadable()) { - MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; - // Determine content type based on file extension - String fileName = resource.getFilename(); - if (fileName != null) { - String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); - switch (fileExtension.toLowerCase()) { - case "jpg": - case "jpeg": - mediaType = MediaType.IMAGE_JPEG; - break; - case "png": - mediaType = MediaType.IMAGE_PNG; - break; - case "gif": - mediaType = MediaType.IMAGE_GIF; - break; - case "pdf": - mediaType = MediaType.APPLICATION_PDF; - break; - // Add more cases for other file types if needed - } - } - return ResponseEntity.ok() - .contentType(mediaType) - .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"") - //.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") - .body(resource); - } else { - return ResponseEntity.notFound().build(); - } - } catch (Exception e) { - return ResponseEntity.notFound().build(); - } - } -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MainController.java deleted file mode 100644 index 838a3e74..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MainController.java +++ /dev/null @@ -1,28 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc") -@Controller("gccOfficeController") -public class MainController { - - @GetMapping({"", "/", "/index"}) - public String main(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - if (LoginUserId != null && !LoginUserId.isEmpty()) { - System.out.println("String UserID: " + LoginUserId); - } - model.addAttribute("LoginUserId",LoginUserId); - return "index"; - } - - @GetMapping("/widget-statistic") - public String widgetStatistic(Model model) { - return "widget-statistic"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java deleted file mode 100644 index bc82455a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java +++ /dev/null @@ -1,167 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ModelAttribute; - -import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemRepository; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@ControllerAdvice -public class MenuController { - - private final AppModuleRepository appModuleRepository; - private final MenuItemRepository menuItemRepository; - private final SubMenuItemRepository subMenuItemRepository; - - private final AppModuleAccessRepository appModuleAccessRepository; - private final MenuItemAccessRepository menuItemAccessRepository; - private final SubMenuItemAccessRepository subMenuItemAccessRepository; - - @Autowired - public MenuController(AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository) { - - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - - this.appModuleAccessRepository = appModuleAccessRepository; - this.menuItemAccessRepository = menuItemAccessRepository; - this.subMenuItemAccessRepository = subMenuItemAccessRepository; - } - - @ModelAttribute("menuItemsHTML") // This will add the menuItems to the model for all requests - public String menuHTML() { - - if(LoginUserInfo.getLoginUserId() == null || LoginUserInfo.getUserGroupId()==null) { - return ""; - } - - List getAppModuleAccessEntities; - List getAppModuleEntities; - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - getAppModuleEntities = appModuleRepository.showAll(); - } - else { - getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId()); - - String[] checkModuleId = new String[getAppModuleAccessEntities.size()]; - int i=0; - for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) { - checkModuleId[i]=accessEntity.getModuleId().getId().toString(); - i++; - } - getAppModuleEntities = appModuleRepository.showAllById(checkModuleId); - } - - String menuHTML = ""; - menuHTML = ""; - for (AppModuleEntity moduleName : getAppModuleEntities) { - - menuHTML = menuHTML+"
    "+moduleName.getName()+"
    "; - - List getMenuItems; - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); - } - else { - List getMenuItemAccess = menuItemAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId(), moduleName.getId().toString()); - - String[] checkMenuId = new String[getMenuItemAccess.size()]; - int j=0; - for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) { - checkMenuId[j]=menuAccessEntity.getMenuItemId().getId().toString(); - j++; - } - getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(moduleName.getId(),checkMenuId); - } - String subMenuHTML = ""; - for (MenuItemEntity menuItem : getMenuItems) { - if(menuItem.getHasSub()) { - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - String target = ""; - System.err.println(subMenuItem.getExtenalLink()); - if(subMenuItem.getExtenalLink()) { - target = " target=\"_blank\""; - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - else { - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - - } - if(subSubMenuHTML.equals("")) - { - subMenuHTML = subMenuHTML+""; - } - else { - subMenuHTML = subMenuHTML+"
    "+menuItem.getName()+"
    "+subSubMenuHTML+"
    "; - } - } - else { - List getSubMenuItemAccess = subMenuItemAccessRepository.findByUserGroupIDAccess(LoginUserInfo.getUserGroupId(), moduleName.getId().toString(), menuItem.getId().toString()); - - String[] checkSubMenuId = new String[getSubMenuItemAccess.size()]; - if(checkSubMenuId.length>0) - { - int k=0; - for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) { - checkSubMenuId[k]=subMenuItemAccessEntity.getSubMenuItemId().getId().toString(); - k++; - } - - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(menuItem.getId(),checkSubMenuId); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - String target = ""; - System.err.println(subMenuItem.getExtenalLink()); - if(subMenuItem.getExtenalLink()) { - target = " target=\"_blank\""; - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - else { - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - } - subMenuHTML = subMenuHTML+"
    "+menuItem.getName()+"
    "+subSubMenuHTML+"
    "; - } - else { - subMenuHTML = subMenuHTML+""; - } - } - - } - else { - if(menuItem.getOrderby()>0) { - subMenuHTML = subMenuHTML+""+menuItem.getName()+""; - } - } - } - - menuHTML = menuHTML+subMenuHTML+"
    "; - } - - return menuHTML; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/login.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/login.java deleted file mode 100644 index e09a5727..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/login.java +++ /dev/null @@ -1,14 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -@RequestMapping("/gcc") -@Controller("gccLoginController") -public class login { - @GetMapping("/login") - public String home(Model model) { - return "login"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/.DS_Store deleted file mode 100644 index 2d00e2b1..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppModuleAccessEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppModuleAccessEntity.java deleted file mode 100644 index 46371b01..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppModuleAccessEntity.java +++ /dev/null @@ -1,116 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "modules_access") -public class AppModuleAccessEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "usergroup_id", referencedColumnName = "id") - private AppUserGroupEntity userGroupId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public AppModuleAccessEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public AppUserGroupEntity getUserGroupId() { - return userGroupId; - } - - - public void setUserGroupId(AppUserGroupEntity userGroupId) { - this.userGroupId = userGroupId; - } - - - public AppModuleEntity getModuleId() { - return moduleId; - } - - - public void setModuleId(AppModuleEntity moduleId) { - this.moduleId = moduleId; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppModuleEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppModuleEntity.java deleted file mode 100644 index f49c7b5f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppModuleEntity.java +++ /dev/null @@ -1,139 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "modules") -public class AppModuleEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "module_path",nullable = false) - private String modulePath; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0") - private Integer orderby; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public AppModuleEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - public String getModulePath() { - return modulePath; - } - - - public String getIcon() { - return icon; - } - - - public void setIcon(String icon) { - this.icon = icon; - } - - - public void setModulePath(String modulePath) { - this.modulePath = modulePath; - } - - - public Integer getOrderby() { - return orderby; - } - - - public void setOrderby(Integer orderby) { - this.orderby = orderby; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppUserEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppUserEntity.java deleted file mode 100644 index b0d9d77e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppUserEntity.java +++ /dev/null @@ -1,155 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "appusers") -public class AppUserEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "userid", referencedColumnName = "userid") - private UserInfoEntity userid; - - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "usergroup_id", referencedColumnName = "id") - private AppUserGroupEntity usergroup_id; - - @Column(name = "username",nullable = false) - private String username; - - @Column(name = "password",nullable = false) - private String password; - - @Column(name = "roles",nullable = false) - private String roles; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public AppUserEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public UserInfoEntity getUserid() { - return userid; - } - - - public void setUserid(UserInfoEntity userid) { - this.userid = userid; - } - - - public AppUserGroupEntity getUsergroup_id() { - return usergroup_id; - } - - - public void setUsergroup_id(AppUserGroupEntity usergroup_id) { - this.usergroup_id = usergroup_id; - } - - - public String getUsername() { - return username; - } - - - public void setUsername(String username) { - this.username = username; - } - - - public String getPassword() { - return password; - } - - - public void setPassword(String password) { - this.password = password; - } - - - public String getRoles() { - return roles; - } - - - public void setRoles(String roles) { - this.roles = roles; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppUserGroupEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppUserGroupEntity.java deleted file mode 100644 index 2d8bc925..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/AppUserGroupEntity.java +++ /dev/null @@ -1,113 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "usergroup") -public class AppUserGroupEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public AppUserGroupEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - public String getIcon() { - return icon; - } - - - public void setIcon(String icon) { - this.icon = icon; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/MenuItemAccessEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/MenuItemAccessEntity.java deleted file mode 100644 index b91a08cd..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/MenuItemAccessEntity.java +++ /dev/null @@ -1,129 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "menuitem_access") -public class MenuItemAccessEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "usergroup_id", referencedColumnName = "id") - private AppUserGroupEntity userGroupId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "menuitem_id", referencedColumnName = "id") - private MenuItemEntity menuItemId; - - @ManyToOne - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public MenuItemAccessEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public AppUserGroupEntity getUserGroupId() { - return userGroupId; - } - - - public void setUserGroupId(AppUserGroupEntity userGroupId) { - this.userGroupId = userGroupId; - } - - - public MenuItemEntity getMenuItemId() { - return menuItemId; - } - - - public void setMenuItemId(MenuItemEntity menuItemId) { - this.menuItemId = menuItemId; - } - - - public AppModuleEntity getModuleId() { - return moduleId; - } - - - public void setModuleId(AppModuleEntity moduleId) { - this.moduleId = moduleId; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/MenuItemEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/MenuItemEntity.java deleted file mode 100644 index 9d86d688..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/MenuItemEntity.java +++ /dev/null @@ -1,168 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "menuitem") -public class MenuItemEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "url",nullable = false) - private String url; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0") - private Integer orderby; - - @Column(name = "ishassub",nullable = false, columnDefinition = "Boolean default false") - private Boolean hasSub; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public MenuItemEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public AppModuleEntity getModuleId() { - return moduleId; - } - - - public void setModuleId(AppModuleEntity moduleId) { - this.moduleId = moduleId; - } - - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - public String getUrl() { - return url; - } - - - public void setUrl(String url) { - this.url = url; - } - - - public String getIcon() { - return icon; - } - - - public Integer getOrderby() { - return orderby; - } - - - public void setOrderby(Integer orderby) { - this.orderby = orderby; - } - - - public void setIcon(String icon) { - this.icon = icon; - } - - - public Boolean getHasSub() { - return hasSub; - } - - - public void setHasSub(Boolean hasSub) { - this.hasSub = hasSub; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java deleted file mode 100644 index 19134c6d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java +++ /dev/null @@ -1,145 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "submenuitem_access") -public class SubMenuItemAccessEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "usergroup_id", referencedColumnName = "id") - private AppUserGroupEntity userGroupId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "submenuitem_id", referencedColumnName = "id") - private SubMenuItemEntity subMenuItemId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "menuitem_id", referencedColumnName = "id") - private MenuItemEntity menuItemId; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public SubMenuItemAccessEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public AppUserGroupEntity getUserGroupId() { - return userGroupId; - } - - - public void setUserGroupId(AppUserGroupEntity userGroupId) { - this.userGroupId = userGroupId; - } - - - public SubMenuItemEntity getSubMenuItemId() { - return subMenuItemId; - } - - - public void setSubMenuItemId(SubMenuItemEntity subMenuItemId) { - this.subMenuItemId = subMenuItemId; - } - - - - public AppModuleEntity getModuleId() { - return moduleId; - } - - - public void setModuleId(AppModuleEntity moduleId) { - this.moduleId = moduleId; - } - - - public MenuItemEntity getMenuItemId() { - return menuItemId; - } - - - public void setMenuItemId(MenuItemEntity menuItemId) { - this.menuItemId = menuItemId; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemEntity.java deleted file mode 100644 index dedd2f33..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemEntity.java +++ /dev/null @@ -1,179 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "submenuitem") -public class SubMenuItemEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "menuitem_id", referencedColumnName = "id") - private MenuItemEntity menuItemId; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "url",nullable = false) - private String url; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0") - private Integer orderby; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - @Column(name = "extenallink",nullable = false, columnDefinition = "Boolean default true") - private Boolean extenalLink; - - public SubMenuItemEntity() { - - } - - - public Integer getId() { - return id; - } - - - public void setId(Integer id) { - this.id = id; - } - - - public AppModuleEntity getModuleId() { - return moduleId; - } - - - public void setModuleId(AppModuleEntity moduleId) { - this.moduleId = moduleId; - } - - - public MenuItemEntity getMenuItemId() { - return menuItemId; - } - - - public void setMenuItemId(MenuItemEntity menuItemId) { - this.menuItemId = menuItemId; - } - - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - public String getUrl() { - return url; - } - - - public void setUrl(String url) { - this.url = url; - } - - - public String getIcon() { - return icon; - } - - - public void setIcon(String icon) { - this.icon = icon; - } - - - public Integer getOrderby() { - return orderby; - } - - - public void setOrderby(Integer orderby) { - this.orderby = orderby; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - - public Boolean getExtenalLink() { - return extenalLink; - } - - - public void setExtenalLink(Boolean extenalLink) { - this.extenalLink = extenalLink; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/UserActivityLog.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/UserActivityLog.java deleted file mode 100644 index aa986a14..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/UserActivityLog.java +++ /dev/null @@ -1,56 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.*; -import java.time.LocalDateTime; - -@Entity -@Table(name = "user_activity_log") -public class UserActivityLog { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String userId; - - private String activityType; - - private LocalDateTime timestamp; - - public UserActivityLog() { - - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getActivityType() { - return activityType; - } - - public void setActivityType(String activityType) { - this.activityType = activityType; - } - - public LocalDateTime getTimestamp() { - return timestamp; - } - - public void setTimestamp(LocalDateTime timestamp) { - this.timestamp = timestamp; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/UserInfoEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/UserInfoEntity.java deleted file mode 100644 index 82e729b9..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/UserInfoEntity.java +++ /dev/null @@ -1,108 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "userinfo") -public class UserInfoEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "userid",nullable = false) - private Integer userid; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "email") - private String email; - - @Column(name = "phone") - private String phone; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - public UserInfoEntity() { - - } - - public Integer getUserid() { - return userid; - } - - public void setUserid(Integer userid) { - this.userid = userid; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - public Integer getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/.DS_Store deleted file mode 100644 index c51f47dc..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/controller/FlagPoleApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/controller/FlagPoleApiController.java deleted file mode 100644 index 36733dcb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/controller/FlagPoleApiController.java +++ /dev/null @@ -1,412 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.flagpole.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.flagpole.service.FlagpoleSMSService; -import in.gov.chennaicorporation.gccoffice.flagpole.service.RdoService; - -@RestController -@RequestMapping("/gcc/api/flagpoleregistration") -public class FlagPoleApiController { - - @Autowired - private RdoService rdoService; - - @Autowired - private FlagpoleSMSService flagpoleSMSService; - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public FlagPoleApiController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - // new - // @GetMapping("/getAllDetails") - // public ResponseEntity getAllRequestDetails( - // @RequestParam String userLogin, - // @RequestParam(required = false) String startDate, - // @RequestParam(required = false) String endDate) { - - // try { - // List> result = - // rdoService.getAllRequestDetailsByUserLogin( - // userLogin, startDate, endDate); - - // // 🔥 Attach HISTORY per refid - // for (Map record : result) { - // String refid = (String) record.get("refid"); - - // // List> history = - // // rdoService.getRequestHistoryByRefId(refid); - // List> history = - // rdoService.getOfficerFeedbackHistoryByRefId(refid, - // userLogin); - - // record.put("history", history); - // } - - // return ResponseEntity.ok( - // Map.of( - // "status", "success", - // "count", result.size(), - // "data", result)); - - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of( - // "status", "error", - // "message", "Failed to fetch data", - // "error", e.getMessage())); - // } - // } - - // @GetMapping("/getAllDetails") - // public ResponseEntity getAllRequestDetails( - // @RequestParam String gccUserId, - // @RequestParam(required = false) String startDate, - // @RequestParam(required = false) String endDate) { - - // try { - - // // 🔥 Resolve username ONCE (backend trust) - // String username = rdoService.getUsernameByUserId(gccUserId); - // if (username == null) { - // throw new RuntimeException("Invalid gccUserId : " + gccUserId); - // } - - // List> result = - // rdoService.getAllRequestDetailsByUserLogin( - // gccUserId, startDate, endDate); - - // // 🔥 Attach HISTORY per refid (dept-wise) - // for (Map record : result) { - // String refid = (String) record.get("refid"); - - // List> history = - // rdoService.getOfficerFeedbackHistoryByRefId( - // refid, username); - - // record.put("history", history); - // } - - // return ResponseEntity.ok( - // Map.of( - // "status", "success", - // "count", result.size(), - // "data", result)); - - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of( - // "status", "error", - // "message", "Failed to fetch data", - // "error", e.getMessage())); - // } - // } - - @GetMapping("/getAllDetails") - public ResponseEntity getAllRequestDetails( - @RequestParam String gccUserId, - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - try { - - /* 🔥 Normalize input (username OR id → gccuserid) */ - gccUserId = rdoService.resolveGccUserId(gccUserId); - - List> result = rdoService.getAllRequestDetailsByUserLogin(gccUserId, - startDate, endDate); - - /* 🔥 Attach HISTORY per refid */ - for (Map record : result) { - - String refid = (String) record.get("refid"); - - List> history = rdoService.getOfficerFeedbackHistoryByRefId(refid, - gccUserId); - - record.put("history", history); - } - - return ResponseEntity.ok( - Map.of( - "status", "success", - "count", result.size(), - "data", result)); - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of( - "status", "error", - "message", "Failed to fetch data", - "error", e.getMessage())); - } - } - - // old - // @PostMapping("/rdo/updateDecision") - // public ResponseEntity updateRdoDecision( - // @RequestParam String refid, - // @RequestParam String status, - // @RequestParam String remarks, - // @RequestParam String approvedBy) { - - // int count = rdoService.updateRdoDecision(refid, status, remarks, approvedBy); - - // if (count > 0) { - // return ResponseEntity.ok(Map.of( - // "status", "SUCCESS", - // "message", "Decision updated successfully")); - // } else { - // return ResponseEntity.badRequest().body(Map.of( - // "status", "FAILED", - // "message", "Unable to update decision")); - // } - // } - - // @PostMapping("/rdo/updateDecision") - // public ResponseEntity updateRdoDecision( - // @RequestParam String refid, - // @RequestParam String status, - // @RequestParam String remarks, - // @RequestParam String gccUserId) { - - // try { - - // /* 🔥 Normalize username OR id → gccuserid */ - // gccUserId = rdoService.resolveGccUserId(gccUserId); - - // int count = rdoService.updateRdoDecision( - // refid, status, remarks, gccUserId); - - // if (count > 0) { - // return ResponseEntity.ok(Map.of( - // "status", "SUCCESS", - // "message", "Decision updated successfully")); - // } else { - // return ResponseEntity.badRequest().body(Map.of( - // "status", "FAILED", - // "message", "Unable to update decision")); - // } - - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of( - // "status", "ERROR", - // "message", e.getMessage())); - // } - // } - - @PostMapping("/officer/updateDecision") - public ResponseEntity updateOfficerDecision( - @RequestParam String refid, - @RequestParam String status, - @RequestParam String remarks, - @RequestParam String gccUserId, - @RequestParam String username) { - - try { - - /* 🔥 Normalize username OR id → gccuserid */ - gccUserId = rdoService.resolveGccUserId(gccUserId); - - int count = rdoService.updateOfficerDecision( - refid, - status, - remarks, - gccUserId, - username); - - if (count > 0) { - return ResponseEntity.ok(Map.of( - "status", "SUCCESS", - "message", "Decision updated successfully")); - } else { - return ResponseEntity.badRequest().body(Map.of( - "status", "FAILED", - "message", "Unable to update decision")); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of( - "status", "ERROR", - "message", e.getMessage())); - } - } - - // old - // @GetMapping("/getApprovedAndRejectedDetails") - // public ResponseEntity getApprovedRequestDetails( - // @RequestParam String userLogin, - // @RequestParam(required = false) String startDate, - // @RequestParam(required = false) String endDate, - // @RequestParam(required = false) String status) { - - // try { - // List> result = - // rdoService.getRdoApprovedRequestDetailsByUserLogin( - // userLogin, startDate, endDate, status); - - // return ResponseEntity.ok( - // Map.of( - // "status", "success", - // "count", result.size(), - // "data", result)); - - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body( - // Map.of( - // "status", "error", - // "message", "Failed to fetch data", - // "error", e.getMessage())); - // } - // } - - // new - // @GetMapping("/getApprovedAndRejectedDetails") - // public ResponseEntity getApprovedRequestDetails( - // @RequestParam String userLogin, - // @RequestParam(required = false) String startDate, - // @RequestParam(required = false) String endDate, - // @RequestParam(required = false) String status) { - - // try { - // List> result = - // rdoService.getRdoApprovedRequestDetailsByUserLogin( - // userLogin, startDate, endDate, status); - - // // 🔥 Attach HISTORY per refid - // for (Map record : result) { - // String refid = (String) record.get("refid"); - - // List> history = - // rdoService.getRequestHistoryByRefId(refid); - - // record.put("history", history); - // } - - // return ResponseEntity.ok( - // Map.of( - // "status", "success", - // "count", result.size(), - // "data", result)); - - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of( - // "status", "error", - // "message", "Failed to fetch data", - // "error", e.getMessage())); - // } - // } - - // @GetMapping("/getApprovedAndRejectedDetails") - // public ResponseEntity getApprovedRequestDetails( - // @RequestParam String userLogin, - // @RequestParam(required = false) String startDate, - // @RequestParam(required = false) String endDate) { - - // try { - // List> result = - // rdoService.getRdoApprovedRequestDetailsByUserLogin( - // userLogin, startDate, endDate, null); - - // for (Map record : result) { - // String refid = (String) record.get("refid"); - - // // 🔥 NEW: officer feedback history - // List> history = - // rdoService.getOfficerFeedbackHistoryByRefId(refid, - // userLogin); - - // record.put("history", history); - // } - - // return ResponseEntity.ok(Map.of( - // "status", "success", - // "count", result.size(), - // "data", result)); - - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of( - // "status", "error", - // "message", "Failed to fetch data", - // "error", e.getMessage())); - // } - // } - - @GetMapping("/getApprovedAndRejectedDetails") - public ResponseEntity getApprovedRequestDetails( - @RequestParam String gccUserId, - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - try { - - /* 🔥 Normalize username OR id → gccuserid */ - gccUserId = rdoService.resolveGccUserId(gccUserId); - - /* 🔥 Fetch approved & rejected records */ - List> result = rdoService.getRdoApprovedRequestDetailsByUserLogin( - gccUserId, startDate, endDate, null); - - /* 🔥 Attach officer feedback history per refid */ - for (Map record : result) { - - String refid = (String) record.get("refid"); - - List> history = rdoService.getOfficerFeedbackHistoryByRefId(refid, - gccUserId); - - record.put("history", history); - } - - return ResponseEntity.ok(Map.of( - "status", "success", - "count", result.size(), - "data", result)); - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of( - "status", "error", - "message", "Failed to fetch approved/rejected data", - "error", e.getMessage())); - } - } - - @GetMapping("/sendRejectMessage") - public void sendRejectMessage(@RequestParam String mobileNo, @RequestParam String refid) { - flagpoleSMSService.userrequestRejectedsms(mobileNo, refid); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/controller/MainController.java deleted file mode 100644 index 4337ed58..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/controller/MainController.java +++ /dev/null @@ -1,53 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.flagpole.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/flagpole") -@Controller("flagpoleController") -public class MainController { - - @GetMapping("/requestlist") - public String home(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("officer_name", officer_name); - - String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central - model.addAttribute("UserRole", UserRole); - - return "modules/flagpole/requestlist"; - } - - @GetMapping("/approvedandrejectedlist") - public String batches(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("officer_name", officer_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - return "modules/flagpole/approvedandrejectedlist"; - } - - @GetMapping("/reports") - public String dataentry(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername(); - model.addAttribute("officer_name", officer_name); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - return "modules/flagpole/reports"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/FlagpoleSMSService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/FlagpoleSMSService.java deleted file mode 100644 index c1105fc0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/FlagpoleSMSService.java +++ /dev/null @@ -1,133 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.flagpole.service; - -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.flagpole.util.MessageUtility; - -@Service -public class FlagpoleSMSService { - - @Autowired - private AppConfig appConfig; - - @Autowired - private MessageUtility messageUtility; - - private final String key = "pfTEYN6H"; - - public String sendBookingSuccesssms(String mobileNo, String requestId) { - - String message = "Your Flag Pole permission request has been submitted successfully. " - + "Request ID: " + requestId - + ". You will be notified once the status is updated. By GCC"; - - // Encode message and fix colon issue (gateway not decoding %3A) - String encodedMsg = URLEncoder.encode(message, StandardCharsets.UTF_8) - .replace("%3A", ":"); - - String urlString = appConfig.getOtpUrl() - + "from=GCCCRP" - + "&key=" + key - + "&sender=GCCCRP" - + "&to=" + mobileNo - + "&body=" + encodedMsg - + "&entityid=1401572690000011081" - + "&templateid=1407176959297472163"; - - System.out.println("SMS URL:- " + urlString); - - String response = messageUtility.sendSMS(urlString); - System.out.println("SMS RESPONSE:- " + response); - - return response; - } - - public String userrequestApprovedsms(String mobileNo, String requestId) { - - String message = "Your Flag Pole permission request has been approved. " - + "Request ID: " + requestId - + ". Please proceed as per the permitted guidelines. By GCC"; - - // Encode message and fix colon issue (gateway not decoding %3A) - String encodedMsg = URLEncoder.encode(message, StandardCharsets.UTF_8) - .replace("%3A", ":"); - - String urlString = appConfig.getOtpUrl() - + "from=GCCCRP" - + "&key=" + key - + "&sender=GCCCRP" - + "&to=" + mobileNo - + "&body=" + encodedMsg - + "&entityid=1401572690000011081" - + "&templateid=1407176959304753543"; - - System.out.println("SMS URL:- " + urlString); - - String response = messageUtility.sendSMS(urlString); - System.out.println("SMS RESPONSE:- " + response); - - return response; - } - - // public String userrequestRejectedsms(String mobileNo, String requestId) { - - // String message = "Your Flag Pole permission request has been rejected. " - // + "Request ID: " + requestId + ". " - // + "Review the details in the portal - // https://gccservices.in/flagpolesregistration/status\n" - // + "By GCC"; - - // // ONLY encode. Do NOT replace %3A - // String encodedMsg = URLEncoder.encode(message, StandardCharsets.UTF_8); - - // String urlString = appConfig.getOtpUrl() - // + "from=GCCCRP" - // + "&key=" + key - // + "&sender=GCCCRP" - // + "&to=" + mobileNo - // + "&body=" + encodedMsg - // + "&entityid=1401572690000011081" - // + "&templateid=1407176959315374790"; - - // System.out.println("SMS URL:- " + urlString); - - // String response = messageUtility.sendSMS(urlString); - // System.out.println("SMS RESPONSE:- " + response); - - // return response; - // } - - public String userrequestRejectedsms(String mobileNo, String requestId) { - - System.out.println("Rejected Mob Num SMSSSSSSS = " + mobileNo); - String url = "https://gccservices.in/flagpolesregistration/status"; - String message = "Your Flag Pole permission request has been rejected. Request ID: " + requestId - + ". Review the details in the portal " + url + "\r\nBy GCC"; - - String encodedMsg = URLEncoder.encode(message, StandardCharsets.UTF_8); - - System.out.println("encodedMsg:- " + encodedMsg); - - String urlString = appConfig.getOtpUrl() - + "from=GCCCRP" - + "&key=" + key - // + "&sender=GCCCRP" - + "&to=" + mobileNo - + "&body=" + encodedMsg - + "&entityid=1401572690000011081" - + "&templateid=1407176959315374790"; - - System.out.println("SMS URL:- " + urlString); - - String response = messageUtility.sendSMS(urlString); - System.out.println("SMS RESPONSE:- " + response); - - return response; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/RdoService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/RdoService.java deleted file mode 100644 index e9cd564a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/RdoService.java +++ /dev/null @@ -1,1130 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.flagpole.service; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class RdoService { - - private JdbcTemplate mysqlAppJdbcTemplate; - - // @Autowired - // private WhatsappServiceFlagPole whatsappService; - - @Autowired - private FlagpoleSMSService smsService; - - @Autowired - public void setMysqlAppJdbcTemplate( - @Qualifier("mysqlAppDataSource") DataSource dataSource) { - this.mysqlAppJdbcTemplate = new JdbcTemplate(dataSource); - } - - private JdbcTemplate mysqlFlagPoleJdbcTemplate; - - @Autowired - public void setMysqlFlagPoleJdbcTemplate( - @Qualifier("mysqlFlagPoleManagerSystemDataSource") DataSource dataSource) { - this.mysqlFlagPoleJdbcTemplate = new JdbcTemplate(dataSource); - } - - public Long getAppUserIdByGccUserId(String gccUserId) { - - String sql = """ - SELECT id - FROM appusers - WHERE userid = ? - AND isactive = 1 - AND isdelete = 0 - LIMIT 1 - """; - - List list = mysqlAppJdbcTemplate.queryForList(sql, Long.class, gccUserId); - - return list.isEmpty() ? null : list.get(0); - } - - public Long getAppUserIdByUsername(String username) { - - String sql = """ - SELECT id - FROM appusers - WHERE username = ? - """; - - return mysqlAppJdbcTemplate.queryForObject(sql, Long.class, username); - } - - public String getDepartmentNameByUsername(String username) { - - String sql = """ - SELECT department_name - FROM department_login - WHERE user_name = ? - AND is_active = 1 - AND is_delete = 0 - """; - - List list = mysqlFlagPoleJdbcTemplate.queryForList(sql, String.class, username); - return list.isEmpty() ? null : list.get(0); - } - - public Integer getDepartmentIdByUsername(String username) { - - String sql = """ - SELECT dpid - FROM department_login - WHERE user_name = ? - AND is_active = 1 - AND is_delete = 0 - """; - - List list = mysqlFlagPoleJdbcTemplate.queryForList(sql, Integer.class, username); - return list.isEmpty() ? null : list.get(0); - } - - // public List> getOfficerFeedbackHistoryByRefId( - // String refid, - // String username) { - - // Integer deptId = getDepartmentIdByUsername(username); - // String departmentName = getDepartmentNameByUsername(username); - // boolean isRdo = isRdoDepartment(departmentName); - - // StringBuilder sql = new StringBuilder(""" - // SELECT - // ofb.refid, - // dl.department_name, - // ofb.status, - // ofb.remarks, - // ofb.cby, - // DATE_FORMAT(ofb.cdate, '%d-%m-%Y %h:%i %p') AS action_date - // FROM officer_feedback ofb - // JOIN department_login dl - // ON ofb.dept_id = dl.dpid - // WHERE ofb.refid = ? - // AND ofb.is_active = 1 - // AND ofb.is_delete = 0 - // """); - - // List params = new ArrayList<>(); - // params.add(refid); - - // // 🔥 NON-RDO → show ONLY own department history - // if (!isRdo) { - // sql.append(" AND ofb.dept_id = ? "); - // params.add(deptId); - // } - - // sql.append(" ORDER BY ofb.cdate ASC "); - - // return mysqlFlagPoleJdbcTemplate.queryForList(sql.toString(), - // params.toArray()); - // } - - private boolean hasValue(String s) { - return s != null && !s.trim().isEmpty(); - } - - // old - public List> getOfficerFeedbackHistoryByRefId( - String refid, - String gccUserId) { - - /* 🔥 Resolve appuser_id from gccuserid (gcc_apps) */ - Long appUserId = getAppUserIdByGccUserId(gccUserId); - if (appUserId == null) { - throw new RuntimeException("Invalid gccUserId: " + gccUserId); - } - - /* 🔥 Resolve department id (gcc_flag_pole) */ - Integer deptId = getDepartmentIdByUserId(gccUserId); - - /* 🔥 Resolve access (gcc_apps) */ - List> access = getUserAccess(appUserId); - - String zone = null; - String zoneArray = null; - String wardArray = null; - - boolean isRdo = false; - boolean isZonalOfficer = false; - - if (!access.isEmpty()) { - - Map row = access.get(0); - - zone = row.get("zone") != null ? row.get("zone").toString() : null; - // zoneArray = row.get("zonearray") != null ? row.get("zonearray").toString() : - // null; - // wardArray = row.get("wardarray") != null ? row.get("wardarray").toString() : - // null; - - /* ✅ RDO → zonearray + wardarray */ - // if (hasValue(zoneArray) && hasValue(wardArray)) { - // isRdo = true; - // } - - /* ✅ Zonal Officer → zone 01–15 */ - if (hasValue(zone) && zone.matches("^(0[1-9]|1[0-5])$")) { - isZonalOfficer = true; - } - } - - StringBuilder sql = new StringBuilder(""" - SELECT - ofb.refid, - dl.department_name, - ofb.status, - ofb.remarks, - ofb.cby, - DATE_FORMAT(ofb.cdate, '%d-%m-%Y %h:%i %p') AS action_date - FROM officer_feedback ofb - JOIN department_login dl - ON ofb.dept_id = dl.dpid - WHERE ofb.refid = ? - AND ofb.is_active = 1 - AND ofb.is_delete = 0 - """); - - List params = new ArrayList<>(); - params.add(refid); - - /* 🔥 Only NON-RDO & NON-ZONAL are restricted */ - if (!isRdo && !isZonalOfficer) { - sql.append(" AND ofb.dept_id = ? "); - params.add(deptId); - } - - sql.append(" ORDER BY ofb.cdate ASC "); - - return mysqlFlagPoleJdbcTemplate.queryForList(sql.toString(), - params.toArray()); - } - - // to show for all departments - // public List> getOfficerFeedbackHistoryByRefId( - // String refid, - // String gccUserId) { - - // /* 🔥 Just validate gccUserId exists */ - // Long appUserId = getAppUserIdByGccUserId(gccUserId); - // if (appUserId == null) { - // throw new RuntimeException("Invalid gccUserId: " + gccUserId); - // } - - // String sql = """ - // SELECT - // ofb.refid, - // dl.department_name, - // ofb.status, - // ofb.remarks, - // ofb.cby, - // DATE_FORMAT(ofb.cdate, '%d-%m-%Y %h:%i %p') AS action_date - // FROM officer_feedback ofb - // JOIN department_login dl - // ON ofb.dept_id = dl.dpid - // WHERE ofb.refid = ? - // AND ofb.is_active = 1 - // AND ofb.is_delete = 0 - // ORDER BY ofb.cdate ASC - // """; - - // return mysqlFlagPoleJdbcTemplate.queryForList(sql, refid); - // } - - // public int insertOfficerFeedback( - // String refId, - // Integer deptId, - // String status, - // String remarks, - // String createdBy) { - - // String sql = """ - // INSERT INTO officer_feedback - // ( - // refid, - // dept_id, - // status, - // remarks, - // cby, - // cdate, - // is_active, - // is_delete - // ) - // VALUES (?, ?, ?, ?, ?, NOW(), 1, 0) - // """; - - // return mysqlFlagPoleJdbcTemplate.update( - // sql, - // refId, - // deptId, - // status, - // remarks, - // createdBy); - // } - - public int insertOfficerFeedback( - String refId, - Integer deptId, - Integer gccUserId, // login user id - String status, - String remarks, - String username // display username - ) { - - String sql = """ - INSERT INTO officer_feedback - ( - refid, - dept_id, - gcc_user_id, - status, - remarks, - cby, - cdate, - is_active, - is_delete - ) - VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, 0) - """; - - return mysqlFlagPoleJdbcTemplate.update( - sql, - refId, - deptId, - gccUserId, - status, - remarks, - username); - } - - // - // public List> getUserAccess(String userLogin) { - - // String sql = """ - // SELECT lmu.zonearray, lmu.wardarray - // FROM login_mapping_user lmu - // JOIN appusers au ON au.id = lmu.appuser_id - // WHERE au.username = ? - // """; - - // return mysqlAppJdbcTemplate.queryForList(sql, userLogin); - // } - - public List> getUserAccess(Long appUserId) { - - String sql = """ - SELECT lmu.zone,lmu.ward,lmu.zonearray, lmu.wardarray - FROM login_mapping_user lmu - WHERE lmu.appuser_id = ? - """; - - return mysqlAppJdbcTemplate.queryForList(sql, appUserId); - } - - public String resolveGccUserId(String input) { - - // already numeric - if (input.matches("\\d+")) { - return input; - } - - // username → userid - String sql = """ - SELECT userid - FROM appusers - WHERE username = ? - AND isactive = 1 - AND isdelete = 0 - LIMIT 1 - """; - - List list = mysqlAppJdbcTemplate.queryForList(sql, Integer.class, input); - - if (list.isEmpty()) { - throw new RuntimeException("Invalid login user: " + input); - } - - return String.valueOf(list.get(0)); - } - - public String getDepartmentNameByUserId(String gccUserId) { - - String sql = """ - SELECT department_name - FROM department_login - WHERE gcc_user_id = ? - AND is_active = 1 - AND is_delete = 0 - """; - - List list = mysqlFlagPoleJdbcTemplate.queryForList(sql, String.class, gccUserId); - - return list.isEmpty() ? null : list.get(0); - } - - public Integer getDepartmentIdByUserId(String gccUserId) { - - String sql = """ - SELECT dpid - FROM department_login - WHERE gcc_user_id = ? - AND is_active = 1 - AND is_delete = 0 - """; - - List list = mysqlFlagPoleJdbcTemplate.queryForList(sql, Integer.class, gccUserId); - - return list.isEmpty() ? null : list.get(0); - } - - public String getUsernameByUserId(String gccUserId) { - - String sql = """ - SELECT user_name - FROM department_login - WHERE gcc_user_id = ? - AND is_active = 1 - AND is_delete = 0 - """; - - List list = mysqlFlagPoleJdbcTemplate.queryForList(sql, String.class, gccUserId); - - return list.isEmpty() ? null : list.get(0); - } - - public List> getAllRequestDetailsByUserLogin( - String gccUserId, - String startDate, - String endDate) { - - /* 🔥 Resolve appuser_id */ - Long appUserId = getAppUserIdByGccUserId(gccUserId); - if (appUserId == null) { - throw new RuntimeException("Invalid gccUserId: " + gccUserId); - } - - /* 🔥 Resolve department id */ - Integer deptId = getDepartmentIdByUserId(gccUserId); - if (deptId == null) { - throw new RuntimeException("Department mapping missing for gccUserId: " + gccUserId); - } - - /* 🔥 Resolve access */ - List> access = getUserAccess(appUserId); - - String zone = null; - String zoneArray = null; - String wardArray = null; - - boolean isRdo = false; - boolean isZonalOfficer = false; - - if (!access.isEmpty()) { - - zone = (String) access.get(0).get("zone"); - zoneArray = (String) access.get(0).get("zonearray"); - wardArray = (String) access.get(0).get("wardarray"); - - // RDO → zonearray + wardarray - if (hasValue(zoneArray) && hasValue(wardArray)) { - isRdo = true; - } - // Zonal → single zone - else if (hasValue(zone)) { - isZonalOfficer = true; - } - } - - StringBuilder sql = new StringBuilder(""" - SELECT - urd.id, - urd.refid, - urd.applicant_name, - urd.mobile_number, - urd.applicant_address, - urd.event_desc, - urd.cdate, - urd.event_date, - urd.ae_status, - urd.rdo_status, - urd.final_status, - urd.no_of_days, - - sd.street_name, - sd.zone, - sd.ward, - sd.no_of_poles, - sd.height, - sd.street_cost, - - fm.flag_material_name AS flag_material, - pm.pole_material_name AS pole_material, - - urd.total_cost, - et.event_name - - FROM user_request_details urd - LEFT JOIN street_details sd - ON urd.refid = sd.refid - AND sd.is_active = 1 - AND sd.is_delete = 0 - LEFT JOIN event_type et ON urd.event_id = et.id - LEFT JOIN flag_material fm ON sd.flag_material_id = fm.id - LEFT JOIN pole_material pm ON sd.pole_material_id = pm.id - WHERE 1 = 1 - """); - - List params = new ArrayList<>(); - - /* 🔥 1. REMOVE RDO-FINALIZED */ - // sql.append(" AND (urd.rdo_status IS NULL OR urd.rdo_status = '') "); - sql.append(" AND (urd.final_status IS NULL OR urd.final_status = '') "); - - /* 🔥 2. REMOVE ALREADY DECIDED BY SAME DEPT */ - sql.append(""" - AND urd.refid NOT IN ( - SELECT ofb.refid - FROM officer_feedback ofb - WHERE ofb.dept_id = ? - AND ofb.status IN ('APPROVED','REJECTED') - AND ofb.is_active = 1 - AND ofb.is_delete = 0 - ) - """); - params.add(deptId); - - /* 🔥 3a. RDO → multi zone + ward */ - if (isRdo) { - sql.append(" AND FIND_IN_SET(sd.zone, ?) "); - sql.append(" AND FIND_IN_SET(sd.ward, ?) "); - params.add(zoneArray); - params.add(wardArray); - } - - /* 🔥 3b. ZONAL → single zone */ - else if (isZonalOfficer) { - sql.append(" AND sd.zone = ? "); - params.add(zone); - } - - /* 🔹 DATE FILTER */ - if (hasValue(startDate) && hasValue(endDate)) { - - sql.append(" AND DATE(urd.event_date) BETWEEN ? AND ? "); - params.add(startDate); - params.add(endDate); - - } else if (hasValue(startDate)) { - - sql.append(" AND DATE(urd.event_date) = ? "); - params.add(startDate); - } - - sql.append(""" - ORDER BY urd.event_date ASC, - urd.cdate ASC, - urd.refid ASC, - sd.id ASC - """); - - List> rows = mysqlFlagPoleJdbcTemplate.queryForList(sql.toString(), params.toArray()); - - /* 🔥 GROUP BY REFID */ - Map> resultMap = new LinkedHashMap<>(); - - for (Map row : rows) { - - String refid = (String) row.get("refid"); - - Map request = resultMap.computeIfAbsent(refid, k -> { - Map map = new LinkedHashMap<>(); - map.put("refid", row.get("refid")); - map.put("applicant_name", row.get("applicant_name")); - map.put("mobile_number", row.get("mobile_number")); - map.put("applicant_address", row.get("applicant_address")); - map.put("event_desc", row.get("event_desc")); - map.put("event_date", row.get("event_date")); - map.put("cdate", row.get("cdate")); - map.put("ae_status", row.get("ae_status")); - map.put("rdo_status", row.get("rdo_status")); - map.put("final_status", row.get("final_status")); - map.put("no_of_days", row.get("no_of_days")); - map.put("event_name", row.get("event_name")); - map.put("total_cost", row.get("total_cost")); - map.put("streets", new ArrayList<>()); - return map; - }); - - Map street = new LinkedHashMap<>(); - street.put("street_name", row.get("street_name")); - street.put("zone", row.get("zone")); - street.put("ward", row.get("ward")); - street.put("no_of_poles", row.get("no_of_poles")); - street.put("height", row.get("height")); - street.put("street_cost", row.get("street_cost")); - street.put("flag_material", row.get("flag_material")); - street.put("pole_material", row.get("pole_material")); - - ((List>) request.get("streets")).add(street); - } - - return new ArrayList<>(resultMap.values()); - } - - // old with rdo and zonal officer final - // @Transactional - // public int updateOfficerDecision( - // String refId, - // String status, - // String remarks, - // String gccUserId, - // String username) { - - // /* 🔹 Resolve appuser_id */ - // Long appUserId = getAppUserIdByGccUserId(gccUserId); - // if (appUserId == null) { - // throw new RuntimeException("Invalid gccUserId"); - // } - - // /* 🔹 Resolve department */ - // Integer deptId = getDepartmentIdByUserId(gccUserId); - // if (deptId == null) { - // throw new RuntimeException("User not mapped to department"); - // } - - // /* 🔹 Access */ - // List> access = getUserAccess(appUserId); - - // String zone = null; - // String zoneArray = null; - // String wardArray = null; - - // boolean isRdo = false; - // boolean isZonalOfficer = false; - - // if (!access.isEmpty()) { - - // Map row = access.get(0); - - // zone = row.get("zone") != null ? row.get("zone").toString() : null; - // zoneArray = row.get("zonearray") != null ? row.get("zonearray").toString() : - // null; - // wardArray = row.get("wardarray") != null ? row.get("wardarray").toString() : - // null; - - // /* ✅ RDO → zonearray + wardarray */ - // if (hasValue(zoneArray) && hasValue(wardArray)) { - // isRdo = true; - // } - - // /* ✅ Zonal Officer → zone 01–15 */ - // if (hasValue(zone) && zone.matches("^(0[1-9]|1[0-5])$")) { - // isZonalOfficer = true; - // } - // } - - // /* - // * ===================================================== - // * 🔹 INSERT FEEDBACK (ALL USERS) - // * ===================================================== - // */ - - // insertOfficerFeedback( - // refId, - // deptId, - // Integer.valueOf(gccUserId), - // status, - // remarks, - // username); - - // /* - // * ===================================================== - // * 🔹 RDO FLOW - // * ===================================================== - // */ - - // if (isRdo) { - - // String historySql = """ - // INSERT INTO user_request_details_history - // ( - // refid, applicant_name, mobile_number, applicant_address, - // event_id, event_date, no_of_days, total_poles, total_cost, - // ae_status, rdo_status, rdo_remarks, - // approved_by, approved_date, - // payment_status, refund_status, booking_status, cdate - // ) - // SELECT - // refid, applicant_name, mobile_number, applicant_address, - // event_id, event_date, no_of_days, total_poles, total_cost, - // ae_status, ?, ?, ?, NOW(), - // payment_status, refund_status, booking_status, NOW() - // FROM user_request_details - // WHERE refid = ? - // """; - - // mysqlFlagPoleJdbcTemplate.update(historySql, status, remarks, gccUserId, - // refId); - - // String updateSql = """ - // UPDATE user_request_details - // SET - // rdo_status = ?, - // rdo_remarks = ?, - // approved_by = ?, - // rdo_updated_date = NOW() - // WHERE refid = ? - // """; - - // return mysqlFlagPoleJdbcTemplate.update(updateSql, status, remarks, - // gccUserId, refId); - // } - - // /* - // * ===================================================== - // * 🔹 ZONAL OFFICER FLOW (FINAL) - // * ===================================================== - // */ - - // if (isZonalOfficer) { - - // String historySql = """ - // INSERT INTO user_request_details_history - // ( - // refid, applicant_name, mobile_number, applicant_address, - // event_id, event_date, no_of_days, total_poles, total_cost, - // ae_status, rdo_status, rdo_remarks, - // final_status, final_remarks, final_approved_by, final_approved_date, - // payment_status, refund_status, booking_status, cdate - // ) - // SELECT - // refid, applicant_name, mobile_number, applicant_address, - // event_id, event_date, no_of_days, total_poles, total_cost, - // ae_status, rdo_status, rdo_remarks, - // ?, ?, ?, NOW(), - // payment_status, refund_status, booking_status, NOW() - // FROM user_request_details - // WHERE refid = ? - // """; - - // mysqlFlagPoleJdbcTemplate.update(historySql, status, remarks, gccUserId, - // refId); - - // String updateSql = """ - // UPDATE user_request_details - // SET - // final_status = ?, - // final_remarks = ?, - // final_approved_by = ?, - // final_approved_date = NOW() - // WHERE refid = ? - // """; - - // return mysqlFlagPoleJdbcTemplate.update(updateSql, status, remarks, - // gccUserId, refId); - // } - - // /* - // * ===================================================== - // * 🔹 OTHER DEPARTMENTS → FEEDBACK ONLY - // * ===================================================== - // */ - - // return 1; - // } - - @Transactional - public int updateOfficerDecision( - String refId, - String status, - String remarks, - String gccUserId, - String username) { - - /* 🔹 Resolve appuser_id */ - Long appUserId = getAppUserIdByGccUserId(gccUserId); - if (appUserId == null) { - throw new RuntimeException("Invalid gccUserId"); - } - - /* 🔹 Resolve department */ - Integer deptId = getDepartmentIdByUserId(gccUserId); - if (deptId == null) { - throw new RuntimeException("User not mapped to department"); - } - - /* 🔹 Access */ - List> access = getUserAccess(appUserId); - - String zone = null; - String zoneArray = null; - String wardArray = null; - - boolean isRdo = false; - boolean isZonalOfficer = false; - - if (!access.isEmpty()) { - - Map row = access.get(0); - - zone = row.get("zone") != null ? row.get("zone").toString() : null; - zoneArray = row.get("zonearray") != null ? row.get("zonearray").toString() : null; - wardArray = row.get("wardarray") != null ? row.get("wardarray").toString() : null; - - if (hasValue(zoneArray) && hasValue(wardArray)) { - isRdo = true; - } - - if (hasValue(zone) && zone.matches("^(0[1-9]|1[0-5])$")) { - isZonalOfficer = true; - } - } - - /* - * ===================================================== - * 🔐 Check if already FINALIZED - * ===================================================== - */ - - String finalStatus = mysqlFlagPoleJdbcTemplate.queryForObject( - "SELECT final_status FROM user_request_details WHERE refid = ?", - String.class, - refId); - - if (finalStatus != null && !finalStatus.isBlank() && !isZonalOfficer) { - throw new RuntimeException("Request already finalized by Zonal Officer"); - } - - /* - * ===================================================== - * 🔹 INSERT FEEDBACK (ALL USERS) - * ===================================================== - */ - - insertOfficerFeedback( - refId, - deptId, - Integer.valueOf(gccUserId), - status, - remarks, - username); - - /* - * ===================================================== - * 🔹 ZONAL OFFICER FLOW (ONLY FINAL AUTHORITY) - * ===================================================== - */ - - if (isZonalOfficer) { - - String historySql = """ - INSERT INTO user_request_details_history - ( - refid, applicant_name, mobile_number, applicant_address, - event_id, event_date, no_of_days, total_poles, total_cost, - ae_status, rdo_status, rdo_remarks, - final_status, final_remarks, final_approved_by, final_approved_date, - payment_status, refund_status, booking_status, cdate - ) - SELECT - refid, applicant_name, mobile_number, applicant_address, - event_id, event_date, no_of_days, total_poles, total_cost, - ae_status, rdo_status, rdo_remarks, - ?, ?, ?, NOW(), - payment_status, refund_status, booking_status, NOW() - FROM user_request_details - WHERE refid = ? - """; - - mysqlFlagPoleJdbcTemplate.update(historySql, status, remarks, gccUserId, refId); - - String updateSql = """ - UPDATE user_request_details - SET - final_status = ?, - final_remarks = ?, - final_approved_by = ?, - final_approved_date = NOW() - WHERE refid = ? - """; - - // return mysqlFlagPoleJdbcTemplate.update(updateSql, status, remarks, - // gccUserId, refId); - - int updated = mysqlFlagPoleJdbcTemplate.update(updateSql, status, remarks, gccUserId, refId); - - // ================= SEND SMS AFTER FINAL APPROVAL ================= - if ("APPROVED".equalsIgnoreCase(status)) { - - try { - - String mobileNo = mysqlFlagPoleJdbcTemplate.queryForObject(""" - SELECT mobile_number - FROM user_request_details - WHERE refid = ? - """, String.class, refId); - - if (mobileNo != null && !mobileNo.isBlank()) { - smsService.userrequestApprovedsms(mobileNo, refId); - } - - } catch (Exception e) { - System.err.println("Approved SMS failed for requestId: " + refId); - e.printStackTrace(); - } - } - - if ("REJECTED".equalsIgnoreCase(status)) { - - try { - System.out.println("Rejected RefID = " + refId); - - String mobileNo = mysqlFlagPoleJdbcTemplate.queryForObject(""" - SELECT mobile_number - FROM user_request_details - WHERE refid = ? - """, String.class, refId); - - if (mobileNo != null && !mobileNo.isBlank()) { - System.out.println("Rejected Mob Num = " + mobileNo); - smsService.userrequestRejectedsms(mobileNo, refId); - } - - } catch (Exception e) { - System.err.println("Approved SMS failed for requestId: " + refId); - e.printStackTrace(); - } - } - // ================================================================ - - return updated; - - } - - /* - * ===================================================== - * RDO FLOW (ONLY RDO FIELDS) - * ===================================================== - */ - - if (isRdo) { - - String historySql = """ - INSERT INTO user_request_details_history - ( - refid, applicant_name, mobile_number, applicant_address, - event_id, event_date, no_of_days, total_poles, total_cost, - ae_status, rdo_status, rdo_remarks, - approved_by, approved_date, - payment_status, refund_status, booking_status, cdate - ) - SELECT - refid, applicant_name, mobile_number, applicant_address, - event_id, event_date, no_of_days, total_poles, total_cost, - ae_status, ?, ?, ?, NOW(), - payment_status, refund_status, booking_status, NOW() - FROM user_request_details - WHERE refid = ? - """; - - mysqlFlagPoleJdbcTemplate.update(historySql, status, remarks, gccUserId, refId); - - String updateSql = """ - UPDATE user_request_details - SET - rdo_status = ?, - rdo_remarks = ?, - approved_by = ?, - rdo_updated_date = NOW() - WHERE refid = ? - """; - - return mysqlFlagPoleJdbcTemplate.update(updateSql, status, remarks, gccUserId, refId); - } - - return 1; - } - - public List> getRdoApprovedRequestDetailsByUserLogin( - String gccUserId, - String startDate, - String endDate, - String status) { - - /* 🔥 Resolve appuser_id */ - Long appUserId = getAppUserIdByGccUserId(gccUserId); - if (appUserId == null) { - throw new RuntimeException("Invalid gccUserId: " + gccUserId); - } - - /* 🔥 Resolve department */ - Integer deptId = getDepartmentIdByUserId(gccUserId); - if (deptId == null) { - throw new RuntimeException("Department mapping missing for gccUserId: " + gccUserId); - } - - /* 🔥 Resolve access */ - List> access = getUserAccess(appUserId); - - String zone = null; - String zoneArray = null; - String wardArray = null; - - boolean isRdo = false; - boolean isZonalOfficer = false; - - if (!access.isEmpty()) { - zone = (String) access.get(0).get("zone"); - zoneArray = (String) access.get(0).get("zonearray"); - wardArray = (String) access.get(0).get("wardarray"); - - if (hasValue(zoneArray) && hasValue(wardArray)) { - isRdo = true; - } else if (hasValue(zone)) { - isZonalOfficer = true; - } - } - - StringBuilder sql = new StringBuilder(""" - SELECT - urd.id, - urd.refid, - urd.applicant_name, - urd.mobile_number, - urd.applicant_address, - urd.event_desc, - urd.cdate, - urd.event_date, - urd.ae_status, - urd.rdo_status, - urd.rdo_remarks, - urd.no_of_days, - - sd.street_name, - sd.zone, - sd.ward, - sd.no_of_poles, - sd.street_cost, - sd.height, - - fm.flag_material_name AS flag_material, - pm.pole_material_name AS pole_material, - - urd.total_cost, - et.event_name, - - ofb.status AS officer_status, - ofb.remarks AS officer_remarks - - FROM officer_feedback ofb - JOIN user_request_details urd - ON urd.refid = ofb.refid - LEFT JOIN street_details sd - ON urd.refid = sd.refid - AND sd.is_active = 1 - AND sd.is_delete = 0 - LEFT JOIN event_type et ON urd.event_id = et.id - LEFT JOIN flag_material fm ON sd.flag_material_id = fm.id - LEFT JOIN pole_material pm ON sd.pole_material_id = pm.id - WHERE ofb.dept_id = ? - AND ofb.status IN ('APPROVED','REJECTED') - AND ofb.is_active = 1 - AND ofb.is_delete = 0 - """); - - List params = new ArrayList<>(); - params.add(deptId); - - /* 🔹 Optional status */ - if (hasValue(status)) { - sql.append(" AND ofb.status = ? "); - params.add(status); - } - - /* 🔹 RDO → zone + ward */ - if (isRdo) { - sql.append(" AND FIND_IN_SET(sd.zone, ?) "); - sql.append(" AND FIND_IN_SET(sd.ward, ?) "); - params.add(zoneArray); - params.add(wardArray); - } - /* 🔹 Zonal → only zone */ - else if (isZonalOfficer) { - sql.append(" AND sd.zone = ? "); - params.add(zone); - } - - /* 🔹 Date */ - if (hasValue(startDate) && hasValue(endDate)) { - - sql.append(" AND DATE(urd.event_date) BETWEEN ? AND ? "); - params.add(startDate); - params.add(endDate); - - } else if (hasValue(startDate)) { - - sql.append(" AND DATE(urd.event_date) = ? "); - params.add(startDate); - } - - sql.append(" ORDER BY ofb.cdate DESC, urd.refid, sd.id "); - - List> rows = mysqlFlagPoleJdbcTemplate.queryForList(sql.toString(), params.toArray()); - - /* 🔥 GROUP BY REFID */ - Map> resultMap = new LinkedHashMap<>(); - - for (Map row : rows) { - - String refid = (String) row.get("refid"); - - Map request = resultMap.computeIfAbsent(refid, k -> { - Map map = new LinkedHashMap<>(); - map.put("refid", row.get("refid")); - map.put("applicant_name", row.get("applicant_name")); - map.put("mobile_number", row.get("mobile_number")); - map.put("applicant_address", row.get("applicant_address")); - map.put("event_desc", row.get("event_desc")); - map.put("cdate", row.get("cdate")); - map.put("event_date", row.get("event_date")); - map.put("ae_status", row.get("ae_status")); - map.put("rdo_status", row.get("rdo_status")); - map.put("rdo_remarks", row.get("rdo_remarks")); - map.put("no_of_days", row.get("no_of_days")); - map.put("event_name", row.get("event_name")); - map.put("total_cost", row.get("total_cost")); - map.put("officer_status", row.get("officer_status")); - map.put("officer_remarks", row.get("officer_remarks")); - map.put("streets", new ArrayList<>()); - return map; - }); - - Map street = new LinkedHashMap<>(); - street.put("street_name", row.get("street_name")); - street.put("zone", row.get("zone")); - street.put("ward", row.get("ward")); - street.put("no_of_poles", row.get("no_of_poles")); - street.put("height", row.get("height")); - street.put("street_cost", row.get("street_cost")); - street.put("flag_material", row.get("flag_material")); - street.put("pole_material", row.get("pole_material")); - - ((List>) request.get("streets")).add(street); - } - - return new ArrayList<>(resultMap.values()); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/SmsServiceFlagPole.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/SmsServiceFlagPole.java deleted file mode 100644 index 8ea2e4c6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/SmsServiceFlagPole.java +++ /dev/null @@ -1,38 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.flagpole.service; - -import java.net.HttpURLConnection; -import java.net.URL; - -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class SmsServiceFlagPole { - - public String sendMsg(String msgUrl) { - - String response = ""; - try { - HttpURLConnection connection = null; - - URL url = new URL(msgUrl); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = responseCode + ""; - System.out.println("Response Code: " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - - return response; - } - - public String sendSMS(String SMS_Url) { - RestTemplate restTemplate = new RestTemplate(); - String response = restTemplate.getForObject(SMS_Url, String.class); - return response; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/WhatsappServiceFlagPole.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/WhatsappServiceFlagPole.java deleted file mode 100644 index 0ebad469..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/service/WhatsappServiceFlagPole.java +++ /dev/null @@ -1,31 +0,0 @@ -// package in.gov.chennaicorporation.gccoffice.flagpole.service; - -// import org.springframework.beans.factory.annotation.Autowired; -// import org.springframework.stereotype.Service; - -// @Service -// public class WhatsappServiceFlagPole { - -// @Autowired -// private SMSService smsService; - -// // c & d waste template after user register -// public void sendOfficerApprovedWhatsappMessage(String refId, String -// mobileNumber) { -// try { - -// String apiUrl = -// "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" -// + mobileNumber -// + -// "&v=1.1&format=json&msg_type=IMAGE&method=SENDMEDIAMESSAGE&caption=Welcome+to+Greater+Chennai+Corporation%2C+%0A%0AYour+Registered+ID+is+%2A${registerId}%2A+.%0AYour+C%26D+waste+registration+has+been+approved+successfully.+%0A%0AFor+downloading+your+ID+card%2C+kindly+click+on+the+button+below+%F0%9F%91%87&media_url=https%3A%2F%2Fres.cloudinary.com%2Fdpub5muar%2Fimage%2Fupload%2Fv1729597847%2Fq2ihjs99puhhwkjzajyo.png&isTemplate=true&buttonUrlParam=userdetail%3Fregister_id%3D" -// + refId; - -// System.out.println("WhatsApp API URL: " + apiUrl); // Optional debug -// smsService.sendMsg(apiUrl); - -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/util/MessageUtility.java b/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/util/MessageUtility.java deleted file mode 100644 index 09b9aaa7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/flagpole/util/MessageUtility.java +++ /dev/null @@ -1,41 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.flagpole.util; - -import java.net.HttpURLConnection; -import java.net.URL; - -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class MessageUtility { - - public String sendMsg(String msgUrl) { - System.out.println("Whatsapp URL :-" + msgUrl); - - String response = ""; - try { - HttpURLConnection connection = null; - - URL url = new URL(msgUrl); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = responseCode + ""; - System.out.println("Response Code: " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - - return response; - } - - public String sendSMS(String SMS_Url) { - // System.out.println("SMS URL:- " + SMS_Url); - RestTemplate restTemplate = new RestTemplate(); - String response = restTemplate.getForObject(SMS_Url, String.class); - return response; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/.DS_Store deleted file mode 100644 index c6825888..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/controller/APIController.java deleted file mode 100644 index e7131bae..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/controller/APIController.java +++ /dev/null @@ -1,59 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.garbagecollection.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("/api/garbagecollection") -@RestController("garbageCollectionRestController") -public class APIController { - private final RestTemplate restTemplate; - private final AppConfig appConfig; - String bodyMessage = ""; - @Autowired - public APIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @GetMapping(value = "/getGarbageDetails") - public String getGarbageDetails(@RequestParam String requestid) { - ResponseEntity response = restTemplate.getForEntity(appConfig.garbageCollection+"/api/getRequestById?requestid={requestid}", String.class,requestid); - bodyMessage = response.getBody().trim(); - - return bodyMessage; - } - - @PostMapping(value = "/saveStatus") - public String saveStatus(@RequestParam("status") String status, @RequestParam("comments") String comments, @RequestParam("request_id") String request_id) { - //System.out.println("I AM IN"); - ResponseEntity response = restTemplate.getForEntity(appConfig.garbageCollection+"/api/saveStatus?status={status}&comments={comments}&request_id={request_id}", String.class,status,comments,request_id); - bodyMessage = response.getBody().trim(); - - return bodyMessage; - } - - @GetMapping(value = "/getStatus") - public String getStatus(@RequestParam String requestid) { - ResponseEntity response = restTemplate.getForEntity(appConfig.garbageCollection+"/api/getStatusByRequestId?requestid={requestid}", String.class,requestid); - bodyMessage = response.getBody().trim(); - - return bodyMessage; - } - - @GetMapping(value = "/getStatusById") - public String getStatusById(@RequestParam String statusid) { - ResponseEntity response = restTemplate.getForEntity(appConfig.garbageCollection+"/api/getStatusById?request_status_id={statusid}", String.class,statusid); - bodyMessage = response.getBody().trim(); - - return bodyMessage; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/controller/MainController.java deleted file mode 100644 index 867516f1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/controller/MainController.java +++ /dev/null @@ -1,73 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.garbagecollection.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.garbagecollection.modeldata.Request; - -@RequestMapping("/garbagecollection") -@Controller("garbageCollectionController") -public class MainController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return "modules/garbagecollection/index"; - } - - @GetMapping("/request-create") - public String category(Model model) { - - //String apiUrl = appConfig.qrAssetFeedback + "/api/category"; - //AssetCategory[] assetCategoryList = restTemplate.getForObject(apiUrl, AssetCategory[].class); - - //model.addAttribute("assetcategorylist",assetCategoryList); - return "modules/taxcollection/request-create"; - } - - @GetMapping("/request-new") - public String newRequestList(Model model) { - String apiUrl = appConfig.garbageCollection+"/api/getRequest"; - Request[] requestList = restTemplate.getForObject(apiUrl, Request[].class); - model.addAttribute("requestlist",requestList); - return "modules/garbagecollection/request-new"; - } - - @GetMapping("/request-pending") - public String pendingRequestList(Model model) { - String apiUrl = appConfig.garbageCollection+"/api/getPendingRequest"; - Request[] requestList = restTemplate.getForObject(apiUrl, Request[].class); - model.addAttribute("requestlist",requestList); - return "modules/garbagecollection/request-pending"; - } - - @GetMapping("/request-completed") - public String completedRequestList(Model model) { - String apiUrl = appConfig.garbageCollection+"/api/getCompletedRequest"; - Request[] requestList = restTemplate.getForObject(apiUrl, Request[].class); - model.addAttribute("requestlist",requestList); - return "modules/garbagecollection/request-completed"; - } - - @GetMapping("/request-outofscope") - public String outofscopeRequestList(Model model) { - String apiUrl = appConfig.garbageCollection+"/api/getOutOfScopeRequest"; - Request[] requestList = restTemplate.getForObject(apiUrl, Request[].class); - model.addAttribute("requestlist",requestList); - return "modules/garbagecollection/request-outofscope"; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/.DS_Store deleted file mode 100644 index 72aa13e6..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/Request.java b/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/Request.java deleted file mode 100644 index 888bdf7f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/Request.java +++ /dev/null @@ -1,242 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.garbagecollection.modeldata; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -public class Request { - - private Integer requestId; - private String name; - private String mobile; - private String email; - private String address; - private String landmark; - private String zone; - private String division; - private String area; - private String locality; - private String street; - private String latitude; - private String longitude; - private String requestType; - private String garbageCategory; - private String status; - private String statusId; - private Boolean isDelete; - private Boolean isActive; - private Integer createdBy; - private String cDate; - - @JsonCreator - public Request(@JsonProperty("request_id") Integer requestId, - @JsonProperty("name") String name, - @JsonProperty("mobile") String mobile, - @JsonProperty("email") String email, - @JsonProperty("address") String address, - @JsonProperty("landmark") String landmark, - @JsonProperty("zone") String zone, - @JsonProperty("division") String division, - @JsonProperty("area") String area, - @JsonProperty("locality") String locality, - @JsonProperty("street") String street, - @JsonProperty("latitude") String latitude, - @JsonProperty("longitude") String longitude, - @JsonProperty("request_type") String requestType, - @JsonProperty("garbage_category") String garbageCategory, - @JsonProperty("status") String status, - @JsonProperty("statusid") String statusId, - @JsonProperty("isdelete") Boolean isDelete, - @JsonProperty("isactive") Boolean isActive, - @JsonProperty("created_by") Integer createdBy, - @JsonProperty("cdate") String cDate) { - this.requestId = requestId; - this.name = name; - this.mobile = mobile; - this.email = email; - this.address = address; - this.landmark = landmark; - this.zone = zone; - this.division = division; - this.area = area; - this.locality = locality; - this.street = street; - this.latitude = latitude; - this.longitude = longitude; - this.requestType = requestType; - this.garbageCategory = garbageCategory; - this.status = status; - this.statusId = statusId; - this.garbageCategory = garbageCategory; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Integer getRequestId() { - return requestId; - } - - public void setRequestId(Integer requestId) { - this.requestId = requestId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getMobile() { - return mobile; - } - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getLandmark() { - return landmark; - } - - public void setLandmark(String landmark) { - this.landmark = landmark; - } - - public String getZone() { - return zone; - } - - public void setZone(String zone) { - this.zone = zone; - } - - public String getDivision() { - return division; - } - - public void setDivision(String division) { - this.division = division; - } - - public String getArea() { - return area; - } - - public void setArea(String area) { - this.area = area; - } - - public String getLocality() { - return locality; - } - - public void setLocality(String locality) { - this.locality = locality; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getLatitude() { - return latitude; - } - - public void setLatitude(String latitude) { - this.latitude = latitude; - } - - public String getLongitude() { - return longitude; - } - - public void setLongitude(String longitude) { - this.longitude = longitude; - } - - public String getRequestType() { - return requestType; - } - - public void setRequestType(String requestType) { - this.requestType = requestType; - } - - public String getGarbageCategory() { - return garbageCategory; - } - - public void setGarbageCategory(String garbageCategory) { - this.garbageCategory = garbageCategory; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getStatusId() { - return statusId; - } - - public void setStatusId(String statusId) { - this.statusId = statusId; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - public Integer getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/RequestStatus.java b/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/RequestStatus.java deleted file mode 100644 index 80dd9709..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/garbagecollection/modeldata/RequestStatus.java +++ /dev/null @@ -1,100 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.garbagecollection.modeldata; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -public class RequestStatus { - - private Integer statusId; - private Integer requestId; - private String status; - private String comments; - private Boolean isDelete; - private Boolean isActive; - private Integer createdBy; - private String cDate; - - @JsonCreator - public RequestStatus(@JsonProperty("request_status_id") Integer statusId, - @JsonProperty("request_id") Integer requestId, - @JsonProperty("status") String status, - @JsonProperty("comments") String comments, - @JsonProperty("isdelete") Boolean isDelete, - @JsonProperty("isactive") Boolean isActive, - @JsonProperty("created_by") Integer createdBy, - @JsonProperty("cdate") String cDate) { - this.statusId = statusId; - this.requestId = requestId; - this.status = status; - this.comments = comments; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Integer getStatusId() { - return statusId; - } - - public void setStatusId(Integer statusId) { - this.statusId = statusId; - } - - public Integer getRequestId() { - return requestId; - } - - public void setRequestId(Integer requestId) { - this.requestId = requestId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getComments() { - return comments; - } - - public void setComments(String comments) { - this.comments = comments; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - public Integer getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/.DS_Store deleted file mode 100644 index 4a3b5d22..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/CreateMeetingApicontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/CreateMeetingApicontroller.java deleted file mode 100644 index d0c41210..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/CreateMeetingApicontroller.java +++ /dev/null @@ -1,101 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.controller; - -import java.time.LocalDate; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.http.ResponseEntity; -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.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.greencommittee.service.CreateMeetingService; - -@RestController -@RequestMapping("/gcc/api/greencommittee/createmeeting") -public class CreateMeetingApicontroller { - - @Autowired - private AppConfig appConfig; - - @Autowired - private CreateMeetingService createMeetingService; - - - - @PostMapping("/savemeeting") - public ResponseEntity> saveEventWithFile( - @RequestParam("eventName") String eventName, - @RequestParam("eventDate") String eventDateStr, - @RequestParam("file") MultipartFile file, - @RequestParam("cby") String cby) { - - Map response = new HashMap<>(); - - try { - - if (file == null || file.isEmpty()) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "File is required"); - return ResponseEntity.badRequest().body(response); - } - - if (eventName == null || eventName.trim().isEmpty()) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Event name cannot be empty"); - return ResponseEntity.badRequest().body(response); - } - - LocalDate eventDate; - try { - eventDate = LocalDate.parse(eventDateStr); - } catch (Exception ex) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Invalid date format (use yyyy-MM-dd)"); - return ResponseEntity.badRequest().body(response); - } - - - String eventFilePath = createMeetingService.fileUpload(file, "meeting_file"); - - if (eventFilePath == null) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "File upload failed"); - return ResponseEntity.internalServerError().body(response); - } - - - String saveStatus = createMeetingService.insertEvent(eventName, eventDate, eventFilePath, cby); - - if (saveStatus == null || saveStatus.equalsIgnoreCase("error")) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Failed to save meeting details"); - return ResponseEntity.internalServerError().body(response); - } - - - response.put("status", true); - response.put("message", "success"); - response.put("description", "Details saved successfully"); - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Internal server error: " + e.getMessage()); - return ResponseEntity.internalServerError().body(response); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/Maincontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/Maincontroller.java deleted file mode 100644 index 379acc28..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/Maincontroller.java +++ /dev/null @@ -1,92 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.greencommittee.service.DashboardService; -import in.gov.chennaicorporation.gccoffice.greencommittee.service.PendinglistService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/greencommittee") -@Controller("greencommitteeMainController") -public class Maincontroller { - - @Autowired - private LoginUserInfo loginUserInfo; - - @Autowired - private PendinglistService pendinglistService; - - @Autowired - private DashboardService dashboardService; - - @GetMapping("/dashboard") - public String viewdashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/greencommittee/dashboard"; - } - - @GetMapping("/createmeeting") - public String viewcreatemeeting(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/greencommittee/createmeeting"; - } - - @GetMapping("/pendinglist") - public String viewpendinglist(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/greencommittee/pendinglist"; - } - - @GetMapping("/monitoring") - public String viewmonitoring(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/greencommittee/monitoring"; - } - - @GetMapping("/reports") - public String viewreports(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/greencommittee/reports"; - } - - @GetMapping("/treepruningreports") - public String viewtreepruningreports(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/greencommittee/treepruningreports"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/MonitoringApicontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/MonitoringApicontroller.java deleted file mode 100644 index c4ab0abf..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/MonitoringApicontroller.java +++ /dev/null @@ -1,51 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.controller; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.greencommittee.service.MonitoringService; - -@RestController -@RequestMapping("/gcc/api/greencommittee/monitoring") -public class MonitoringApicontroller { - - @Autowired - private MonitoringService monitoringService; - - @GetMapping("/getgreencommitteelist") - public List> getgreencommitteelist(@RequestParam String meetingid, - @RequestParam String zones) { - - List refnums = monitoringService.getrefnums(meetingid, zones); - System.out.println("refnums="+refnums); - - - List> finalList = new ArrayList<>(); - - if (refnums.isEmpty()) { - return Collections.emptyList(); - } - - for (String ref : refnums) { - Map data = monitoringService.getlistdata(ref); - if (data != null && !data.isEmpty()) { - finalList.add(data); - } - } - - return finalList; - } - - @GetMapping("/getdetailsbyrefid") - public Map getdetailsbyrefid(@RequestParam String refid) { - return monitoringService.getdetailsbyrefid(refid); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/PendinglistApicontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/PendinglistApicontroller.java deleted file mode 100644 index 9739a804..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/PendinglistApicontroller.java +++ /dev/null @@ -1,182 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.controller; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.greencommittee.service.PendinglistService; - -@RestController -@RequestMapping("/gcc/api/greencommittee/pendinglist") -public class PendinglistApicontroller { - - @Autowired - private PendinglistService pendinglistService; - - @GetMapping("/getzones") - public List> ViewZoneDropdown() { - - return pendinglistService.ViewZoneDropdown(); - - } - - @GetMapping("/getwardbyzone") - public List> ViewWardDropdown(@RequestParam String zone) { - - return pendinglistService.ViewWardDropdown(zone); - - } - - @GetMapping("/dropdown-Event") - public ResponseEntity>> ViewDropdownEvent() { - try { - List> result = pendinglistService.ViewDropdownEvent(); - return ResponseEntity.ok(result); - } catch (Exception e) { - Map error = new HashMap<>(); - error.put("error", "Unable to fetch event list"); - error.put("details", e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonList(error)); - } - } - - // @GetMapping("/getgreencommitteelist") - // public List> getgreencommitteelist(@RequestParam String - // date, - // @RequestParam String zones) { - // - // List refnums = pendinglistService.getrefnums(date, zones); - // //System.out.println("refnums="+refnums); - // List> savedids=pendinglistService.getvcsavedrefids(); - // //System.err.println("savedids="+savedids); - // // Convert to List - // List savedRefIds = savedids.stream() - // .map(m -> m.get("ref_id").toString()) - // .toList(); - // - // //System.out.println("savedRefIds=" + savedRefIds); - // - // List> finalList = new ArrayList<>(); - // - // if (refnums.isEmpty()) { - // return Collections.emptyList(); - // } - // - // // REMOVE already saved ref_ids - // List filteredRefIds = refnums.stream() - // .filter(ref -> !savedRefIds.contains(ref)) - // .toList(); - // - // //System.out.println("filteredRefIds="+filteredRefIds); - // - // for (String ref : filteredRefIds) { - // Map data = pendinglistService.getlistdata(ref); - // if (data != null && !data.isEmpty()) { - // finalList.add(data); - // } - // } - // - // return finalList; - // } - - @GetMapping("/getgreencommitteelist") - public List> getgreencommitteelist( - @RequestParam String date, @RequestParam String zones) { - - List> refnums = pendinglistService.getrefnums(date, zones); - System.out.println("refnums=" + refnums); - List> savedIds = pendinglistService.getvcsavedrefids(); - System.out.println("savedIds=" + savedIds); - // Convert savedIds → List - List savedRefList = new ArrayList<>(); - for (Map m : savedIds) { - savedRefList.add(m.get("ref_id").toString()); - } - - List> finalList = new ArrayList<>(); - - for (Map row : refnums) { - - String refId = row.get("ref_id").toString(); - Integer inspReinsId = row.get("latest_reinspection_id") != null - ? Integer.parseInt(row.get("latest_reinspection_id").toString()) - : null; - - // Skip if already committee decided - if (savedRefList.contains(refId)) - continue; - - // Get reinspection latest id - Integer dbLatest = pendinglistService.getLatestReinspectionId(refId); - - // Rule: if inspection reinspection ID is NULL but in DB exists → skip - if (inspReinsId == null && dbLatest != null) - continue; - - // Rule: if BOTH exist AND not equal → skip - if (inspReinsId != null && dbLatest != null && !inspReinsId.equals(dbLatest)) - continue; - - // 👍 Valid, add final data - Map data = pendinglistService.getlistdata(refId); - if (data != null && !data.isEmpty()) { - - System.out.println("inside=" + refId); - finalList.add(data); - } - } - - return finalList; - } - - @GetMapping("/getdetailsbyrefid") - public Map getdetailsbyrefid(@RequestParam String refid) { - return pendinglistService.getdetailsbyrefid(refid); - } - - @GetMapping("/getCommitteeActions") - public List> getCommitteeActions() { - - return pendinglistService.getCommitteeActions(); - - } - - @PostMapping("/savecommittee") - public Map saveCommittee(@RequestBody Map payload) { - - String refId = (String) payload.get("ref_id"); - String remarks = (String) payload.get("remarks"); - int userId = Integer.parseInt(payload.get("userId").toString()); - int meetingid = Integer.parseInt(payload.get("meetingid").toString()); - - List> decisions = (List>) payload.get("decisions"); - - return pendinglistService.saveCommittee(refId, remarks, meetingid, userId, decisions); - } - - @PostMapping("/savereinspection") - public Map saveReInspection(@RequestBody Map payload) { - - String refId = payload.get("ref_id").toString(); - int committeeAction = Integer.parseInt(payload.get("committee_action").toString()); - int meetingId = Integer.parseInt(payload.get("meeting_id").toString()); - String remarks = payload.get("remarks") != null ? payload.get("remarks").toString() : null; - int userId = Integer.parseInt(payload.get("userId").toString()); - - return pendinglistService.saveReInspection(refId, committeeAction, meetingId, remarks, userId); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/ReportApicontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/ReportApicontroller.java deleted file mode 100644 index 9a3984b6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/controller/ReportApicontroller.java +++ /dev/null @@ -1,189 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.controller; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.greencommittee.service.ReportService; - -@RestController -@RequestMapping("/gcc/api/greencommittee/report") -public class ReportApicontroller { - - @Autowired - private ReportService reportService; - - @GetMapping("/getgreencommitteelist") - public List> getgreencommitteelist(@RequestParam String meetingid, - @RequestParam String zones, @RequestParam String deptid, @RequestParam String appType) { - - List refnums = reportService.getrefnums(meetingid, zones, deptid, appType); - System.out.println("refnums=" + refnums); - - List> finalList = new ArrayList<>(); - - if (refnums.isEmpty()) { - return Collections.emptyList(); - } - - for (String ref : refnums) { - System.out.println("ref=" + ref); - Map data = reportService.getlistdata(ref); - if (data != null && !data.isEmpty()) { - finalList.add(data); - } - } - - return finalList; - } - - @GetMapping("/getabscount") - public Map getabscount(@RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - Map response = new HashMap<>(); - - try { - List> data = reportService.getabscount(startDate, endDate); - - response.put("data", data); - response.put("message", "Zone-wise abstract report"); - response.put("status", "Success"); - - } catch (Exception e) { - e.printStackTrace(); - - response.put("data", Collections.emptyList()); - response.put("message", "Failed to fetch abstract report"); - response.put("status", "Error"); - } - - return response; - } - - @GetMapping("/getWardDetailsByZone") - public Map getWardDetailsByZone(@RequestParam(required = true) String zone, - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - Map response = new HashMap<>(); - - try { - List> data = reportService.getWardDetailsByZone(zone, startDate, endDate); - - response.put("data", data); - response.put("message", "Ward-wise abstract report"); - response.put("status", "Success"); - - } catch (Exception e) { - e.printStackTrace(); - - response.put("data", Collections.emptyList()); - response.put("message", "Failed to fetch abstract report"); - response.put("status", "Error"); - } - - return response; - } - - @GetMapping("/getPendingDetails") - public Map getPendingDetails( - @RequestParam String zone, - @RequestParam(required = false) String ward, - @RequestParam String type, - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - Map response = new HashMap<>(); - - try { - List refIds = reportService.getPendingRefIds(zone, ward, type, startDate, endDate); - - List> dataList = new ArrayList<>(); - - for (String refId : refIds) { - Map fullData = reportService.getfulldetailsdata(refId); - if (fullData != null && !fullData.isEmpty()) { - dataList.add((Map) fullData.get("data")); - } - } - - response.put("data", dataList); - response.put("message", "Complaint List"); - response.put("status", "Success"); - - } catch (Exception e) { - e.printStackTrace(); - response.put("data", Collections.emptyList()); - response.put("message", "Failed to fetch complaints"); - response.put("status", "Error"); - } - - return response; - } - - @GetMapping("/getDepartments") - @ResponseBody - public List> getDepartments() { - return reportService.getDepartments(); - } - - @GetMapping("/wards") - public List> getWards(@RequestParam Integer zoneId) { - - return reportService.getWards(zoneId); - - } - - @GetMapping("/zones") - public List> getZones() { - return reportService.getZones(); - } - - @GetMapping("/details") - public ResponseEntity getComplaintDetails( - @RequestParam String complaintId) { - - return ResponseEntity.ok( - reportService.getComplaintDetailsreport(complaintId)); - } - - @GetMapping("/getreport") - public ResponseEntity>> getTreePruningReport( - - @RequestParam String fromDate, - @RequestParam String toDate, - - @RequestParam(required = false) String zone, - - @RequestParam(required = false) String ward, - - @RequestParam(required = false) String status - - ) { - - return ResponseEntity.ok( - - reportService.getReport( - - fromDate, - toDate, - zone, - ward, - status) - - ); - - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/CreateMeetingService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/CreateMeetingService.java deleted file mode 100644 index 8d501e42..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/CreateMeetingService.java +++ /dev/null @@ -1,100 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.LocalDate; - -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.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.vendor.service.DateTimeUtil; - -@Service -public class CreateMeetingService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private Environment environment; - - @Autowired - public void setDataSource(@Qualifier("mysqlGreenCommitteeDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public String fileUpload(MultipartFile file, String name) { - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory.mobile"); - String serviceFolderName = environment.getProperty("green_committee_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 + "_" + 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); - */ - - Files.write(path, bytes); - - //System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - public String insertEvent(String eventName, LocalDate eventDate, String fileUrl,String cby) { - String sql = "INSERT INTO create_meeting (event_name, event_date, file_url,cby) VALUES (?, ?, ?,?)"; - try { - jdbcTemplate.update(sql, eventName, eventDate, fileUrl,cby); - return "success"; - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - } - return "error"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/DashboardService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/DashboardService.java deleted file mode 100644 index ad0255eb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/DashboardService.java +++ /dev/null @@ -1,77 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.service; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class DashboardService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlGreenCommitteeDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public int getApplicationsCount() - { - String sql="SELECT COUNT(*) FROM reg_details WHERE is_active=1"; - - try { - return jdbcTemplate.queryForObject(sql,Integer.class); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return 0; - } - - - } - - - public int getDGCcompletedCount() { - - try { - - String sql = - "SELECT COUNT(*) AS total " + - "FROM ( " + - " SELECT ref_id " + - " FROM ( " + - " SELECT ref_id, inspection_by, MAX(cdate) AS latest_date " + - " FROM inspection_data " + - " WHERE isactive = 1 " + - " GROUP BY ref_id, inspection_by " + - " ) AS t " + - " GROUP BY ref_id " + - " HAVING COUNT(DISTINCT inspection_by) = 3 " + - ") AS final"; - - return jdbcTemplate.queryForObject(sql, Integer.class); - - } catch (Exception e) { - System.err.println("Error in getCompletedRefIdCount(): " + e.getMessage()); - e.printStackTrace(); - return 0; - } - } - - public int getCommitteeCompleted() - { - String sql="SELECT COUNT(*) FROM committee_data WHERE isactive=1"; - - try { - return jdbcTemplate.queryForObject(sql,Integer.class); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return 0; - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/DateTimeUtil.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/DateTimeUtil.java deleted file mode 100644 index 67b25227..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/DateTimeUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.service; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -import org.springframework.stereotype.Component; - - -@Component("greencommitteDateTimeUtil") -public final class DateTimeUtil { - public static String getCurrentDateTime() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentYear() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentMonth() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentDay() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentDateTimeMysql() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/MonitoringService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/MonitoringService.java deleted file mode 100644 index 2c753f6e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/MonitoringService.java +++ /dev/null @@ -1,217 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.service; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class MonitoringService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Value("${fileBaseUrl}") - private String fileBaseUrl; - - @Autowired - public void setDataSource(@Qualifier("mysqlGreenCommitteeDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List getrefnums(String meetingid, String zones) { - try { - - StringBuilder sql = new StringBuilder( - " SELECT cd.ref_id " + - " FROM committee_data cd " - + " LEFT JOIN reg_details rd ON rd.ref_id=cd.ref_id " + - " WHERE cd.isactive = 1 " - - ); - - List params = new ArrayList<>(); - - if (meetingid != null && !meetingid.isEmpty()) { - sql.append(" AND cd.meeting_id = ? "); - params.add(meetingid); - } - - if (zones != null && !zones.isEmpty()) { - sql.append(" AND rd.zone = ? "); - params.add(zones); - } - - return jdbcTemplate.queryForList(sql.toString(), params.toArray(), String.class); - - } catch (Exception e) { - - System.err.println("Error in getrefums(): " + e.getMessage()); - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public Map getlistdata(String ref) { - - Map regDetails = getRegDetails(ref); - - List> compDetails = getComplaintDetails(ref); - - regDetails.put("comp_details", compDetails); - - return regDetails; - } - - public Map getRegDetails(String ref) { - String sql = "SELECT * FROM reg_details WHERE is_active = 1 AND ref_id = ?"; - return jdbcTemplate.queryForMap(sql, ref); - } - - public List> getComplaintDetails(String ref) { - - String sql = "SELECT cn.name AS nature, SUM(cd.no_of_trees) AS total_trees " + - "FROM complaint_details cd " + - "JOIN comp_nature cn ON cn.id = cd.comp_nature_id " + - "WHERE cd.is_active = 1 AND cd.ref_id = ? " + - "GROUP BY cn.name"; - - return jdbcTemplate.queryForList(sql, ref); - } - - public Map getdetailsbyrefid(String refId) { - - Map response = new HashMap<>(); - - // 1 — Application details - Map app = jdbcTemplate.queryForMap( - "SELECT *,DATE_FORMAT(cdate, '%d-%m-%Y %l:%i %p') as r_Cdate FROM reg_details WHERE ref_id=? AND is_active=1", - refId - ); - - // 2 — Complaint details (grouped) - List> complaints = jdbcTemplate.queryForList( - "SELECT cn.name AS nature, SUM(cd.no_of_trees) AS count " + - "FROM complaint_details cd JOIN comp_nature cn ON cn.id=cd.comp_nature_id " + - "WHERE cd.ref_id=? GROUP BY cn.name", refId - ); - - // 3 — Complaint images - List compImages = jdbcTemplate.queryForList( - "SELECT img_path FROM img_uploads WHERE ref_id=? AND is_active=1", - new Object[]{refId}, String.class - ).stream() - .map(path -> fileBaseUrl + "/gccofficialapp/files" + path) - .collect(Collectors.toList()); - - app.put("complaints", complaints); - app.put("images", compImages); - response.put("application", app); - - // 4 — Inspection details - List> inspectionList = new ArrayList<>(); - - String sql = - "SELECT id.*, um.name AS inspector_name, " + - " DATE_FORMAT(id.cdate, '%d-%m-%Y %l:%i %p') AS f_Cdate " + - "FROM inspection_data id " + - "LEFT JOIN user_maping um ON um.userid = id.cby " + - "INNER JOIN ( " + - " SELECT inspection_by, MAX(cdate) AS latest_date " + - " FROM inspection_data " + - " WHERE ref_id = ? AND isactive = 1 " + - " GROUP BY inspection_by " + - ") latest ON id.inspection_by = latest.inspection_by " + - " AND id.cdate = latest.latest_date " + - "WHERE id.ref_id = ? AND id.isactive = 1 " + - "ORDER BY FIELD(id.inspection_by, 'GCC', 'NGO', 'TNFD')"; - - List> rows = jdbcTemplate.queryForList( - sql, refId, refId - ); - - - for (Map row : rows) { - - Integer inspId = (Integer) row.get("inspection_data_id"); - - // 4a — Recommendation details - List> recommend = jdbcTemplate.queryForList( - "SELECT rm.name, itd.nooftrees AS count " + - "FROM inspection_tree_data itd " + - "JOIN inspection_recommend_master rm ON rm.rid = itd.action " + - "WHERE itd.inspection_data_id=? AND itd.isactive=1", - inspId - ); - - row.put("recommendations", recommend); - - // 4b — Images (thumbnail list) - List imgs = new ArrayList<>(); - if (row.get("file_1") != null) { - imgs.add(fileBaseUrl + "/gccofficialapp/files" + row.get("file_1").toString()); - } - if (row.get("file_2") != null) { - imgs.add(fileBaseUrl + "/gccofficialapp/files" + row.get("file_2").toString()); - } - if (row.get("file_3") != null) { - imgs.add(fileBaseUrl + "/gccofficialapp/files" + row.get("file_3").toString()); - } - - row.put("images", imgs); - - inspectionList.add(row); - } - - response.put("inspections", inspectionList); - - - // 5 — Re-Inspection Details - String reSql = - "SELECT r.id AS reins_id, r.committee_action, r.remarks AS reins_remarks, " + - " DATE_FORMAT(r.cdate, '%d-%m-%Y %l:%i %p') AS reins_date, " + - " cm.event_name, DATE_FORMAT(cm.event_date, '%d-%m-%Y') AS event_date " + - "FROM reinspection r " + - "LEFT JOIN create_meeting cm ON cm.id = r.meeting_id " + - "WHERE r.ref_id = ? AND r.isactive = 1 " + - "ORDER BY r.id DESC"; - - List> reinspectionList = jdbcTemplate.queryForList(reSql, refId); - - response.put("reinspections", reinspectionList); - - - //List> committeeList = new ArrayList<>(); - - Map c1 = jdbcTemplate.queryForMap( - "SELECT cd.*,DATE_FORMAT(cd.cdate, '%d-%m-%Y %l:%i %p') as c_Cdate,cm.event_name as meeting_name,cm.event_date as meeting_date " - + " FROM committee_data cd " - + " LEFT JOIN create_meeting cm ON cm.id=cd.meeting_id " - + " WHERE cd.ref_id=? AND cd.isactive=1 ", - refId - ); - - List> com_complaints = jdbcTemplate.queryForList( - "SELECT crm.name AS nature, SUM(ctd.nooftrees) AS count " + - "FROM committee_tree_data ctd JOIN committee_recommend_master crm ON crm.id=ctd.committee_action " + - "WHERE ctd.ref_id=? GROUP BY crm.name", refId - ); - - c1.put("com_complaints",com_complaints ); - response.put("committee", c1); - - return response; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/PendinglistService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/PendinglistService.java deleted file mode 100644 index 9bf542b4..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/PendinglistService.java +++ /dev/null @@ -1,476 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.service; - -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class PendinglistService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Value("${fileBaseUrl}") - private String fileBaseUrl; - - @Autowired - public void setDataSource(@Qualifier("mysqlGreenCommitteeDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> ViewWardDropdown(String zone) { - String sql = "SELECT ward_name " - + "FROM ward_master " - + "WHERE is_active=1 AND is_delete=0 AND zone_id=?"; - try { - return jdbcTemplate.queryForList(sql, zone); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> ViewZoneDropdown() { - String sql = "SELECT zone_name " - + "FROM zone_master " - + "WHERE is_active=1 AND is_delete=0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> ViewDropdownEvent() { - String sql = "SELECT * FROM create_meeting WHERE isactive=1 AND isdelete=0"; - return jdbcTemplate.queryForList(sql); - } - - // public List getrefnums(String date, String zones) { - // - // try { - // - // StringBuilder sql = new StringBuilder( - // "SELECT t.ref_id " + - // "FROM ( " + - // " SELECT ref_id, inspection_by, MAX(cdate) AS latest_date " + - // " FROM inspection_data " + - // " WHERE DATE(cdate) <= STR_TO_DATE(?, '%d-%m-%Y') " + - // " AND isactive = 1 " - // ); - // - // List params = new ArrayList<>(); - // params.add(date); - // - // if (zones != null && !zones.isEmpty()) { - // sql.append(" AND zone = ? "); - // params.add(zones); - // } - // - // sql.append( - // " GROUP BY ref_id, inspection_by " + - // ") AS t " + - // "GROUP BY t.ref_id " + - // "HAVING COUNT(DISTINCT t.inspection_by) = 3 " + - // "ORDER BY MAX(t.latest_date) DESC" - // ); - // - // return jdbcTemplate.queryForList(sql.toString(), params.toArray(), - // String.class); - // - // } catch (Exception e) { - // - // System.err.println("Error in getrefums(): " + e.getMessage()); - // e.printStackTrace(); - // return Collections.emptyList(); - // } - // } - - public List> getrefnums(String date, String zones) { - System.out.println(date + " " + zones); - - try { - - StringBuilder sql = new StringBuilder( - "SELECT ref_id, " + - " MAX(latest_reinspection_id) AS latest_reinspection_id " + - "FROM ( " + - " SELECT ref_id, inspection_by, " + - " MAX(cdate) AS latest_date, " + - " MAX(reinspection_id) AS latest_reinspection_id " + - " FROM inspection_data " + - " WHERE DATE(cdate) <= STR_TO_DATE(?, '%d-%m-%Y') " + - " AND isactive = 1 "); - - List params = new ArrayList<>(); - params.add(date); - - if (zones != null && !zones.isEmpty()) { - sql.append(" AND zone = ? "); - params.add(zones); - } - - sql.append( - " GROUP BY ref_id, inspection_by " + - ") AS x " + - "GROUP BY ref_id " + - "HAVING COUNT(DISTINCT inspection_by) >= 2 " + - "ORDER BY MAX(latest_date) DESC"); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public Integer getLatestReinspectionId(String refId) { - try { - String sql = "SELECT id FROM reinspection WHERE ref_id=? ORDER BY id DESC LIMIT 1"; - return jdbcTemplate.queryForObject(sql, Integer.class, refId); - } catch (Exception e) { - return null; - } - } - - public Map getlistdata(String ref) { - - Map regDetails = getRegDetails(ref); - - List> compDetails = getComplaintDetails(ref); - - regDetails.put("comp_details", compDetails); - - return regDetails; - } - - public Map getRegDetails(String ref) { - String sql = "SELECT * FROM reg_details WHERE is_active = 1 AND ref_id = ?"; - return jdbcTemplate.queryForMap(sql, ref); - } - - public List> getComplaintDetails(String ref) { - - String sql = "SELECT cn.name AS nature, SUM(cd.no_of_trees) AS total_trees " + - "FROM complaint_details cd " + - "JOIN comp_nature cn ON cn.id = cd.comp_nature_id " + - "WHERE cd.is_active = 1 AND cd.ref_id = ? " + - "GROUP BY cn.name"; - - return jdbcTemplate.queryForList(sql, ref); - } - - public Map getdetailsbyrefid(String refId) { - - Map response = new HashMap<>(); - - // 1 — Application details - Map app = jdbcTemplate.queryForMap( - "SELECT *,DATE_FORMAT(cdate, '%d-%m-%Y %l:%i %p') as r_Cdate FROM reg_details WHERE ref_id=? AND is_active=1", - refId); - - // 2 — Complaint details (grouped) - List> complaints = jdbcTemplate.queryForList( - "SELECT cn.name AS nature, SUM(cd.no_of_trees) AS count " + - "FROM complaint_details cd JOIN comp_nature cn ON cn.id=cd.comp_nature_id " + - "WHERE cd.ref_id=? GROUP BY cn.name", - refId); - - // 3 — Complaint images - List compImages = jdbcTemplate.queryForList( - "SELECT img_path FROM img_uploads WHERE ref_id=? AND is_active=1", - new Object[] { refId }, String.class).stream() - .map(path -> fileBaseUrl + "/gccofficialapp/files" + path) - .collect(Collectors.toList()); - - app.put("complaints", complaints); - app.put("images", compImages); - response.put("application", app); - - // 4 — Inspection details - List> inspectionList = new ArrayList<>(); - - String sql = "SELECT id.*, um.name AS inspector_name, " + - " DATE_FORMAT(id.cdate, '%d-%m-%Y %l:%i %p') AS f_Cdate " + - "FROM inspection_data id " + - "LEFT JOIN user_maping um ON um.userid = id.cby " + - "INNER JOIN ( " + - " SELECT inspection_by, MAX(cdate) AS latest_date " + - " FROM inspection_data " + - " WHERE ref_id = ? AND isactive = 1 " + - " GROUP BY inspection_by " + - ") latest ON id.inspection_by = latest.inspection_by " + - " AND id.cdate = latest.latest_date " + - "WHERE id.ref_id = ? AND id.isactive = 1 " + - "ORDER BY FIELD(id.inspection_by, 'GCC', 'NGO', 'TNFD')"; - - List> rows = jdbcTemplate.queryForList( - sql, refId, refId); - - for (Map row : rows) { - - Integer inspId = (Integer) row.get("inspection_data_id"); - - // 4a — Recommendation details - List> recommend = jdbcTemplate.queryForList( - "SELECT rm.name, itd.nooftrees AS count,itd.treename as treename " + - "FROM inspection_tree_data itd " + - "JOIN inspection_recommend_master rm ON rm.rid = itd.action " + - "WHERE itd.inspection_data_id=? AND itd.isactive=1", - inspId); - - row.put("recommendations", recommend); - - // 4b — Images (thumbnail list) - List imgs = new ArrayList<>(); - if (row.get("file_1") != null) { - imgs.add(fileBaseUrl + "/gccofficialapp/files" + row.get("file_1").toString()); - } - if (row.get("file_2") != null) { - imgs.add(fileBaseUrl + "/gccofficialapp/files" + row.get("file_2").toString()); - } - if (row.get("file_3") != null) { - imgs.add(fileBaseUrl + "/gccofficialapp/files" + row.get("file_3").toString()); - } - - row.put("images", imgs); - - inspectionList.add(row); - } - // ak - // Expected inspection stages - List expected = Arrays.asList("GCC", "NGO", "TNFD"); - - // Completed stages - Set completed = inspectionList.stream() - .map(m -> String.valueOf(m.get("inspection_by"))) - .collect(Collectors.toSet()); - - // Add pending cards - for (String type : expected) { - - if (!completed.contains(type)) { - - Map pending = new HashMap<>(); - - pending.put("inspection_by", type); - pending.put("status", "PENDING"); - pending.put("inspector_name", ""); - pending.put("f_Cdate", ""); - pending.put("remarks", ""); - pending.put("recommendations", new ArrayList<>()); - pending.put("images", new ArrayList<>()); - - inspectionList.add(pending); - } - } - - // Sort in order GCC -> NGO -> TNFD - Map order = new HashMap<>(); - order.put("GCC", 1); - order.put("NGO", 2); - order.put("TNFD", 3); - - inspectionList.sort( - Comparator.comparingInt( - m -> order.getOrDefault(String.valueOf(m.get("inspection_by")), 99))); - - response.put("inspections", inspectionList); - - // 5 — Re-Inspection Details - String reSql = "SELECT r.id AS reins_id, r.committee_action, r.remarks AS reins_remarks, " + - " DATE_FORMAT(r.cdate, '%d-%m-%Y %l:%i %p') AS reins_date, " + - " cm.event_name, DATE_FORMAT(cm.event_date, '%d-%m-%Y') AS event_date " + - "FROM reinspection r " + - "LEFT JOIN create_meeting cm ON cm.id = r.meeting_id " + - "WHERE r.ref_id = ? AND r.isactive = 1 " + - "ORDER BY r.id DESC"; - - List> reinspectionList = jdbcTemplate.queryForList(reSql, refId); - - response.put("reinspections", reinspectionList); - - return response; - } - - public List> getCommitteeActions() { - String sql = "SELECT id,name " - + "FROM committee_recommend_master " - + "WHERE isactive=1 AND isdelete=0 " - + "ORDER BY orderby"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public Map saveCommittee( - String refId, - String remarks, - int meetingid, - int userId, - List> decisions) { - - Map response = new HashMap<>(); - - try { - // 1️⃣ Save committee_data and get generated ID - int committeeDataId = saveCommitteeData(refId, remarks, meetingid, userId); - - List insertedTreeIds = saveCommitteeTreeData(decisions, committeeDataId, refId, userId); - - response.put("committee_data_id", committeeDataId); - response.put("tree_ids", insertedTreeIds); - response.put("status", "success"); - response.put("message", "Committee decision saved!"); - - } catch (Exception e) { - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - } - - public int saveCommitteeData(String refId, String remarks, int meetingid, int userId) { - - String remarksValue = (remarks == null || remarks.trim().isEmpty()) ? null : remarks.trim(); - - String sql = "INSERT INTO committee_data (ref_id, meeting_id, remarks, cby) VALUES (?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, refId); - ps.setInt(2, meetingid); - if (remarksValue == null) { - ps.setNull(3, Types.VARCHAR); - } else { - ps.setString(3, remarksValue); - } - ps.setInt(4, userId); - return ps; - }, keyHolder); - - return keyHolder.getKey().intValue(); // generated committee_data.id - } - - public List saveCommitteeTreeData( - List> decisions, - int committeeDataId, - String refId, - int userId) { - - String sql = "INSERT INTO committee_tree_data (nooftrees, committee_action, committee_data_id, ref_id, cby) " + - "VALUES (?, ?, ?, ?, ?)"; - - List insertedIds = new ArrayList<>(); - - for (Map row : decisions) { - - int actionId = Integer.parseInt(row.get("id").toString()); - int count = Integer.parseInt(row.get("count").toString()); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, count); - ps.setInt(2, actionId); - ps.setInt(3, committeeDataId); - ps.setString(4, refId); - ps.setInt(5, userId); - return ps; - }, keyHolder); - - insertedIds.add(keyHolder.getKey().intValue()); - } - - return insertedIds; - } - - public List> getvcsavedrefids() { - String sql = "SELECT ref_id FROM committee_data WHERE isactive=1"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - - } - } - - @Transactional - public Map saveReInspection(String refId, int action, int meetingId, - String remarks, int userId) { - - Map response = new HashMap<>(); - - try { - - // Insert into reinspection table - String sql = "INSERT INTO reinspection (ref_id, committee_action, meeting_id, remarks, cby) " + - "VALUES (?, ?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, refId); - ps.setInt(2, action); - ps.setInt(3, meetingId); - ps.setString(4, remarks); - ps.setInt(5, userId); - return ps; - }, keyHolder); - - int generatedId = keyHolder.getKey().intValue(); - - // Update reg_details.reinspection_id - jdbcTemplate.update("UPDATE reg_details SET reinspection_id=? WHERE ref_id=?", generatedId, refId); - - jdbcTemplate.update("UPDATE inspection_data SET isactive=0,isdelete=1 WHERE ref_id=?", refId); - - response.put("status", "success"); - response.put("message", "Committee decision saved!"); - response.put("reinspection_id", generatedId); - - } catch (Exception e) { - response.put("status", "error"); - response.put("message", e.getMessage()); - } - - return response; - - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/ReportService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/ReportService.java deleted file mode 100644 index cdff1176..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/greencommittee/service/ReportService.java +++ /dev/null @@ -1,743 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.greencommittee.service; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.net.URL; -import java.net.URLEncoder; -import com.fasterxml.jackson.core.type.TypeReference; - -@Service -public class ReportService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Value("${fileBaseUrl}") - private String fileBaseUrl; - - @Autowired - public void setDataSource(@Qualifier("mysqlGreenCommitteeDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List getrefnums(String meetingid, String zones, String deptid, String appType) { - try { - - StringBuilder sql = new StringBuilder( - " SELECT DISTINCT ref_id FROM ( " + - - " SELECT cd.ref_id " + - " FROM committee_data cd " + - " LEFT JOIN reg_details rd ON rd.ref_id = cd.ref_id " + - " WHERE cd.isactive = 1 " + - - " UNION " + - - " SELECT ri.ref_id " + - " FROM reinspection ri " + - " INNER JOIN ( " + - " SELECT ref_id, MAX(cdate) AS max_cdate " + - " FROM reinspection " + - " WHERE isactive = 1 " + - " GROUP BY ref_id " + - " ) latest " + - " ON latest.ref_id = ri.ref_id " + - " AND latest.max_cdate = ri.cdate " + - " LEFT JOIN reg_details rd2 ON rd2.ref_id = ri.ref_id " + - " WHERE ri.isactive = 1 " + - - " ) t WHERE 1=1 "); - - List params = new ArrayList<>(); - - /* Meeting filter */ - if (meetingid != null && !meetingid.isEmpty()) { - sql.append( - " AND ref_id IN ( " + - " SELECT ref_id FROM committee_data WHERE meeting_id = ? " + - " UNION " + - " SELECT ref_id FROM reinspection WHERE meeting_id = ? " + - " ) "); - params.add(meetingid); - params.add(meetingid); - } - - /* Zone filter */ - if (zones != null && !zones.isEmpty()) { - sql.append( - " AND ref_id IN ( " + - " SELECT ref_id FROM reg_details WHERE zone = ? " + - " ) "); - params.add(zones); - } - - if (deptid != null && !deptid.isEmpty()) { - sql.append( - " AND ref_id IN ( " + - " SELECT ref_id FROM reg_details WHERE dept_id = ? " + - " ) "); - params.add(deptid); - } - - if (appType != null && !appType.isEmpty()) { - sql.append( - " AND ref_id IN ( " + - " SELECT ref_id FROM reg_details WHERE cby = ? " + - " ) "); - params.add(appType); - } - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray(), - String.class); - - } catch (Exception e) { - System.err.println("Error in getrefnums(): " + e.getMessage()); - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public Map getlistdata(String ref) { - - Map regDetails = getRegDetails(ref); - - List> compDetails = getComplaintDetails(ref); - - regDetails.put("comp_details", compDetails); - - List> inspectionList = new ArrayList<>(); - - String sql = "SELECT id.*, um.name AS inspector_name, " + - " DATE_FORMAT(id.cdate, '%d-%m-%Y %l:%i %p') AS f_Cdate " + - "FROM inspection_data id " + - "LEFT JOIN user_maping um ON um.userid = id.cby " + - "INNER JOIN ( " + - " SELECT inspection_by, MAX(cdate) AS latest_date " + - " FROM inspection_data " + - " WHERE ref_id = ? AND isactive = 1 " + - " GROUP BY inspection_by " + - ") latest ON id.inspection_by = latest.inspection_by " + - " AND id.cdate = latest.latest_date " + - "WHERE id.ref_id = ? AND id.isactive = 1 " + - "ORDER BY FIELD(id.inspection_by, 'GCC', 'NGO', 'TNFD')"; - - List> rows = jdbcTemplate.queryForList( - sql, ref, ref); - - for (Map row : rows) { - - Integer inspId = (Integer) row.get("inspection_data_id"); - - // 4a — Recommendation details - List> recommend = jdbcTemplate.queryForList( - "SELECT rm.name, itd.nooftrees AS count " + - "FROM inspection_tree_data itd " + - "JOIN inspection_recommend_master rm ON rm.rid = itd.action " + - "WHERE itd.inspection_data_id=? AND itd.isactive=1", - inspId); - - row.put("recommendations", recommend); - - inspectionList.add(row); - } - - regDetails.put("inspections", inspectionList); - - String reSql = "SELECT r.id AS reins_id, r.committee_action, r.remarks AS reins_remarks, " + - " DATE_FORMAT(r.cdate, '%d-%m-%Y %l:%i %p') AS reins_date, " + - " cm.event_name, DATE_FORMAT(cm.event_date, '%d-%m-%Y') AS event_date, crm.name as ins_name " + - "FROM reinspection r " + - "LEFT JOIN create_meeting cm ON cm.id = r.meeting_id " + - " LEFT JOIN committee_recommend_master crm ON crm.id=r.committee_action " + - "WHERE r.ref_id = ? AND r.isactive = 1 " + - "ORDER BY r.id DESC"; - - List> reinspectionList = jdbcTemplate.queryForList(reSql, ref); - - regDetails.put("reinspections", reinspectionList); - - Map c1 = null; - - List> committeeList = jdbcTemplate.queryForList( - "SELECT cd.*, DATE_FORMAT(cd.cdate, '%d-%m-%Y %l:%i %p') AS c_Cdate, " + - "cm.event_name AS meeting_name, cm.event_date AS meeting_date " + - "FROM committee_data cd " + - "LEFT JOIN create_meeting cm ON cm.id = cd.meeting_id " + - "WHERE cd.ref_id = ? AND cd.isactive = 1", - ref); - - if (!committeeList.isEmpty()) { - c1 = committeeList.get(0); - - List> com_complaints = jdbcTemplate.queryForList( - "SELECT crm.name AS nature, SUM(ctd.nooftrees) AS count " + - "FROM committee_tree_data ctd " + - "JOIN committee_recommend_master crm ON crm.id = ctd.committee_action " + - "WHERE ctd.ref_id = ? " + - "GROUP BY crm.name", - ref); - - c1.put("com_complaints", com_complaints); - } - - // IMPORTANT: always put committee key (even if null) - regDetails.put("committee", c1); - - return regDetails; - } - - public Map getRegDetails(String ref) { - String sql = "SELECT rd.*,dm.name as department_name FROM reg_details rd left join dept_master dm on dm.id=rd.dept_id WHERE rd.is_active = 1 AND rd.ref_id = ?"; - return jdbcTemplate.queryForMap(sql, ref); - } - - public List> getComplaintDetails(String ref) { - - String sql = "SELECT cn.name AS nature, SUM(cd.no_of_trees) AS total_trees " + - "FROM complaint_details cd " + - "JOIN comp_nature cn ON cn.id = cd.comp_nature_id " + - "WHERE cd.is_active = 1 AND cd.ref_id = ? " + - "GROUP BY cn.name"; - - return jdbcTemplate.queryForList(sql, ref); - } - - public List> getabscount(String startDate, String endDate) { - - String baseSql = "SELECT " + - " zm.zone_name, " + - " COALESCE(COUNT(DISTINCT rd.ref_id), 0) AS total_requests, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='NGO' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id=id.reinspection_id) ) " + - " ) " + - " THEN 1 ELSE 0 END), 0) AS ngo_pending, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='GCC' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id=id.reinspection_id) ) " + - " ) " + - " THEN 1 ELSE 0 END), 0) AS gcc_pending, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='TNFD' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id=id.reinspection_id) ) " + - " ) " + - " THEN 1 ELSE 0 END), 0) AS tnfd_pending, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND ( " + - " SELECT COUNT(DISTINCT inspection_by) " + - " FROM inspection_data id " + - " WHERE id.ref_id = rd.ref_id AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id=id.reinspection_id) ) " + - " ) = 3 " + - " THEN 1 ELSE 0 END), 0) AS committee_pending, " + - - " COALESCE(SUM(CASE WHEN rd.is_withdraw = 1 THEN 1 ELSE 0 END), 0) AS withdrawn, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " THEN 1 ELSE 0 END), 0) AS completed " + - - "FROM zone_master zm " + - "LEFT JOIN reg_details rd " + - " ON rd.zone = zm.zone_name " + - " AND rd.is_active = 1 "; - - StringBuilder sql = new StringBuilder(baseSql); - List params = new ArrayList<>(); - - if (startDate != null && !startDate.isEmpty()) { - sql.append(" AND DATE(rd.cdate) >= ? "); - params.add(startDate); - } - - if (endDate != null && !endDate.isEmpty()) { - sql.append(" AND DATE(rd.cdate) <= ? "); - params.add(endDate); - } - - sql.append( - " WHERE zm.is_active = 1 " + - " AND zm.is_delete = 0 " + - " GROUP BY zm.zone_name " + - " ORDER BY zm.zone_name "); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - public List> getWardDetailsByZone( - String zone, - String startDate, - String endDate) { - - String baseSql = "SELECT " + - " wm.zone_id, " + - " wm.ward_name, " + - - " COALESCE(COUNT(DISTINCT rd.ref_id), 0) AS total_requests, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='NGO' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - " ) " + - " THEN 1 ELSE 0 END), 0) AS ngo_pending, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='GCC' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - " ) " + - " THEN 1 ELSE 0 END), 0) AS gcc_pending, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='TNFD' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - " ) " + - " THEN 1 ELSE 0 END), 0) AS tnfd_pending, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IS NOT NULL " + - " AND rd.is_withdraw = 0 " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - " AND ( " + - " SELECT COUNT(DISTINCT inspection_by) " + - " FROM inspection_data id " + - " WHERE id.ref_id = rd.ref_id AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - " ) = 3 " + - " THEN 1 ELSE 0 END), 0) AS committee_pending, " + - - " COALESCE(SUM(CASE WHEN rd.is_withdraw=1 THEN 1 ELSE 0 END), 0) AS withdrawn, " + - - " COALESCE(SUM(CASE " + - " WHEN rd.ref_id IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - " THEN 1 ELSE 0 END), 0) AS completed " + - - "FROM ward_master wm " + - "JOIN zone_master zm ON zm.id = wm.zone_id AND zm.zone_name = ? " + - "LEFT JOIN reg_details rd " + - " ON rd.ward = wm.ward_name " + - " AND rd.is_active = 1 "; - - StringBuilder sql = new StringBuilder(baseSql); - List params = new ArrayList<>(); - - params.add(zone); - - if (startDate != null && !startDate.isEmpty()) { - sql.append(" AND DATE(rd.cdate) >= ? "); - params.add(startDate); - } - - if (endDate != null && !endDate.isEmpty()) { - sql.append(" AND DATE(rd.cdate) <= ? "); - params.add(endDate); - } - - sql.append( - " WHERE wm.is_active=1 AND wm.is_delete=0 " + - " GROUP BY wm.zone_id, wm.ward_name " + - " ORDER BY wm.ward_name "); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - public List getPendingRefIds( - String zone, - String ward, - String type, - String startDate, - String endDate) { - - String baseSql; - - switch (type.toUpperCase()) { - - case "NGO": - baseSql = "SELECT rd.ref_id FROM reg_details rd " + - "WHERE rd.zone=? " + - "AND rd.is_active=1 AND rd.is_withdraw=0 " + - "AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - "AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - "AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='NGO' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - ")"; - break; - - case "GCC": - baseSql = "SELECT rd.ref_id FROM reg_details rd " + - "WHERE rd.zone=? " + - "AND rd.is_active=1 AND rd.is_withdraw=0 " + - "AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - "AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - "AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='GCC' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - ")"; - break; - - case "TNFD": - baseSql = "SELECT rd.ref_id FROM reg_details rd " + - "WHERE rd.zone=? " + - "AND rd.is_active=1 AND rd.is_withdraw=0 " + - "AND rd.ref_id NOT IN (SELECT ref_id FROM committee_data WHERE isactive=1) " + - "AND rd.ref_id NOT IN (SELECT ref_id FROM reinspection WHERE isactive=1) " + - "AND rd.ref_id NOT IN ( " + - " SELECT id.ref_id FROM inspection_data id " + - " WHERE id.inspection_by='TNFD' AND id.isactive=1 " + - " AND ( (rd.reinspection_id IS NULL AND id.reinspection_id IS NULL) " + - " OR (rd.reinspection_id = id.reinspection_id) ) " + - ")"; - break; - - case "WITHDRAW": - baseSql = "SELECT rd.ref_id FROM reg_details rd " + - "WHERE rd.zone=? AND rd.is_withdraw=1"; - break; - - default: - return Collections.emptyList(); - } - - StringBuilder sql = new StringBuilder(baseSql); - List params = new ArrayList<>(); - - params.add(zone); - - if (ward != null && !ward.isEmpty()) { - sql.append(" AND rd.ward = ? "); - params.add(ward); - } - - if (startDate != null && !startDate.isEmpty()) { - sql.append(" AND DATE(rd.cdate) >= ? "); - params.add(startDate); - } - - if (endDate != null && !endDate.isEmpty()) { - sql.append(" AND DATE(rd.cdate) <= ? "); - params.add(endDate); - } - - return jdbcTemplate.query( - sql.toString(), - params.toArray(), - (rs, rowNum) -> rs.getString("ref_id")); - } - - public Map getfulldetailsdata(String refId) { - - Map response = new HashMap<>(); - - // 1 — Application details - Map app = jdbcTemplate.queryForMap( - "SELECT *,DATE_FORMAT(cdate, '%d-%m-%Y %l:%i %p') as r_Cdate,IFNULL(reinspection_id, '') AS com_reinspection_id FROM reg_details WHERE ref_id=? AND is_active=1", - refId); - - // 2 — Complaint details (grouped) - List> complaints = jdbcTemplate.queryForList( - "SELECT cn.name AS nature, SUM(cd.no_of_trees) AS count " + - "FROM complaint_details cd JOIN comp_nature cn ON cn.id=cd.comp_nature_id " + - "WHERE cd.ref_id=? GROUP BY cn.name", - refId); - - String compDetails = complaints.stream() - .map(c -> c.get("nature") + "-" + c.get("count")) - .collect(Collectors.joining(",")); - - // 3 — Complaint images - List> imagePaths = jdbcTemplate.queryForList( - "SELECT img_path FROM img_uploads WHERE ref_id=? AND is_active=1", - new Object[] { refId }).stream() - .map(row -> { - Map img = new HashMap<>(); - img.put( - "img_path", - fileBaseUrl + "/gccofficialapp/files" + row.get("img_path").toString()); - return img; - }) - .collect(Collectors.toList()); - - app.put("complaints", complaints); - app.put("comp_details", compDetails); - app.put("image_paths", imagePaths); - - response.put("data", app); - - return response; - } - - public List> getDepartments() { - - String sql = "SELECT id, name FROM dept_master WHERE is_active = 1 ORDER BY id"; - - return jdbcTemplate.queryForList(sql); - } - - public List> getZones() { - - String sql = """ - SELECT id, zone_name - FROM gcc_street_vendor.zone_master - ORDER BY zone_name - """; - - return jdbcTemplate.queryForList(sql); - } - - public List> getWards(Integer zoneId) { - - String sql = """ - SELECT id, - ward_name - FROM gcc_street_vendor.ward_master - WHERE zone_id=? - ORDER BY ward_name - """; - - return jdbcTemplate.queryForList(sql, zoneId); - - } - - public List> getReport( - String fromDate, - String toDate, - String zone, - String ward, - String status) { - - List> result = new ArrayList<>(); - - try { - - String externalUrl = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice"; - - StringBuilder url = new StringBuilder(externalUrl); - - url.append("?serviceId=ms_dashboard_details"); - - // Mandatory - url.append("&From_date=").append(URLEncoder.encode(fromDate, "UTF-8")); - url.append("&To_date=").append(URLEncoder.encode(toDate, "UTF-8")); - url.append("&jsonResp=Yes"); - - // Status - if (status == null || status.trim().isEmpty()) { - url.append("&Status=total"); - } else { - url.append("&Status=").append(URLEncoder.encode(status, "UTF-8")); - } - - // Mandatory Parameters - url.append("&isQcuser=Yes"); - url.append("&ComplaintType=") - .append(URLEncoder.encode("Tree Pruning", "UTF-8")); - - url.append("&ComplaintGroupId=") - .append(URLEncoder.encode("Park and Playground", "UTF-8")); - - // Zone - if (zone != null && !zone.trim().isEmpty()) { - url.append("&Zoneid=N") - .append(String.format("%02d", Integer.parseInt(zone))); - } else { - url.append("&Zoneid="); - } - - // Mandatory blank - url.append("&RegionId="); - - // Ward - if (ward != null && !ward.trim().isEmpty()) { - url.append("&WardId=N") - .append(String.format("%03d", Integer.parseInt(ward))); - } else { - url.append("&WardId="); - } - - System.out.println("======================================"); - System.out.println("Calling URL:"); - System.out.println(url.toString()); - System.out.println("======================================"); - - URL api = new URL(url.toString()); - - HttpURLConnection conn = (HttpURLConnection) api.openConnection(); - conn.setRequestMethod("GET"); - conn.setRequestProperty("Accept", "application/json"); - - int responseCode = conn.getResponseCode(); - - System.out.println("Response Code : " + responseCode); - - BufferedReader br; - - if (responseCode >= 200 && responseCode < 300) { - br = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - } else { - br = new BufferedReader( - new InputStreamReader(conn.getErrorStream())); - } - - StringBuilder response = new StringBuilder(); - - String line; - - while ((line = br.readLine()) != null) { - response.append(line); - } - - br.close(); - - System.out.println("API Response:"); - System.out.println(response.toString()); - - ObjectMapper mapper = new ObjectMapper(); - - JsonNode root = mapper.readTree(response.toString()); - - JsonNode details = root.get("Details"); - - if (details != null && details.isArray()) { - - result = mapper.convertValue( - details, - new TypeReference>>() { - }); - - } - - } catch (Exception e) { - - e.printStackTrace(); - - } - - return result; - } - - public Map getComplaintDetailsreport(String complaintId) { - - try { - - String url = "https://erp.chennaicorporation.gov.in/pgr/newmobileservice" - + "?serviceId=getComplaintByID" - + "&ComplaintId=" + URLEncoder.encode(complaintId, "UTF-8") - + "&imgUrlonly=yes" - + "&isQcuser=Yes" - + "&jsonResp=Yes"; - - HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); - - conn.setRequestMethod("GET"); - - BufferedReader br = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - - StringBuilder sb = new StringBuilder(); - - String line; - - while ((line = br.readLine()) != null) { - sb.append(line); - } - - br.close(); - - ObjectMapper mapper = new ObjectMapper(); - - List> response = mapper.readValue( - sb.toString(), - new TypeReference>>() { - }); - - Map root = response.get(0); - - List> history = (List>) root.get("ComplaintListHistory"); - - return history.get(0); - - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Controller/HomelessSurveyController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Controller/HomelessSurveyController.java deleted file mode 100644 index ad91febc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Controller/HomelessSurveyController.java +++ /dev/null @@ -1,815 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.homelesssurvey.Controller; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.net.URL; -import java.net.http.HttpHeaders; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.Resource; - -import in.gov.chennaicorporation.gccoffice.homelesssurvey.Service.HomelessSurveyService; - -@RestController -@RequestMapping("/gcc/api/homeless-survey") -public class HomelessSurveyController { - - @Autowired - private HomelessSurveyService service; - - @GetMapping("/list") - public ResponseEntity>> getHomelessSurveyList( - - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate) { - - return ResponseEntity.ok( - service.getHomelessSurveyList( - zone, - ward, - fromDate, - toDate)); - } - - @GetMapping("/zones") - public ResponseEntity>> getZones() { - - return ResponseEntity.ok( - service.getZones()); - } - - @GetMapping("/wards") - public ResponseEntity>> getWards( - @RequestParam String zoneId) { - - return ResponseEntity.ok( - service.getWards(zoneId)); - } - - @GetMapping("/nonsurveyed/list") - @ResponseBody - public List> getHomelessNonSurveyedList( - - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate) { - - return service.getHomelessNonSurveyedList( - zone, - ward, - fromDate, - toDate); - } - - @GetMapping("/details") - public ResponseEntity>> getSurveyDetails( - @RequestParam String surveyId) { - - return ResponseEntity.ok( - service.getHomelessSurveyDetails(surveyId)); - } - - @GetMapping("/document-count") - public ResponseEntity getDocumentCount( - @RequestParam String surveyId) { - - return ResponseEntity.ok( - service.getDocumentCount(surveyId)); - } - - @GetMapping("/documents") - public ResponseEntity>> getDocuments( - @RequestParam String surveyId) { - System.out.println("surveyId"); - System.out.println(surveyId); - - return ResponseEntity.ok( - service.getSurveyDocuments(surveyId)); - } - - /* - * @GetMapping("/download") - * public ResponseEntity downloadFile( - * - * @RequestParam String fileUrl) throws Exception { - * - * URL url = new URL(fileUrl); - * - * InputStream inputStream = url.openStream(); - * - * byte[] bytes = inputStream.readAllBytes(); - * - * ByteArrayResource resource = new ByteArrayResource(bytes); - * - * String fileName = fileUrl.substring( - * fileUrl.lastIndexOf("/") + 1); - * - * return ResponseEntity.ok() - * .header( - * HttpHeaders.CONTENT_DISPOSITION, - * "attachment; filename=\"" + - * fileName + "\"") - * .contentLength(bytes.length) - * .body(resource); - * } - */ - @GetMapping("/download-all-documents") - public ResponseEntity downloadAllDocuments( - @RequestParam String surveyId) throws Exception { - - List> documents = service.getSurveyDocuments(surveyId); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ZipOutputStream zipOut = new ZipOutputStream(baos); - - for (Map doc : documents) { - - String fileUrl = String.valueOf(doc.get("file_url")); - - String documentName = String.valueOf(doc.get("document_name")) - .replaceAll("\\s+", "_"); - - URL url = new URL(fileUrl); - - InputStream is = url.openStream(); - - byte[] fileBytes = is.readAllBytes(); - - String extension = fileUrl.substring(fileUrl.lastIndexOf(".")); - - ZipEntry zipEntry = new ZipEntry( - documentName + "_" + - surveyId + - extension); - - zipOut.putNextEntry(zipEntry); - - zipOut.write(fileBytes); - - zipOut.closeEntry(); - - is.close(); - } - - zipOut.close(); - - return ResponseEntity.ok() - .header( - "Content-Disposition", - "attachment; filename=\"" - + surveyId - + "_Documents.zip\"") - .header( - "Content-Type", - "application/zip") - .body(baos.toByteArray()); - } - - /* - * @GetMapping("/download-document") - * public ResponseEntity downloadDocument( - * - * @RequestParam String fileUrl, - * - * @RequestParam String fileName) { - * - * try { - * - * URL url = new URL(fileUrl); - * - * InputStream is = url.openStream(); - * - * byte[] fileBytes = is.readAllBytes(); - * - * String extension = fileUrl.substring( - * fileUrl.lastIndexOf(".")); - * - * return ResponseEntity.ok() - * .header( - * "Content-Disposition", - * "attachment; filename=\"" + fileName + extension + "\"") - * .header( - * "Content-Type", - * "application/octet-stream") - * .body(fileBytes); - * - * } catch (Exception e) { - * - * throw new RuntimeException(e); - * } - * } - */ - @GetMapping("/categories") - public ResponseEntity>> getCategories() { - - return ResponseEntity.ok( - service.getCategories()); - } - - @GetMapping("/getSurveyorsList") - @ResponseBody - public List> getSurveyorsList( - - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam(required = false) String fromDate, - @RequestParam(required = false) String toDate) { - - return service.getSurveyorsList( - zone, - ward, - fromDate, - toDate); - } - - @GetMapping("/surveyor-details") - public ResponseEntity>> getSurveyorDetails( - - @RequestParam String loginId, - @RequestParam String zone, - @RequestParam String ward, - @RequestParam String surveyDate) { - - return ResponseEntity.ok( - service.getSurveyorWiseSurveyList( - loginId, - zone, - ward, - surveyDate)); - } - - @GetMapping("/gendermasterlist") - public List> getGenderList() { - - return service.getGenderList(); - } - - @PostMapping("/gendersave") - public String saveGender( - @RequestBody Map req) { - - service.saveGender(req); - - return "SUCCESS"; - } - - @PostMapping("/gender-status") - public String updateGenderStatus( - @RequestBody Map req) { - - service.updateGenderStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/relationtypemasterlist") - public List> getRelationTypeList() { - - return service.getRelationTypeList(); - } - - @PostMapping("/relationtypesave") - public String saveRelationType( - @RequestBody Map req) { - - service.saveRelationType(req); - - return "SUCCESS"; - } - - @PostMapping("/relationtype-status") - public String updateRelationTypeStatus( - @RequestBody Map req) { - - service.updateRelationTypeStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/currentlylivingmasterlist") - public List> getCurrentlyLivingList() { - - return service.getCurrentlyLivingList(); - } - - @PostMapping("/currentlylivingsave") - public String saveCurrentlyLiving( - @RequestBody Map req) { - - service.saveCurrentlyLiving(req); - - return "SUCCESS"; - } - - @PostMapping("/currentlyliving-status") - public String updateCurrentlyLivingStatus( - @RequestBody Map req) { - - service.updateCurrentlyLivingStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/martialmasterlist") - public List> getMartialList() { - - return service.getMartialList(); - } - - @PostMapping("/martialsave") - public String saveMartial( - @RequestBody Map req) { - - service.saveMartial(req); - - return "SUCCESS"; - } - - @PostMapping("/martial-status") - public String updateMartialStatus( - @RequestBody Map req) { - - service.updateMartialStatus(req); - - return "SUCCESS"; - } - - @GetMapping("/disabilitytype") - public List> getDisabilityTypeList() { - return service.getDisabilityTypeList(); - } - - @PostMapping("/disabilitytypesave") - public String saveDisabilityType( - @RequestBody Map req) { - service.saveDisabilityType(req); - return "SUCCESS"; - } - - @PostMapping("/disabilitytype-status") - public String updateDisabilityTypeStatus( - @RequestBody Map req) { - service.updateDisabilityTypeStatus(req); - return "SUCCESS"; - } - - @GetMapping("/disabiltycertificatelist") - public List> getDisabilityCertificateMasterList() { - return service.getDisabilityCertificateMasterList(); - } - - @PostMapping("/disabiltycertificategersave") - public String saveDisabilityCertificateMaster( - @RequestBody Map req) { - service.saveDisabilityCertificateMaster(req); - return "SUCCESS"; - } - - @PostMapping("/disabiltycertificate-status") - public String updateDisabilityCertificateMasterStatus( - @RequestBody Map req) { - service.updateDisabilityCertificateMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/healthconditionlist") - public List> getHealthConditionList() { - return service.getHealthConditionList(); - } - - @PostMapping("/healthconditionsave") - public String saveHealthCondition( - @RequestBody Map req) { - service.saveHealthCondition(req); - return "SUCCESS"; - } - - @PostMapping("/healthcondition-status") - public String updateHealthConditionStatus( - @RequestBody Map req) { - service.updateHealthConditionStatus(req); - return "SUCCESS"; - } - - @GetMapping("/educationmasterlist") - public List> getEducationMasterList() { - return service.getEducationMasterList(); - } - - @PostMapping("/educationsave") - public String saveEducationMaster( - @RequestBody Map req) { - service.saveEducationMaster(req); - return "SUCCESS"; - } - - @PostMapping("/education-status") - public String updateEducationMasterStatus( - @RequestBody Map req) { - service.updateEducationMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/discontinuedlist") - public List> getDiscontinuedList() { - return service.getDiscontinuedList(); - } - - @PostMapping("/discontinuedsave") - public String saveDiscontinuedMaster( - @RequestBody Map req) { - service.saveDiscontinuedMaster(req); - return "SUCCESS"; - } - - @PostMapping("/discontinued-status") - public String updateDiscontinuedMasterStatus( - @RequestBody Map req) { - service.updateDiscontinuedMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/employmenttypelist") - public List> getEmploymentTypeList() { - return service.getEmploymentTypeList(); - } - - @PostMapping("/employmenttypesave") - public String saveEmploymentType( - @RequestBody Map req) { - service.saveEmploymentType(req); - return "SUCCESS"; - } - - @PostMapping("/employmenttype-status") - public String updateEmploymentTypeStatus( - @RequestBody Map req) { - service.updateEmploymentTypeStatus(req); - return "SUCCESS"; - } - - @GetMapping("/occupationlist") - public List> getOccupationList() { - return service.getOccupationList(); - } - - @PostMapping("/occupationsave") - public String saveOccupation( - @RequestBody Map req) { - service.saveOccupation(req); - return "SUCCESS"; - } - - @PostMapping("/occupation-status") - public String updateOccupationStatus( - @RequestBody Map req) { - service.updateOccupationStatus(req); - return "SUCCESS"; - } - - @GetMapping("/notemployedlist") - public List> getNotEmployedList() { - return service.getNotEmployedList(); - } - - @PostMapping("/notemployedsave") - public String saveNotEmployed( - @RequestBody Map req) { - service.saveNotEmployed(req); - return "SUCCESS"; - } - - @PostMapping("/notemployed-status") - public String updateNotEmployedStatus( - @RequestBody Map req) { - service.updateNotEmployedStatus(req); - return "SUCCESS"; - } - - @GetMapping("/homelessreasonmasterlist") - public List> getReasonHomelessList() { - return service.getReasonHomelessList(); - } - - @PostMapping("/homelessreasonmasterlist") - public String saveReasonHomeless( - @RequestBody Map req) { - service.saveHomelessReason(req); - return "SUCCESS"; - } - - @PostMapping("/homelessreasonmaster-status") - public String updateHomelessReasonStatus( - @RequestBody Map req) { - service.updateHomelessReasonStatus(req); - return "SUCCESS"; - } - - @GetMapping("/sleepingspacemasterlist") - public List> getSleepingSpaceList() { - return service.getSleepingSpaceList(); - } - - @PostMapping("/sleepingspacesave") - public String saveSleepingSpace( - @RequestBody Map req) { - service.saveSleepingSpace(req); - return "SUCCESS"; - } - - @PostMapping("/sleepingspace-status") - public String updateSleepingSpaceStatus( - @RequestBody Map req) { - service.updateSleepingSpaceStatus(req); - return "SUCCESS"; - } - - @GetMapping("/movingreasonmasterlist") - public List> getMovingReasonList() { - return service.getMovingReasonList(); - } - - @PostMapping("/movingreasonmasterdatasave") - public String saveMovingReason( - @RequestBody Map req) { - service.saveMovingReason(req); - return "SUCCESS"; - } - - @PostMapping("/movingreasonmasterdata-status") - public String updateMovingReasonStatus( - @RequestBody Map req) { - service.updateMovingReasonStatus(req); - return "SUCCESS"; - } - - @GetMapping("/comeoutsheltermasterlist") - public List> getComeOutShelterList() { - return service.getComeOutShelterList(); - } - - @PostMapping("/comeoutsheltersave") - public String saveComeOutShelter( - @RequestBody Map req) { - service.saveComeOutShelter(req); - return "SUCCESS"; - } - - @PostMapping("/comeoutshelter-status") - public String updateComeOutShelterStatus( - @RequestBody Map req) { - service.updateComeOutShelterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/gccsheltermasterlist") - public List> getGCCShelterMasterList() { - return service.getGCCShelterMasterList(); - } - - @PostMapping("/gccsheltermasterdatasave") - public String saveGCCShelterMaster( - @RequestBody Map req) { - service.saveGCCShelterMaster(req); - return "SUCCESS"; - } - - @PostMapping("/gccsheltermasterdata-status") - public String updateGCCShelterMasterStatus( - @RequestBody Map req) { - service.updateGCCShelterMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/birthcertificatmasterlist") - public List> getBirthCertificateNoReasonMasterList() { - return service.getBirthCertificateNoReasonMasterList(); - } - - @PostMapping("/birthcertificatmasterdatasave") - public String saveBirthCertificateNoReasonMaster( - @RequestBody Map req) { - service.saveBirthCertificateNoReasonMaster(req); - return "SUCCESS"; - } - - @PostMapping("/birthcertificatmasterdata-status") - public String updateBirthCertificateNoReasonMasterStatus( - @RequestBody Map req) { - service.updateBirthCertificateNoReasonMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/communitymasterlist") - public List> getCommunityMasterList() { - return service.getCommunityMasterList(); - } - - @PostMapping("/communitycertmasterdatasave") - public String saveCommunityMaster( - @RequestBody Map req) { - service.saveCommunityMaster(req); - return "SUCCESS"; - } - - @PostMapping("/communitycertmasterdata-status") - public String updateCommunityMasterStatus( - @RequestBody Map req) { - service.updateCommunityMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/voteridmasterlist") - public List> getVoterIdMasterList() { - return service.getVoterIdMasterList(); - } - - @PostMapping("/voteridmastersave") - public String saveVoterIdMaster( - @RequestBody Map req) { - service.saveVoterIdMaster(req); - return "SUCCESS"; - } - - @PostMapping("/voteridmaster-status") - public String updateVoterIdMasterStatus( - @RequestBody Map req) { - service.updateVoterIdMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/aadharnoreasonlst") - public List> getAadharCertificateNoReasonMasterList() { - return service.getAadharCertificateNoReasonMasterList(); - } - - @PostMapping("/aadharnoreasonsave") - public String saveAadharCertificateNoReasonMaster( - @RequestBody Map req) { - service.saveAadharCertificateNoReasonMaster(req); - return "SUCCESS"; - } - - @PostMapping("/aadharnoreason-status") - public String updateAadharCertificateNoReasonMasterStatus( - @RequestBody Map req) { - service.updateAadharCertificateNoReasonMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/smartcardnoreasonmasterlist") - public List> getSmartCardNoReasonMasterList() { - return service.getSmartCardNoReasonMasterList(); - } - - @PostMapping("/smartcardnoreasonsave") - public String saveSmartCardNoReasonMaster( - @RequestBody Map req) { - service.saveSmartCardNoReasonMaster(req); - return "SUCCESS"; - } - - @PostMapping("/smartcardnoreasonstatus") - public String updateSmartCardNoReasonMasterStatus( - @RequestBody Map req) { - service.updateSmartCardNoReasonMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/driverlicensemasterlist") - public List> getDriverLicenseNoReasonMasterList() { - return service.getDriverLicenseNoReasonMasterList(); - } - - @PostMapping("/driverlicensesave") - public String saveDriverLicenseNoReasonMaster( - @RequestBody Map req) { - service.saveDriverLicenseNoReasonMaster(req); - return "SUCCESS"; - } - - @PostMapping("/driverlicense-status") - public String updateDriverLicenseNoReasonMasterStatus( - @RequestBody Map req) { - service.updateDriverLicenseNoReasonMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/cminsurancemasterlist") - public List> getCmInsuranceNoReasonMasterList() { - return service.getCmInsuranceNoReasonMasterList(); - } - - @PostMapping("/cminsurancesave") - public String saveCmInsuranceNoReasonMaster( - @RequestBody Map req) { - service.saveCmInsuranceNoReasonMaster(req); - return "SUCCESS"; - } - - @PostMapping("/cminsurance-status") - public String updateCmInsuranceNoReasonMasterStatus( - @RequestBody Map req) { - service.updateCmInsuranceNoReasonMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/bankpassbookreasonmasterlist") - public List> getBankPassbookNoReasonMasterList() { - return service.getBankPassbookNoReasonMasterList(); - } - - @PostMapping("/bankpassbookreasonmaster-save") - public String saveBankPassbookNoReasonMaster( - @RequestBody Map req) { - service.saveBankPassbookNoReasonMaster(req); - return "SUCCESS"; - } - - @PostMapping("/bankpassbookreasonmasterstatus") - public String updateBankPassbookNoReasonMasterStatus( - @RequestBody Map req) { - service.updateBankPassbookNoReasonMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/religionmasterlist") - public List> getReligionMasterList() { - return service.getReligionMasterList(); - } - - @PostMapping("/religionmasterdatasave") - public String saveReligionMaster( - @RequestBody Map req) { - service.saveReligionMaster(req); - return "SUCCESS"; - } - - @PostMapping("/religionmasterdata-status") - public String updateReligionMasterStatus( - @RequestBody Map req) { - service.updateReligionMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/castemasterlist") - public List> getCasteMasterList() { - return service.getCasteMasterList(); - } - - @PostMapping("/castemasterdatasave") - public String saveCasteMaster( - @RequestBody Map req) { - service.saveCasteMaster(req); - return "SUCCESS"; - } - - @PostMapping("/castemasterdata-status") - public String updateCasteMasterStatus( - @RequestBody Map req) { - service.updateCasteMasterStatus(req); - return "SUCCESS"; - } - - @GetMapping("/dashboard") - public ResponseEntity> getDashboard() { - - return ResponseEntity.ok( - service.getDashboard()); - } - - @GetMapping("/zone-wise") - public ResponseEntity>> getZoneWiseCount() { - - return ResponseEntity.ok( - service.getZoneWiseCount()); - } - - @GetMapping("/ward-wise") - public ResponseEntity>> getWardWiseCount( - @RequestParam String zone) { - - return ResponseEntity.ok( - service.getWardWiseCount(zone)); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Controller/MainController.java deleted file mode 100644 index 839a6861..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Controller/MainController.java +++ /dev/null @@ -1,168 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.homelesssurvey.Controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller("HomelessSurveyController") -@RequestMapping("/gcc/homelesssurvey") -public class MainController { - - @GetMapping("/homelesslist/surveyedlist") - public String surveyedlist() { - return "modules/homelesssurvey/homelesslist"; - } - - @GetMapping("/homelesslist/nonsurveyedlist") - public String nonsurveyedlist() { - return "modules/homelesssurvey/nonsurveyedhomelist"; - } - - @GetMapping("/surveylist") - - public String surveylist() { - return "modules/homelesssurvey/surveyorlist"; - } - - @GetMapping("/surveyorsreports") - - public String surveyorsreports() { - return "modules/homelesssurvey/surveyorsreports"; - } - - @GetMapping("/homelesslist/gender") - public String gender() { - return "modules/homelesssurvey/gendermaster"; - } - - @GetMapping("/homelesslist/relationtype") - public String relationtype() { - return "modules/homelesssurvey/relationtype"; - } - - @GetMapping("/homelesslist/currentlyliving") - public String currentlyliving() { - return "modules/homelesssurvey/currentlyliving"; - } - - @GetMapping("/homelesslist/martial") - public String martialstatus() { - return "modules/homelesssurvey/martial"; - } - - @GetMapping("/homelesslist/disabilitytype") - public String disabilitytype() { - return "modules/homelesssurvey/disability"; - } - - @GetMapping("/homelesslist/diable") - public String disabiltycertificate() { - return "modules/homelesssurvey/disabiltycertificate"; - } - - @GetMapping("/homelesslist/healthcondition") - public String healthcondition() { - return "modules/homelesssurvey/healthcondition"; - } - - @GetMapping("/homelesslist/education") - public String education() { - return "modules/homelesssurvey/education"; - } - - @GetMapping("/homelesslist/discontinued") - public String discontinued() { - return "modules/homelesssurvey/discontinued"; - } - - @GetMapping("/homelesslist/employment") - public String employmenttype() { - return "modules/homelesssurvey/employmenttype"; - } - - @GetMapping("/homelesslist/occupation") - public String occupation() { - return "modules/homelesssurvey/occupation"; - } - - @GetMapping("/homelesslist/notemployed") - public String notemployed() { - return "modules/homelesssurvey/notemployed"; - } - - @GetMapping("/homelesslist/homeless") - public String homelessreason() { - return "modules/homelesssurvey/homelessreason"; - } - - @GetMapping("/homelesslist/sleepingspace") - public String sleepingspace() { - return "modules/homelesssurvey/sleepingspace"; - } - - @GetMapping("/homelesslist/moving") - public String movingreason() { - return "modules/homelesssurvey/movingreason"; - } - - @GetMapping("/homelesslist/comeoutshelter") - public String comeoutshelter() { - return "modules/homelesssurvey/comeoutshelter"; - } - - @GetMapping("/homelesslist/gccshelter") - public String gccshelter() { - return "modules/homelesssurvey/gccshelter"; - } - - @GetMapping("/homelesslist/birthcertificate") - public String birthcertficatenoreason() { - return "modules/homelesssurvey/birthcertficatenoreason"; - } - - @GetMapping("/homelesslist/communitycertificate") - public String communitycertificate() { - return "modules/homelesssurvey/communitynoreason"; - } - - @GetMapping("/homelesslist/votercertificate") - public String voterid() { - return "modules/homelesssurvey/voterid"; - } - - @GetMapping("/homelesslist/aadharcertificate") - public String aadhar() { - return "modules/homelesssurvey/aadhar"; - } - - @GetMapping("/homelesslist/smartcertificate") - public String smartcard() { - return "modules/homelesssurvey/smart"; - } - - @GetMapping("/homelesslist/drivercertificate") - public String driverlicense() { - return "modules/homelesssurvey/driver"; - } - - @GetMapping("/homelesslist/cmrcertificate") - public String cminsurance() { - return "modules/homelesssurvey/cminsurance"; - } - - @GetMapping("/homelesslist/bankpassbook") - public String bankpassbook() { - return "modules/homelesssurvey/bankpassbook"; - } - - @GetMapping("/homelesslist/religion") - public String religion() { - return "modules/homelesssurvey/religion"; - } - - @GetMapping("/homelesslist/caste") - public String caste() { - return "modules/homelesssurvey/caste"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Service/HomelessSurveyService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Service/HomelessSurveyService.java deleted file mode 100644 index b3fffed1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/homelesssurvey/Service/HomelessSurveyService.java +++ /dev/null @@ -1,4103 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.homelesssurvey.Service; - -import java.nio.file.Path; -import java.sql.PreparedStatement; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; -import java.nio.file.Files; -import javax.sql.DataSource; -import java.nio.file.Paths; -import java.awt.image.BufferedImage; -import javax.imageio.ImageIO; -import java.io.ByteArrayInputStream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -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.web.multipart.MultipartFile; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.stream.ImageOutputStream; -import java.sql.Statement; -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; -import in.gov.chennaicorporation.gccoffice.nulm.repository.NulmRepository; - -@Service -public class HomelessSurveyService { - @Autowired - @Value("${fileBaseUrl}") - - private String fileBaseUrl; - - @Autowired - private JdbcTemplate jdbcTemplate; - @Autowired - private Environment environment; - - @Autowired - public void setDataSource(@Qualifier("mysqlHomelessSurveyDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public HomelessSurveyService(Environment environment) { - - this.environment = environment; - - this.fileBaseUrl = environment.getProperty("fileBaseUrl"); - } - - public List> getHomelessSurveyList( - String zone, - String ward, - String fromDate, - String toDate) { - - StringBuilder sql = new StringBuilder(""" - - SELECT - - DATE(MAX(hr.cdate)) AS survey_date, - - hr.survey_id, - - MAX(CASE - WHEN hr.qid = 2 - THEN hr.answer - END) AS name, - - MAX( - CASE - WHEN hr.qid = 7 - THEN CASE - WHEN hr.others_answer IS NOT NULL - AND TRIM(hr.others_answer) <> '' - THEN hr.others_answer - ELSE gm.english_name - END - END - ) AS gender, - - sld.zone AS zone, - - sld.ward AS ward - - FROM homeless_survey_response hr - - LEFT JOIN gender_master gm - ON hr.qid = 7 - AND gm.id = hr.answer - - LEFT JOIN surveyor_location_details sld - ON sld.survey_id = hr.survey_id - - - - - WHERE hr.isactive = 1 - AND hr.isdelete = 0 - AND NOT EXISTS ( - SELECT 1 - FROM homeless_survey_response hr2 - INNER JOIN homeless_survey_questions_master hqm2 - ON hqm2.qid = hr2.qid - WHERE hr2.survey_id = hr.survey_id - AND hqm2.flag = 'N' - ) - - """); - - List params = new ArrayList<>(); - - if (zone != null && !zone.isBlank()) { - - sql.append(""" - AND CAST(sld.zone AS UNSIGNED) = ? - """); - - params.add(zone); - } - - if (ward != null && !ward.isBlank()) { - - sql.append(""" - AND CAST(sld.ward AS UNSIGNED) = ? - """); - - params.add(ward); - } - - if (fromDate != null && !fromDate.isBlank() - && toDate != null && !toDate.isBlank()) { - - sql.append(""" - AND DATE(hr.cdate) BETWEEN ? AND ? - """); - - params.add(fromDate); - params.add(toDate); - } - - sql.append(""" - - GROUP BY - - hr.survey_id, - sld.zone, - sld.ward - - ORDER BY - - MAX(hr.cdate) DESC - - """); - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray()); - } - - public List> getZones() { - - String sql = """ - - SELECT - - id, - zone_name - FROM gcc_street_vendor.zone_master - ORDER BY zone_name - - """; - - return jdbcTemplate.queryForList(sql); - } - - public List> getWards(String zoneId) { - - String sql = """ - - SELECT - id, - ward_name - FROM gcc_street_vendor.ward_master - WHERE zone_id = ? - ORDER BY ward_name - - """; - - return jdbcTemplate.queryForList( - sql, - zoneId); - } - - public List> getHomelessNonSurveyedList( - String zone, - String ward, - String fromDate, - String toDate) { - - StringBuilder sql = new StringBuilder( - - "SELECT " + - - "DATE(MAX(hr.cdate)) AS survey_date, " + - "hr.survey_id, " + - - "MAX(CASE " + - "WHEN hr.qid = 2 THEN hr.answer " + - "END) AS name, " + - - "MAX(CASE " + - "WHEN hr.qid = 78 THEN hr.answer " + - "END) AS age, " + - - "MAX(CASE " + - "WHEN hr.qid = 8 THEN hr.answer " + - "END) AS dob, " + - - "MAX(CASE " + - "WHEN hr.qid = 79 THEN hr.answer " + - "END) AS remarks, " + - - "IFNULL(MAX(CASE " + - "WHEN hr.qid = 77 " + - "THEN CONCAT('" + fileBaseUrl + "/gccofficialapp/files', hr.answer) " + - "END),'') AS image_url, " + - - "sld.zone AS zone, " + - "sld.ward AS ward " + - - "FROM homeless_survey_response hr " + - - "LEFT JOIN surveyor_location_details sld " + - "ON sld.survey_id = hr.survey_id " + - - "WHERE hr.isactive = 1 " + - "AND hr.isdelete = 0 " + - "AND EXISTS ( " + - "SELECT 1 " + - "FROM homeless_survey_response hr2 " + - "INNER JOIN homeless_survey_questions_master hqm2 " + - "ON hqm2.qid = hr2.qid " + - "WHERE hr2.survey_id = hr.survey_id " + - "AND hqm2.flag = 'N')"); - - List params = new ArrayList<>(); - - if (zone != null && !zone.isBlank()) { - - sql.append( - " AND CAST(sld.zone AS UNSIGNED) = ? "); - - params.add(Integer.parseInt(zone)); - } - - if (ward != null && !ward.isBlank()) { - - sql.append( - " AND CAST(sld.ward AS UNSIGNED) = ? "); - - params.add(Integer.parseInt(ward)); - } - - if (fromDate != null - && !fromDate.isBlank() - && toDate != null - && !toDate.isBlank()) { - - sql.append( - " AND DATE(hr.cdate) BETWEEN ? AND ? "); - - params.add(fromDate); - params.add(toDate); - } - - sql.append( - - " GROUP BY " + - " hr.survey_id, " + - " sld.zone, " + - " sld.ward " + - - " ORDER BY MAX(hr.cdate) DESC "); - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray()); - } - - public List> getHomelessSurveyDetails( - String surveyId) { - - String sql = - - "SELECT " + - - "hqm.cid, " + - "qcm.english_name AS category_name, " + - - "hqm.qid, " + - "hqm.q_english AS question, " + - "hqm.question_type, " + - "hqm.master_table_name, " + - - "CASE " + - - "WHEN hqm.question_type = 'image' " + - "THEN CONCAT('" + fileBaseUrl + "/gccofficialapp/files', hr.answer) " + - - "WHEN hr.others_answer IS NOT NULL " + - "AND TRIM(hr.others_answer) <> '' " + - "THEN hr.others_answer " + - - "WHEN hqm.question_type = 'radio' " + - "THEN ham.answer " + - - "ELSE hr.answer " + - - "END AS answer " + - - "FROM homeless_survey_response hr " + - - "INNER JOIN homeless_survey_questions_master hqm " + - "ON hqm.qid = hr.qid " + - - "LEFT JOIN question_category_master qcm " + - "ON qcm.id = hqm.cid " + - - "LEFT JOIN homeless_survey_answer_master ham " + - "ON ham.qid = hr.qid " + - "AND ham.id = CAST(hr.answer AS UNSIGNED) " + - - "WHERE hr.survey_id = ? " + - "AND hr.isactive = 1 " + - "AND hr.isdelete = 0 " + - - "ORDER BY hqm.cid, hqm.orderby"; - - List> result = jdbcTemplate.queryForList( - sql, - surveyId); - - for (Map row : result) { - - String questionType = row.get("question_type") == null - ? "" - : row.get("question_type").toString(); - - String masterTable = row.get("master_table_name") == null - ? "" - : row.get("master_table_name").toString(); - - /* - * String answer = row.get("answer") == null - * ? "" - * : row.get("answer").toString(); - */ - String answer = row.get("answer") == null - ? "" - : row.get("answer").toString().trim(); - - try { - - // DROPDOWN - if ("dropdown".equalsIgnoreCase(questionType) - && !masterTable.isBlank() - && answer.matches("\\d+")) { - - String valueSql = "SELECT english_name FROM " - + masterTable - + " WHERE id = ?"; - - String value = jdbcTemplate.queryForObject( - valueSql, - String.class, - Integer.parseInt(answer)); - - row.put("answer", value); - } - - // CHECKBOX / MULTICHECK - else if (("checkbox".equalsIgnoreCase(questionType) - || "multicheck".equalsIgnoreCase(questionType)) - && !masterTable.isBlank() - && !answer.isBlank()) { - - String[] ids = answer.split(","); - - StringBuilder placeholders = new StringBuilder(); - - for (int i = 0; i < ids.length; i++) { - - placeholders.append("?"); - - if (i < ids.length - 1) { - placeholders.append(","); - } - } - - String checkboxSql = "SELECT english_name FROM " - + masterTable - + " WHERE id IN (" - + placeholders - + ") ORDER BY id"; - - List values = jdbcTemplate.query( - checkboxSql, - ids, - (rs, rowNum) -> rs.getString("english_name")); - - row.put( - "answer", - String.join(", ", values)); - } - - } catch (Exception e) { - - System.out.println( - "Master value fetch failed for qid : " - + row.get("qid")); - } - } - - return result; - } - - public List> getSurveyDocuments(String surveyId) { - - String sql = - - "SELECT " + - - "hr.survey_id, " + - - "(" + - " SELECT q2.q_english " + - " FROM homeless_survey_questions_master q2 " + - " WHERE q2.cid = hqm.cid " + - " AND q2.question_type = 'radio' " + - " AND q2.orderby < hqm.orderby " + - " ORDER BY q2.orderby DESC " + - " LIMIT 1 " + - ") AS document_name, " + - - "CONCAT('" + fileBaseUrl + - "/gccofficialapp/files', hr.answer) AS file_url " + - - "FROM homeless_survey_response hr " + - - "INNER JOIN homeless_survey_questions_master hqm " + - "ON hqm.qid = hr.qid " + - - "WHERE hr.survey_id = ? " + - "AND hqm.cid = 5 " + - "AND hqm.question_type = 'image' " + - - "ORDER BY hqm.orderby"; - - return jdbcTemplate.queryForList( - sql, - surveyId); - } - - /* - * public List> getSurveyDocuments(String surveyId) { - * - * String sql = "SELECT " + - * "hr.survey_id, " + - * "hqm.q_english, " + - * "CONCAT('" + fileBaseUrl + - * "/gccofficialapp/files', hr.answer) AS file_url " + - * - * "FROM homeless_survey_response hr " + - * - * "INNER JOIN homeless_survey_questions_master hqm " + - * "ON hqm.qid = hr.qid " + - * - * "WHERE hr.survey_id = ? " + - * "AND hqm.cid = 5 " + - * "AND hqm.question_type = 'image'"; - * - * return jdbcTemplate.queryForList(sql, surveyId); - * } - */ - public List> getCategories() { - - String sql = - - "SELECT " + - "id, " + - "english_name, " + - "orderby " + - - "FROM question_category_master " + - - "WHERE isactive = 1 " + - "AND isdelete = 0 " + - - "ORDER BY orderby"; - - return jdbcTemplate.queryForList(sql); - } - - public List> getSurveyorsList( - - String zone, - String ward, - String fromDate, - String toDate) { - - StringBuilder sql = new StringBuilder(""" - - SELECT - - d.user_name, - d.mobile_no, - sl.loginId, - - sl.zone, - sl.ward, - - COUNT(DISTINCT hs.survey_id) - AS total_survey_done, - - DATE(hs.cdate) - AS survey_date - - FROM homeless_survey_response hs - - INNER JOIN surveyor_location_details sl - ON sl.survey_id = hs.survey_id - - INNER JOIN login_details d - ON d.uid = sl.loginId - - WHERE 1 = 1 - - """); - - List params = new ArrayList<>(); - - if (zone != null && !zone.isEmpty()) { - - sql.append(""" - AND CAST(sl.zone AS UNSIGNED) = ? - """); - - params.add(zone); - } - - if (ward != null && !ward.isEmpty()) { - - sql.append(""" - AND CAST(sl.ward AS UNSIGNED) = ? - """); - - params.add(ward); - } - - if (fromDate != null - && toDate != null - && !fromDate.isEmpty() - && !toDate.isEmpty()) { - - sql.append(""" - AND DATE(hs.cdate) - BETWEEN ? AND ? - """); - - params.add(fromDate); - params.add(toDate); - } - - sql.append(""" - - GROUP BY - - d.user_name, - d.mobile_no, - sl.loginId, - sl.zone, - sl.ward, - DATE(hs.cdate) - - ORDER BY DATE(hs.cdate) DESC - - """); - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray()); - } - - public List> getSurveyorWiseSurveyList( - String loginId, - String zone, - String ward, - String surveyDate) { - - StringBuilder sql = new StringBuilder(""" - - SELECT - - DATE(MAX(hr.cdate)) AS survey_date, - - hr.survey_id, - - MAX(CASE - WHEN hr.qid = 2 - THEN hr.answer - END) AS name, - MAX( - CASE - WHEN hr.qid = 7 - THEN CASE - WHEN hr.others_answer IS NOT NULL - AND TRIM(hr.others_answer) <> '' - THEN hr.others_answer - ELSE gm.english_name - END - END - ) AS gender, - - - - sld.zone AS zone, - - sld.ward AS ward - - FROM homeless_survey_response hr - - LEFT JOIN gender_master gm - ON hr.qid = 7 - AND gm.id = hr.answer - - LEFT JOIN surveyor_location_details sld - ON sld.survey_id = hr.survey_id - - WHERE hr.isactive = 1 - AND hr.isdelete = 0 - AND sld.loginId = ? - - """); - - List params = new ArrayList<>(); - params.add(loginId); - /* - * MAX(CASE - * WHEN hr.qid = 7 - * THEN gm.english_name - * END) AS gender, - */ - - if (zone != null && !zone.isBlank()) { - - sql.append(""" - AND sld.zone = ? - """); - - params.add(zone); - } - - if (ward != null && !ward.isBlank()) { - - sql.append(""" - AND sld.ward = ? - """); - - params.add(ward); - } - - if (surveyDate != null && !surveyDate.isBlank()) { - - sql.append(""" - AND DATE(hr.cdate) = ? - """); - - params.add(surveyDate); - } - - sql.append(""" - - GROUP BY - - hr.survey_id, - sld.zone, - sld.ward - - ORDER BY - - MAX(hr.cdate) DESC - - """); - - return jdbcTemplate.queryForList( - sql.toString(), - params.toArray()); - } - - public List> getBulkExcelData(String zone, - String ward, - String fromDate, - String toDate) { - - String sql = "SELECT " + - " hs.survey_id, " + - " qm.q_english, " + - " hs.answer " + - "FROM homeless_survey_response hs " + - "INNER JOIN homeless_survey_questions_master qm " + - " ON qm.qid = hs.qid " + - "INNER JOIN surveyor_location_details sl " + - " ON sl.survey_id = hs.survey_id " + - "WHERE hs.isactive = 1 " + - "AND hs.isdelete = 0 "; - - List params = new ArrayList<>(); - - if (zone != null && !zone.isEmpty()) { - sql += " AND sl.zone = ? "; - params.add(zone); - } - - if (ward != null && !ward.isEmpty()) { - sql += " AND sl.ward = ? "; - params.add(ward); - } - - if (fromDate != null && !fromDate.isEmpty()) { - sql += " AND DATE(hs.cdate) >= ? "; - params.add(fromDate); - } - - if (toDate != null && !toDate.isEmpty()) { - sql += " AND DATE(hs.cdate) <= ? "; - params.add(toDate); - } - - sql += " ORDER BY hs.survey_id,qm.orderby "; - - List> rows = jdbcTemplate.queryForList(sql, params.toArray()); - - Map> surveyMap = new LinkedHashMap<>(); - - for (Map row : rows) { - - String surveyId = String.valueOf(row.get("survey_id")); - - String question = String.valueOf(row.get("q_english")); - - String answer = row.get("answer") == null ? "" : String.valueOf(row.get("answer")); - - surveyMap.putIfAbsent( - surveyId, - new LinkedHashMap<>()); - - surveyMap.get(surveyId) - .put("Survey ID", surveyId); - - surveyMap.get(surveyId) - .put(question, answer); - } - - return new ArrayList<>(surveyMap.values()); - } - - public List> getGenderList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM gender_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveGender(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE gender_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM gender_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO gender_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateGenderStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE gender_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getRelationTypeList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM relation_type_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveRelationType(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE relation_type_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM relation_type_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO relation_type_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateRelationTypeStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE relation_type_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getCurrentlyLivingList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM current_living_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveCurrentlyLiving(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE current_living_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM current_living_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO current_living_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateCurrentlyLivingStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE current_living_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getMartialList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM martial_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveMartial(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE martial_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM martial_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO martial_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateMartialStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE martial_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDisabilityTypeList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM disability_type_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDisabilityType(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE disability_type_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM disability_type_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO disability_type_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateDisabilityTypeStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE disability_type_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDisabilityCertificateMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM disable_cert_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDisabilityCertificateMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE disable_cert_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM disable_cert_no_reason_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO disable_cert_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateDisabilityCertificateMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE disable_cert_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getHealthConditionList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM health_condition_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveHealthCondition(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE health_condition_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM health_condition_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO health_condition_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateHealthConditionStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE health_condition_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getEducationMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM education_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveEducationMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE education_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM education_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO education_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateEducationMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE education_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDiscontinuedList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM discontinued_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDiscontinuedMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE discontinued_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM discontinued_reason_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO discontinued_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateDiscontinuedMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE discontinued_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getEmploymentTypeList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM employment_type_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveEmploymentType(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE employment_type_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM employment_type_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO employment_type_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateEmploymentTypeStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE employment_type_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getOccupationList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM occupation_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveOccupation(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE occupation_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM occupation_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO occupation_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateOccupationStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE occupation_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getNotEmployedList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM not_employed_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveNotEmployed(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE not_employed_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM not_employed_reason_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO not_employed_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateNotEmployedStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE not_employed_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getReasonHomelessList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM reason_homeless_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveHomelessReason(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE reason_homeless_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM reason_homeless_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO reason_homeless_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateHomelessReasonStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE reason_homeless_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getSleepingSpaceList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM sleepingspace_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveSleepingSpace(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE sleepingspace_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM sleepingspace_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO sleepingspace_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateSleepingSpaceStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE sleepingspace_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getMovingReasonList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM reason_moving_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveMovingReason(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE reason_moving_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM reason_moving_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO reason_moving_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateMovingReasonStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE reason_moing_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getComeOutShelterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM reason_comeoutshelter_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveComeOutShelter(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE reason_comeoutshelter_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM reason_comeoutshelter_master - - """, - Integer.class); - - String insertSql = """ - - INSERT INTO reason_comeoutshelter_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateComeOutShelterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE reason_comeoutshelter_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getGCCShelterMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM gccshelter_notstayed_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveGCCShelterMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE gccshelter_notstayed_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM gccshelter_notstayed_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO gccshelter_notstayed_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateGCCShelterMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE gccshelter_notstayed_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getBirthCertificateNoReasonMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM birth_cert_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveBirthCertificateNoReasonMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE birth_cert_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM birth_cert_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO birth_cert_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateBirthCertificateNoReasonMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE birth_cert_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getCommunityMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM commu_cert_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveCommunityMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE commu_cert_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM commu_cert_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO commu_cert_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateCommunityMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE commu_cert_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getVoterIdMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM voter_id_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveVoterIdMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE voter_id_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM voter_id_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO voter_id_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateVoterIdMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE voter_id_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getAadharCertificateNoReasonMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM adhar_card_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveAadharCertificateNoReasonMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE adhar_card_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM adhar_card_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO adhar_card_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateAadharCertificateNoReasonMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE adhar_card_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getSmartCardNoReasonMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM smart_card_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveSmartCardNoReasonMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE smart_card_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM smart_card_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO smart_card_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateSmartCardNoReasonMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE smart_card_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getDriverLicenseNoReasonMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM dri_license_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveDriverLicenseNoReasonMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE dri_license_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM dri_license_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO dri_license_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateDriverLicenseNoReasonMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE dri_license_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getCmInsuranceNoReasonMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM cm_insurance_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveCmInsuranceNoReasonMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE cm_insurance_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM cm_insurance_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO cm_insurance_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateCmInsuranceNoReasonMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE cm_insurance_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getBankPassbookNoReasonMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM bank_passbook_no_reason_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveBankPassbookNoReasonMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE bank_passbook_no_reason_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM bank_passbook_no_reason_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO bank_passbook_no_reason_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateBankPassbookNoReasonMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE bank_passbook_no_reason_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getReligionMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM religion_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveReligionMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE religion_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM religion_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO religion_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateReligionMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE religion_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getCasteMasterList() { - - String sql = """ - - SELECT - id, - english_name, - isactive, - isdelete - FROM caste_master - WHERE isactive = 1 - AND isdelete = 0 - ORDER BY orderby - - """; - - return jdbcTemplate.queryForList(sql); - } - - public void saveCasteMaster(Map req) { - - Integer id = req.get("id") != null - ? Integer.parseInt(req.get("id").toString()) - : 0; - - // UPDATE - if (id > 0) { - - String updateSql = """ - - UPDATE caste_master - SET english_name = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - updateSql, - req.get("english_name"), - id); - } - - // INSERT - else { - - Integer nextOrder = jdbcTemplate.queryForObject( - """ - - SELECT IFNULL(MAX(orderby),0) + 1 - FROM caste_master - """, - Integer.class); - - String insertSql = """ - - INSERT INTO caste_master - ( - english_name, - orderby, - - isactive, - isdelete - ) - VALUES - ( - ?, - ?, - - 1, - 0 - ) - - """; - - jdbcTemplate.update( - insertSql, - req.get("english_name"), - nextOrder); - } - } - - public void updateCasteMasterStatus( - Map req) { - - Integer id = Integer.parseInt( - req.get("id").toString()); - - Integer status = Integer.parseInt( - req.get("status").toString()); - - String sql = """ - - UPDATE caste_master - SET - isactive = ?, - isdelete = ? - WHERE id = ? - - """; - - jdbcTemplate.update( - sql, - status, - status == 1 ? 0 : 1, - id); - } - - public List> getZoneWiseCount() { - - String sql = - - "SELECT " + - - "zm.zone_name AS zone, " + - - "COUNT(DISTINCT sld.survey_id) AS total " + - - "FROM gcc_street_vendor.zone_master zm " + - - "LEFT JOIN surveyor_location_details sld " + - "ON sld.zone = zm.zone_name " + - - "GROUP BY zm.zone_name " + - - "ORDER BY CAST(zm.zone_name AS UNSIGNED)"; - - return jdbcTemplate.queryForList(sql); - } - - public List> getWardWiseCount( - String zone) { - - String sql = - - "SELECT " + - - "wm.ward_name AS ward, " + - - "COUNT(DISTINCT sld.survey_id) AS total " + - - "FROM gcc_street_vendor.ward_master wm " + - - "LEFT JOIN surveyor_location_details sld " + - "ON sld.zone = wm.zone_id " + - "AND sld.ward = wm.ward_name " + - - "WHERE wm.zone_id = ? " + - - "GROUP BY wm.ward_name " + - - "ORDER BY CAST(wm.ward_name AS UNSIGNED)"; - - return jdbcTemplate.queryForList( - sql, - zone); - } - - public Map getDashboard() { - - Map response = new HashMap<>(); - - response.put( - "totalHomeless", - getTotalHomeless()); - - response.put( - "zonesCovered", - getZonesCovered()); - - response.put( - "maleCount", - getMaleCount()); - - response.put( - "femaleCount", - getFemaleCount()); - - response.put( - "othersCount", - getOthersCount()); - - response.put( - "zoneWise", - getZoneWiseCount()); - - response.put( - "casteWise", - getCasteWiseCount()); - response.put( - "employedCount", - getEmployedCount()); - - response.put( - "unEmployedCount", - getUnEmployedCount()); - - response.put( - "shelterStayedYes", - getShelterStayedYesCount()); - - response.put( - "shelterStayedNo", - getShelterStayedNoCount()); - response.put( - "youngAdults", - getYoungAdultsCount()); - - response.put( - "middleAgedAdults", - getMiddleAgedCount()); - - response.put( - "olderAdults", - getOlderAdultsCount()); - - return response; - } - - private int getShelterStayedNoCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 44 " + - - "AND answer = '17' " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getShelterStayedYesCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 44 " + - - "AND answer = '16' " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getUnEmployedCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 27 " + - - "AND answer = '13' " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getEmployedCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 27 " + - - "AND answer = '12' " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getOlderAdultsCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 78 " + - - "AND CAST(answer AS UNSIGNED) >= 55 " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getYoungAdultsCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 78 " + - - "AND CAST(answer AS UNSIGNED) BETWEEN 18 AND 34 " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - public Integer getDocumentCount(String surveyId) { - - String sql = """ - - SELECT COUNT(*) - - FROM homeless_survey_response - - WHERE survey_id = ? - - AND qid IN (50,53,56,59,62,65,68,71) - - AND answer IS NOT NULL - - AND TRIM(answer) <> '' - - AND isactive = 1 - - AND isdelete = 0 - - """; - - return jdbcTemplate.queryForObject( - sql, - Integer.class, - surveyId); - } - - private int getMiddleAgedCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 78 " + - - "AND CAST(answer AS UNSIGNED) BETWEEN 35 AND 54 " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getMiddleAgedCount1() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - - "FROM homeless_survey_response " + - - "WHERE qid = 78 " + - - "AND CAST(answer AS UNSIGNED) BETWEEN 35 AND 54 " + - - "AND isactive = 1 " + - - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getTotalHomeless() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - "FROM homeless_survey_response " + - "WHERE isactive = 1 " + - "AND isdelete = 0"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getZonesCovered() { - - String sql = - - "SELECT COUNT(DISTINCT zone) " + - "FROM surveyor_location_details"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - public List> getCasteWiseCount() { - - String sql = - - "SELECT " + - - "cm.id, " + - - "cm.english_name AS caste, " + - - "COALESCE(COUNT(DISTINCT hr.survey_id), 0) AS total " + - - "FROM caste_master cm " + - - "LEFT JOIN homeless_survey_response hr " + - - "ON hr.qid = 13 " + - - "AND CAST(hr.answer AS UNSIGNED) = cm.id " + - - "AND hr.isactive = 1 " + - - "AND hr.isdelete = 0 " + - - "WHERE cm.isactive = 1 " + - - "AND cm.isdelete = 0 " + - - "GROUP BY cm.id, cm.english_name " + - - "ORDER BY cm.orderby"; - - return jdbcTemplate.queryForList(sql); - } - - private int getMaleCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - "FROM homeless_survey_response " + - "WHERE qid = 7 " + - "AND answer = '1'"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getFemaleCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - "FROM homeless_survey_response " + - "WHERE qid = 7 " + - "AND answer = '2'"; - - return jdbcTemplate.queryForObject( - sql, - Integer.class); - } - - private int getOthersCount() { - - String sql = - - "SELECT COUNT(DISTINCT survey_id) " + - "FROM homeless_survey_response " + - "WHERE qid = 7 " + - "AND answer = '3'"; - - Integer count = jdbcTemplate.queryForObject( - sql, - Integer.class); - - return count == null ? 0 : count; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/interceptor/AppInterceptor.java b/src/main/java/in/gov/chennaicorporation/gccoffice/interceptor/AppInterceptor.java deleted file mode 100644 index 89cc9faa..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/interceptor/AppInterceptor.java +++ /dev/null @@ -1,315 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.interceptor; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.security.web.util.matcher.RequestMatcher; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - -import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.AppModuleRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.MenuItemRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemAccessRepository; -import in.gov.chennaicorporation.gccoffice.repository.SubMenuItemRepository; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class AppInterceptor implements HandlerInterceptor { - - List getAppModuleAccessEntities; - List getMenuItemAccessEntities; - List getSubMenuItemAccessEntities; - - private AppModuleAccessRepository appModuleAccessRepository; - private MenuItemAccessRepository menuItemAccessRepository; - private SubMenuItemAccessRepository subMenuItemAccessRepository; - - List getAppModuleEntities; - List getMenuItemEntities; - List getSubMenuItemEntities; - - private AppModuleRepository appModuleRepository; - private MenuItemRepository menuItemRepository; - private SubMenuItemRepository subMenuItemRepository; - - private final Environment environment; - - - @Autowired - public AppInterceptor(AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository, - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - Environment environment) { - - this.appModuleAccessRepository = appModuleAccessRepository; - this.menuItemAccessRepository = menuItemAccessRepository; - this.subMenuItemAccessRepository = subMenuItemAccessRepository; - - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - - this.environment = environment; - } - - private boolean isLoginPage(HttpServletRequest request) { - RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/gcc/login"); - return loginPageMatcher.matches(request); - } - - private boolean isErrorPage(HttpServletRequest request) { - RequestMatcher errorPageMatcher = new AntPathRequestMatcher("/gcc/error"); - return errorPageMatcher.matches(request); - } - - private boolean isfavicon(HttpServletRequest request) { - RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/favicon.ico"); - return loginPageMatcher.matches(request); - } - - public static String[] Split(String request,String patten) { - String path = request; - // Split the string by "/" - String[] parts = path.split(patten); - /* - // Display the parts - for (String part : parts) { - System.out.println(part); - } - */ - return parts; - } - - private boolean hasModuleAccess(String moduleName) { - getAppModuleEntities = appModuleRepository.findByModulePath(moduleName); - //System.out.println("DataTable Size for the url ("+moduleName+"): "+getAppModuleEntities.size()); - - String moduleid = null; - - if(getAppModuleEntities.size()>0) { - for ( AppModuleEntity appModuleEntity : getAppModuleEntities) { - moduleid = appModuleEntity.getId().toString(); - } - if(moduleid != null) { - String userGroupId = LoginUserInfo.getUserGroupId(); - System.out.println("hasModuleAccess : Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid); - getAppModuleAccessEntities = appModuleAccessRepository.findByAll(userGroupId,moduleid); - //System.out.println("After Check in(hasModuleAccess):"+getAppModuleAccessEntities.size()); - if(getAppModuleAccessEntities.size()>0) { - return true; - } - else { - System.out.println("hasModuleAccess : getAppModuleAccessEntities.size = " + getAppModuleAccessEntities.size()); - } - - } - } - return false; - } - - private boolean hasMenuAccess(String url,String moduleName,String menuName) { - - if(!hasModuleAccess(moduleName)) {return false; } - - getMenuItemEntities = menuItemRepository.findByUrl(url); - //System.out.println("DataTable Size for the url ("+url+"): "+getMenuItemEntities.size()); - - String moduleid = null; - String menuid = null; - - if(getMenuItemEntities.size()>0) { - for (MenuItemEntity MenuEntity : getMenuItemEntities) { - moduleid = MenuEntity.getModuleId().getId().toString(); - menuid = MenuEntity.getId().toString(); - } - if(moduleid != null && menuid != null) { - String userGroupId = LoginUserInfo.getUserGroupId(); - System.out.println("hasMenuAccess : Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid); - getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId,moduleid,menuid); - if(getMenuItemAccessEntities.size()>0) { - return true; - } - } - } - return false; - } - - private boolean hasSubMenuAccess(String url,String moduleName,String menuName,String subMenuName) { - - if(!hasModuleAccess(moduleName)) {return false; } - - getSubMenuItemEntities = subMenuItemRepository.findByUrl(url); - //System.out.println("DataTable Size for the url ("+url+"): "+getSubMenuItemEntities.size()); - - String moduleid = null; - String menuid = null; - String submenuid = null; - - if(getSubMenuItemEntities.size()>0) { - for (SubMenuItemEntity subMenuEntity : getSubMenuItemEntities) { - moduleid = subMenuEntity.getModuleId().getId().toString(); - menuid = subMenuEntity.getMenuItemId().getId().toString(); - submenuid = subMenuEntity.getId().toString(); - } - if(moduleid != null && menuid != null && submenuid != null) { - String userGroupId = LoginUserInfo.getUserGroupId(); - System.out.println("hasSubMenuAccess 1: Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid+"\n submenuid : "+submenuid); - getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(userGroupId,moduleid,menuid,submenuid); - if(getSubMenuItemAccessEntities.size()>0) { - // Check Parent Menu Access (Menu Access) - if(moduleid != null && menuid != null) { - System.out.println("hasSubMenuAccess 2: Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid); - getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId,moduleid,menuid); - if(getMenuItemAccessEntities.size()>0) { - return true; - } - } - } - } - } - return false; - } - - private boolean hasAccess(String path) { - - String userRole = LoginUserInfo.getUserRole(); - - if (userRole != null && userRole.equals("ADMIN")) { - return true; - } - - /* - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - return true; - } - */ - String url = removeLeadingSlash(path); - - url = removeStartingString(url); // Remove parent App url "gcc" - - //System.out.println("Give URL : "+path+" After remove leading slash : "+url); - - // If default home page - if(path.equals("/")) { - return true; - } - - //continue for access check - String[] parts = Split(url, "/"); - - if(parts.length<=0) {return true;} - - //System.out.println("Part Length:"+ parts.length); - - if(parts.length>1) { - int j=0; - for (String part : parts) { - System.out.println(j+") URL SPLIT: "+part); - j++; - } - String moduleName = ""; - String menuName = ""; - String subMenuName = ""; - - if(parts.length==1) { // Check Only Module Access - moduleName = parts[0]; - return hasModuleAccess(moduleName); - } - else if(parts.length==2) { // Check Module & Menu Access - moduleName = parts[0]; - menuName = parts[1]; - subMenuName = ""; - return hasMenuAccess(url,moduleName,menuName); - } - else if(parts.length==3) { // Check Module , Menu & Sub-Menu Access - moduleName = parts[0]; - menuName = parts[1]; - subMenuName = parts[2]; - return hasSubMenuAccess(url,moduleName,menuName,subMenuName); - } - } - - return true; - } - - public static String removeLeadingSlash(String input) { - if (input.startsWith("/")) { - return input.substring(1); - } - return input; - } - - public static String removeStartingString(String input) { - if (input.startsWith("gcc")) { - return removeLeadingSlash(input.substring(3)); - } - return input; - } - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - String assetsBaseUrl = environment.getProperty("assets.base-url"); - request.setAttribute("assetsBaseUrl", assetsBaseUrl); - - if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.isAuthenticated()) { - String fullRequestURI = request.getRequestURI(); - String contextPath = request.getContextPath(); - String path = fullRequestURI.substring(contextPath.length()); - if(!hasAccess(path)) { - //Object principal = authentication.getPrincipal(); - //UserDetails userDetails = (UserDetails) principal; - - //System.out.println("1) Access Deny For --- " + userDetails.getAuthorities().toString()); - // Redirect to the error page - //response.sendRedirect(request.getContextPath() + "/error"); - request.getRequestDispatcher("/error").forward(request, response); - } - } - } - - // Continue with the request processing - return true; - } - - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) throws Exception { - // Check if the current request matches the login or error page URLs - if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) { - if (modelAndView != null) { - String assetsBaseUrl = environment.getProperty("assets.base-url"); - request.setAttribute("assetsBaseUrl", assetsBaseUrl); - modelAndView.addObject("assetsBaseUrl", assetsBaseUrl); - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.isAuthenticated()) { - Object principal = authentication.getPrincipal(); - if (principal instanceof UserDetails) { - UserDetails userDetails = (UserDetails) principal; - modelAndView.addObject("currentUserDetails", userDetails); - System.out.println(userDetails); - } - } - } - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/APIController.java deleted file mode 100644 index e5607f5d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/APIController.java +++ /dev/null @@ -1,189 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.controller; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -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.gccoffice.m_petition.service.Petition; -import in.gov.chennaicorporation.gccoffice.m_petition.service.PetitionMaster; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/m_petition") -@RestController("mpRest") // Mayor Petition Rest -public class APIController { - private PetitionMaster petitionMaster; - private Petition petition; - - @Autowired - public APIController(PetitionMaster petitionMaster,Petition petition) { - this.petitionMaster = petitionMaster; - this.petition = petition; - } - - @GetMapping(value="/getComplaintTypes") - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @GetMapping(value="/getOfficerList") - public List getOfficerList() { - return petitionMaster.getOfficerList(); - } - - @GetMapping(value="/getPetitionTypes") - public List getPetitionTypes() { - return petitionMaster.getPetitionTypes(); - } - - @GetMapping(value="/getPetitionList") - public List getPetitionList(@RequestParam("searchmonth") String month, - @RequestParam("searchyear") String year) { - return petition.getPetitionList(month,year); - } - - @GetMapping(value="/getUnmapPetitionList") - public List getUnmapPetitionList() { - return petition.getUnmapPetitionList(); - } - - @GetMapping(value="/getPetitionDetails") - public List getPetitionDetails(@RequestParam("petitionNo") String petitionNo) { - return petition.getPetitionDetails(petitionNo); - } - - @PostMapping(value="/savePetition") - public String savePetition( - @RequestParam("createdBy") String createdBy, - @RequestParam("petitionType") String petitionType, - @RequestParam("petitionerName") String petitionerName, - @RequestParam("petitionerMobile") String petitionerMobile, - @RequestParam("complaintType") String petitionerComplaint, - @RequestParam("san_page1") MultipartFile page1, - @RequestParam("san_page2") MultipartFile page2, - @RequestParam("san_page3") MultipartFile page3, - @RequestParam("san_page4") MultipartFile page4) { - - return petition.savePetition(petitionType, createdBy, petitionerName, petitionerMobile, petitionerComplaint, page1, page2, page3, page4); - } - - @PostMapping(value="/updatePetition") - public Boolean updatePetition( - @RequestParam("petitionType") String petitionType, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam("petitionerName") String petitionerName, - @RequestParam("petitionerMobile") String petitionerMobile, - @RequestParam("petitionerAddress") String petitionerAddress, - @RequestParam("petitionerPincode") String petitionerPincode, - @RequestParam("complaintType") String petitionerComplaint, - @RequestParam("complaintNature") String complaintNature) { - - return petition.updatePetition(petitionNo, petitionType, createdBy, petitionerName, petitionerMobile, petitionerAddress, petitionerPincode, petitionerComplaint, complaintNature); - } - - @PostMapping(value="/mapComplientToOfficer") - public Boolean updatePetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String mapOfficers) { - - String com_mapping = mapOfficers; - - // First before Mapping need to unmaps old list - petition.unmapComplient(petitionId, petitionNo); - - if(com_mapping!=null) { - String[] com_mapping_parts = com_mapping.split(","); - for (String values : com_mapping_parts) { - String[] com_mapping_val = values.split("_"); - if (com_mapping_val.length > 0) { - String complientId = com_mapping_val[0]; - String offcierId = com_mapping_val[1]; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - } - } - } - return true; - } - - - @GetMapping(value="/getComplaintMappingDetails") - public List getComplaintMappingDetails( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("complaintTypeId") String complaintTypeId) { - return petition.getComplaintMappingDetails(petitionNo,petitionId,complaintTypeId); - } - - @GetMapping(value="/getComplaintList") - public List getComplaintList(@RequestParam("loginId") String loginId, - @RequestParam("searchmonth") String month, - @RequestParam("searchyear") String year - ) { - - return petition.getComplaintList(loginId,month,year); - } - - @GetMapping(value="/getComplaintListByPetitionId") - public List getComplaintListByPetitionId(@RequestParam("petitionId") String petitionId) { - return petition.getComplaintListByPetitionId(petitionId); - } - - @GetMapping(value="/getComplaintDetails") - public List getComplaintDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintDetails(mapId); - } - - @GetMapping(value="/getComplaintActionDetails") - public List getComplaintActionDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintActionDetails(mapId); - } - - @PostMapping(value="/saveComplanitStatus") - public String saveComplanitStatus( - @RequestParam("createdBy") String createdBy, - @RequestParam("mapId") String mapId, - @RequestParam("complaintStatus") String complaintStatus, - @RequestParam("complaintActionText") String complaintActionText, - @RequestParam("action_san_page1") MultipartFile actionPage1, - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo) { - - return petition.saveComplanitStatus(createdBy, mapId, complaintStatus, complaintActionText, actionPage1, petitionId, petitionNo); - } - - @GetMapping("/getReportList") - public List> getReportList( - @RequestParam(value = "fromDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate, - - @RequestParam(value = "toDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate, - - @RequestParam(value = "petitionType", required = false) String petitionType) { - - return petition.getReportList(fromDate, toDate, petitionType); - } - - /* - // Import Old Data - @PostMapping("/upload") - public String uploadExcelFile() { - try { - return petition.saveOldData(); - } catch (Exception e) { - return "Error: " + e.getMessage(); - } - } - */ -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/MainController.java deleted file mode 100644 index 4e92eab4..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/MainController.java +++ /dev/null @@ -1,137 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.controller; - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/m_petition") -@Controller("MayorPetitionController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/m_petition/"; - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"index"; - } - - @GetMapping({"/new_petition"}) - public String newPetition(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_petition"; - } - - @GetMapping("/petition-ack/{petitionNo}") - public String petitionAck(Model model,@PathVariable("petitionNo") String petitionNo) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_ack"; - } - - @GetMapping("/petition-list") - public String petitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_list"; - } - - @GetMapping("/unmapped-petition-list") - public String unMappedPetitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_not_mapped_list"; - } - - @GetMapping("/update-petition") - public String petitionUpadte(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/view-petition") - public String petitionView(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view"; - } - - @GetMapping("/view-petition-modal") - public String petitionViewModal(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view_modal_page"; - } - - @GetMapping("/search-petition") - public String petitionSearch(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - //model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/complaint-list") - public String complaintList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"complaint_list"; - } - - @GetMapping("/report/list") - public String reportList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"pending_list"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/package-info.java deleted file mode 100644 index 26006d9e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/data/ComplaintType.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/data/ComplaintType.java deleted file mode 100644 index d05aa6c0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/data/ComplaintType.java +++ /dev/null @@ -1,21 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.data; - -import java.util.Map; - -public class ComplaintType { - private int complaintTypeId; - private String complaintType; - - public ComplaintType(Map map) { - this.complaintTypeId = (int) map.get("complaint_typeid"); - this.complaintType = (String) map.get("complaint_type"); - } - - public int getComplaintTypeId() { - return complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/data/package-info.java deleted file mode 100644 index bd0b33ca..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/entity/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/entity/package-info.java deleted file mode 100644 index 8a257add..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/entity/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.entity; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/package-info.java deleted file mode 100644 index ccdd4b16..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ -/** - * - */ -package in.gov.chennaicorporation.gccoffice.m_petition; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/repository/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/repository/package-info.java deleted file mode 100644 index 52f87dc6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/repository/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.repository; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/Petition.java deleted file mode 100644 index 8efc9a75..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/Petition.java +++ /dev/null @@ -1,1142 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.service; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.transaction.annotation.Transactional; -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.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - -import ch.qos.logback.core.recovery.ResilientSyslogOutputStream; -import in.gov.chennaicorporation.gccoffice.m_petition.data.ComplaintType; -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.GetMappingUserDetails; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -//import org.apache.poi.ss.usermodel.*; -//import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -//import org.jsoup.Jsoup; - -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; - -@Service -public class Petition { - - private final GetMappingUserDetails getMappingUserDetails; - private final JdbcTemplate jdbcTemplate; - private final JdbcTemplate jdbcOracleTemplate; - private final Environment environment; - private final PetitionMaster petitionMaster; - - - // Constructor injection - @Autowired - public Petition(GetMappingUserDetails getMappingUserDetails, - @Qualifier("mysqlMayorPetitionDataSource") DataSource dataSource, - @Qualifier("oracleDataSource") DataSource oracleDataSource, - Environment environment, - PetitionMaster petitionMaster) { - this.getMappingUserDetails = getMappingUserDetails; - this.jdbcTemplate = new JdbcTemplate(dataSource); // Set jdbcTemplate using injected dataSource - this.jdbcOracleTemplate = new JdbcTemplate(oracleDataSource); // Set jdbcOracleTemplate using injected oracleDataSource - this.environment = environment; - this.petitionMaster = petitionMaster; - } - - @Transactional(readOnly = true) - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - /* - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - return complaintTypeMaps.stream() - .map(ComplaintType::new) - .collect(Collectors.toList()); - } - */ - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - List complaintTypes = new ArrayList(); - - if (complaintTypeMaps != null) { - for (Map map : complaintTypeMaps) { - ComplaintType ct = new ComplaintType(map); - complaintTypes.add(ct); - } - } - - return complaintTypes; - } - @Transactional(readOnly = true) - // Method to map complaint type IDs to their respective complaint types - public static String mapComplaintTypes(List complaintTypes, String complaint) { - String[] complaintIds = complaint.split(","); - StringBuilder complaintTxtBuilder = new StringBuilder(); - - for (String complaintId : complaintIds) { - int id = Integer.parseInt(complaintId); - for (ComplaintType type : complaintTypes) { - if (type.getComplaintTypeId() == id) { - if (complaintTxtBuilder.length() > 0) { - complaintTxtBuilder.append(","); - } - complaintTxtBuilder.append(type.getComplaintType()); - break; - } - } - } - - return complaintTxtBuilder.toString(); - } - - @Transactional(readOnly = true) - public List> getPetitionList(String month, String year) { - try { - // Construct the date pattern using the provided month and year - String datePattern = year + "-" + month + "-%"; // Example: "2025-02-%" - - // Corrected SQL query using the proper date format - String sqlQuery = "SELECT p.*, pt.name as petition_type_name FROM petition p " - + "LEFT JOIN petition_master.petition_types pt ON pt.petition_type_id = p.petition_type " - + "WHERE (p.`isactive`=1 AND p.`isdelete`=0) AND DATE(p.cdate) LIKE ?"; - - - // Execute the query with the date pattern as parameter - List> result = jdbcTemplate.queryForList(sqlQuery, datePattern); - - // Encode the SQL query for logging or tracking - Base64Util.encodeBase64(sqlQuery); - - // Iterate over the list of results and encode the 'petitionNo' - for (Map map : result) { - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getUnmapPetitionList() { - try { - String sqlQuery = "SELECT " - + " p.* " - + "FROM " - + " `petition` p " - + "WHERE " - + " p.`isactive` = 1 AND p.`isdelete` = 0 " - + " AND NOT EXISTS (" - + " SELECT 1 " - + " FROM `petition_mapping` pm " - + " WHERE (p.`petition_id` = pm.`petition_id`) AND (pm.`isactive` = 1 AND pm.`isdelete` = 0 ) " - + " )"; - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getPetitionDetails(String petitionNo) { - try { - String sqlQuery = "SELECT * FROM petition WHERE petition_no = ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String savePetition( - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerComplaint, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition` " - + "(`petition_type`,`created_by`, `petitioner_name`, `petitioner_mobile`, " - + "`petitioner_complaint`, `petitioner_complaint_txt`) " - + "VALUES (?, ?, ?, ?, ?, ?)"; - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, petitionType); - ps.setString(2, createdBy); - ps.setString(3, petitionerName); - ps.setString(4, petitionerMobile); - ps.setString(5, petitionerComplaint); - ps.setString(6, petitionerComplaint_txt); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - - // Get the value of mp_ackno from application.properties - String ackno = environment.getProperty("mp_ackno"); - String ackno_prefix = environment.getProperty("mp_ackno_prefix"); - - // Convert ackno to int if needed - int acknoInt = Integer.parseInt(ackno); - - // Calculate the petition number - int petitionNo = (int) (lastInsertId + acknoInt); - - // Construct the petition number string - String petitionNoString = ackno_prefix + petitionNo; - - // Update the petition number in the database - updatePetitionNumber(lastInsertId, petitionNoString); - - // Add Petition Scan File in the database - addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return petitionNoString; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionNumber(int petitionId,String petitionNoString) { - String sqlQuery = "UPDATE `petition` SET `petition_no`='"+petitionNoString+"' WHERE `petition_id`='"+petitionId+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String addPetitionFile(String createdBy, - int petitionId, - String petitionNoString, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - String fileName=""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - case 2: - file = page2; - fileName = "Scan2"; - break; - case 3: - file = page3; - fileName = "Scan3"; - break; - case 4: - file = page4; - fileName = "Scan4"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("mp_foldername"); - - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - - uploadDirectory = uploadDirectory + serviceFolderName;// + year + "/" + month; - - //uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = petitionId + "_" + fileName + "_" + petitionNoString + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"','"+petitionNoString+"','"+petitionId+"')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - @Transactional - public boolean updatePetition( - String petitionNo, - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerAddress, - String petitionerPincode, - String petitionerComplaint, - String complaintNature) { - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type`='"+petitionType+"', `created_by`='"+createdBy+"', `petitioner_name`='"+petitionerName+"', `petitioner_mobile`='"+petitionerMobile+"', " - + "`petitioner_address`='"+petitionerAddress+"', `petitioner_pincode`='"+petitionerPincode+"'," - + "`petitioner_complaint`='"+petitionerComplaint+"', `petitioner_complaint_txt`='"+petitionerComplaint_txt+"', `complaint_nature`='"+complaintNature+"' " - + "WHERE (`petition_no`='"+petitionNo+"') LIMIT 1"; - System.out.println(sqlQuery); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(sqlQuery); - - // Add Petition Scan File in the database - //addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return true; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return false; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionStatus(String petitionId,String petitionNo) { - String status_value = "close"; - List> petitionMappingDetails = getPetitionMappingDetails(petitionNo, petitionId); - - for (Map mapping : petitionMappingDetails) { - // Access values from the map using keys - Object status = mapping.get("status"); - // Check if status is "close" - if (!"close".equals(status)) { - status_value = "partial"; - } - - } - - String sqlQuery = "UPDATE `petition` SET `status`='"+status_value+"' WHERE `petition_no`='"+petitionNo+"' AND `petition_id`='"+petitionId+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails(String petitionNo, String petitionId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public boolean unmapComplient(String petitionId, String petitionNo) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `petition_id`='"+petitionId+"' AND `petition_no`='"+petitionNo+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public boolean mapComplientToOfficer( - String createdBy, String petitionId, String petitionNo, String complaintId, String officerId) { - String sqlQuery = "INSERT INTO `petition_mapping`" - + "(`created_by`, `off_id`, `petition_no`, `complaint_typeid`, `petition_id`) " - + "VALUES (?, ?, ?, ?, ?)"; - jdbcTemplate.update(sqlQuery, createdBy, officerId, petitionNo, complaintId, petitionId); - return true; - } - - @Transactional - public boolean updateMapComplientStatus(String mapId,String status) { - String sqlQuery = "UPDATE `petition_mapping` SET `status`=? WHERE `mapid`=? LIMIT 1"; - jdbcTemplate.update(sqlQuery, status, mapId); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getComplaintMappingDetails(String petitionNo, String petitionId, String complaintTypeId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND `complaint_typeid`= ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo,complaintTypeId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintList(String loginId, String month, String year) { - // Construct the date pattern using the provided month and year - String datePattern = year + "-" + month + "-%"; // Example: "2025-02-%" - - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `petition` p, `petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`) " - + " AND DATE(p.cdate) LIKE ?" - + " "; - - - //if (officerMaster != null && !officerMaster.isEmpty() && loginId!='256') { - if (!loginId.equals("491") && !loginId.equals("1") ) { - - String officerMaster = getMappingUserDetails.getOfficerMaster(loginId); - sqlQuery = sqlQuery + " AND (pm.off_id IN("+officerMaster+"))"; - } - - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery,datePattern); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintListByPetitionId(String petitionId) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, p.`status` petition_status, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status` complaint_status, pm.`cdate` mappedOn, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `mayor_petition`.`petition` p,`mayor_petition`.`petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`petition_id` = '"+petitionId+"' AND p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintDetails(String mapid) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm`, ctype.`complaint_type`, " - + " COALESCE(pf.`mtm_pet_file_id`, 'No file available') AS mtm_pet_file_id, " - + " COALESCE(pf.`cdate`, '') AS file_cdate, " - + " COALESCE(pf.`created_by`, 'N/A') AS file_created_by, " - + " COALESCE(pf.`file_name`, 'No file available') AS file_name, " - + " COALESCE(pf.`file_size`, 0) AS file_size, " - + " COALESCE(pf.`file_type`, 'Unknown') AS file_type, " - + " COALESCE(pf.`isactive`, 0) AS file_isactive, " - + " COALESCE(pf.`isdelete`, 0) AS file_isdelete " - + " FROM " - + " `petition` p " - + " JOIN `petition_mapping` pm ON p.`petition_id` = pm.`petition_id` " - + " JOIN `petition_master`.`officer_master` om ON om.`off_id` = pm.`off_id` " - + " JOIN `petition_master`.`complaint_types` ctype ON ctype.`complaint_typeid` = pm.`complaint_typeid` " - + " LEFT JOIN `pentition_files` pf ON p.`petition_id` = pf.`petition_id` " - + " WHERE " - + " pm.`mapid` = '" + mapid + "' " - + " AND p.`isactive` = 1 AND p.`isdelete` = 0 " - + " AND pm.`isactive` = 1 AND pm.`isdelete` = 0 " - + " AND om.`isactive` = 1 AND om.`isdelete` = 0 "; - - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintActionDetails(String mapId) { - try { - String sqlQuery = "SELECT * FROM `petition_action_taken` WHERE (`mapid`= ? AND `isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, mapId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String saveComplanitStatus( - String createdBy, - String mapId, - String complaintStatus, - String complaintActionText, - MultipartFile actionPage1, - String petitionId, - String petitionNo) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition_action_taken` " - + "(`created_by`, `off_id`, `mapid`, `status`, " - + "`comments`) " - + "VALUES (?, ?, ?, ?, ?)"; - - try { - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, createdBy); - ps.setString(3, mapId); - ps.setString(4, complaintStatus); - ps.setString(5, complaintActionText); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int)keyHolder.getKey().longValue(); - String actionID = "error"; - if(lastInsertId>0) { - // Update Complaint Status - updateMapComplientStatus(mapId,"close"); - // Update Petition Status - updatePetitionStatus(petitionId,petitionNo); - // Add Action Scan File in the database - addActionFile(mapId,lastInsertId, actionPage1); - actionID = ""+lastInsertId; - } - - return actionID; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public String addActionFile( String mapId, int solmapid, - MultipartFile page1) { - - MultipartFile file = page1; - String fileName = "Scan1_"+solmapid; - - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("mp_foldername"); - String serviceActionFolderName = environment.getProperty("mp_action_Foldername"); - - //uploadDirectory = uploadDirectory + serviceFolderName +"/"+ serviceActionFolderName; - - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - - uploadDirectory = uploadDirectory + serviceFolderName + "/" + serviceActionFolderName;// + year + "/" + month; - - // File name - fileName = mapId + "_" + fileName + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "UPDATE `petition_action_taken` SET " - + "`file_name`='"+fileName+"', " - + "`file_size`='"+fileSize+"', " - + "`file_type`='"+fileType+"' " - + "WHERE `solmapid`='"+solmapid+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - return "success"; - } - - - //Report List - @Transactional(readOnly = true) - public List> getReportList(Date fromDate, Date toDate, String petitionType) { - try { - StringBuilder sql = new StringBuilder( - "SELECT p.petition_no, p.petitioner_name, pt.name AS petition_type, \r\n" + - "p.petitioner_mobile, p.complaint_nature, zh.off_nm AS officer_name, \r\n" + - "zh.off_id AS officer_id, pm.status \r\n" + - "FROM mayor_petition.petition_mapping pm \r\n" + - "LEFT JOIN mayor_petition.petition p \r\n" + - "ON p.petition_id = pm.petition_id \r\n" + - "LEFT JOIN petition_master.officer_master_zh zh \r\n" + - "ON zh.off_id = pm.off_id \r\n" + - "LEFT JOIN petition_master.petition_types pt \r\n" + - "ON pt.petition_type_id = p.petition_type \r\n" - ); - - List params = new ArrayList<>(); - List conditions = new ArrayList<>(); - - if (fromDate != null && toDate != null) { - // Ensure toDate includes full day - Calendar cal = Calendar.getInstance(); - cal.setTime(toDate); - cal.set(Calendar.HOUR_OF_DAY, 23); - cal.set(Calendar.MINUTE, 59); - cal.set(Calendar.SECOND, 59); - cal.set(Calendar.MILLISECOND, 999); - Date toDateEnd = cal.getTime(); - - conditions.add("date(pm.cdate) BETWEEN ? AND ?"); - params.add(fromDate); - params.add(toDateEnd); - } - - if (petitionType != null && !petitionType.trim().isEmpty()) { - conditions.add("pt.petition_type_id = ?"); - params.add(petitionType); - } - - if (!conditions.isEmpty()) { - sql.append("WHERE ").append(String.join(" AND ", conditions)); - } - - List> result = jdbcTemplate.queryForList( - sql.toString(), params.toArray() - ); - - for (Map map : result) { - String petitionNo = (String) map.get("petition_no"); - if (petitionNo != null) { - map.put("petitionNoEncode", Base64Util.encodeBase64(petitionNo)); - } - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - // Import Old data - /* - public String HtmlDecoder(String tamilTxt) { - // HTML-encoded string - String encodedString = ""+tamilTxt; - - // Decode the HTML-encoded string using Jsoup - String decodedString = Jsoup.parse(encodedString).text(); - - // Output the decoded Tamil text - System.out.println(decodedString); - - return decodedString; - } - - @Transactional - public String importPetition( - String oldPetionid, - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerComplaint, - String page1, - String page2, - String page3, - String page4, - String cdate, - String officerId, - String address, - String complainttxt, - String pin) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition` " - + "(`petition_type`,`created_by`, `petitioner_name`, `petitioner_mobile`, " - + "`petitioner_complaint`, `petitioner_complaint_txt`,`cdate`,`petitioner_address`,`complaint_nature`,`petitioner_pincode`) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, petitionType); - ps.setString(2, createdBy); - ps.setString(3, petitionerName); - ps.setString(4, petitionerMobile); - ps.setString(5, petitionerComplaint); - ps.setString(6, petitionerComplaint_txt); - ps.setString(7, cdate); - ps.setString(8, address); - ps.setString(9, complainttxt); - ps.setString(10, pin); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - - // Get the value of mp_ackno from application.properties - String ackno = environment.getProperty("mp_ackno"); - String ackno_prefix = environment.getProperty("mp_ackno_prefix"); - - // Convert ackno to int if needed - int acknoInt = Integer.parseInt(ackno); - - // Calculate the petition number - int petitionNo = (int) (lastInsertId + acknoInt); - - // Construct the petition number string - String petitionNoString = ackno_prefix + petitionNo; - - // Update the petition number in the database - updatePetitionNumber(lastInsertId, petitionNoString); - - // Add Petition Scan File in the database - //addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("mp_foldername"); - - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - - uploadDirectory = uploadDirectory + serviceFolderName;// + year + "/" + month; - - String fileName = page1;//uploadDirectory + "/" + page1; - String fileSize = "10000"; - String fileType = "application/pdf"; - - // Save the file path to a database - String sqlFileQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"','"+petitionNoString+"','"+lastInsertId+"')"; - jdbcTemplate.update(sqlFileQuery); - - String lastInsertIdtxt = ""+lastInsertId; - - // map Complient Mapping - if(mapComplientToOfficer( - createdBy, lastInsertIdtxt, petitionNoString, petitionerComplaint, officerId - )) { - System.out.println("Complient Created : "+ lastInsertIdtxt); - - String sqlQueryMap = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND `complaint_typeid`= ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQueryMap, lastInsertId, petitionNoString, petitionerComplaint); - - //System.out.println(sqlQueryMap); - // Check if result is not empty - if (result.size() > 0) { - // Retrieve mapId from the first result - String mapId = String.valueOf(result.get(0).get("mapid")); - - // Save the reply with the retrieved mapId - saveReplay(oldPetionid, mapId, createdBy, lastInsertIdtxt, petitionNoString); - } - } - - return petitionNoString; // If no exception, query executed successfully - - } catch (Exception e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - public String saveReplay(String oldPetionid, String mapId, String createdBy, String petitionId, String petitionNo) { - try { - - String sqlQuery2 = "SELECT mr.PET_ID, mr.FLE_UPD, mr.REPLY_DT, mr.REPLY " - + "FROM FAS.MAYOR_REPLY mr " - + "WHERE mr.PET_ID = ? " - + "AND ROWNUM <= 1"; - List> petData = jdbcOracleTemplate.queryForList(sqlQuery2,oldPetionid); - - int lastInsertId = 0; - for (Map pet : petData) { - - String complaintActionText = HtmlDecoder((String) pet.get("REPLY")); - String status = "close"; - String fileName = (String) pet.get("FLE_UPD"); - //String cdate = (String) pet.get("REPLY_DT"); - String cdate =""; - Object replyDateObj = pet.get("REPLY_DT"); - - if (replyDateObj != null) { - if (replyDateObj instanceof Timestamp) { - Timestamp timestamp = (Timestamp) replyDateObj; - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - cdate = dateFormat.format(timestamp); - // Now you can use cdate - } else { - // Handle other types or null case - cdate = replyDateObj.toString(); - } - } else { - // Handle the case where REPLY_DT is null - cdate = ""; - } - - String cdatetxt = cdate; - System.out.println(cdate); - - String sqlQuery = "INSERT INTO `petition_action_taken` " - + "(`created_by`, `off_id`, `mapid`, `status`, " - + "`comments`, `cdate`) " - + "VALUES (?, ?, ?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, createdBy); - ps.setString(3, mapId); - ps.setString(4, status); - ps.setString(5, complaintActionText); - ps.setString(6, cdatetxt); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int)keyHolder.getKey().longValue(); - String actionID = "error"; - if(lastInsertId>0) { - // Update Complaint Status - updateMapComplientStatus(mapId,"close"); - // Update Petition Status - updatePetitionStatus(petitionId,petitionNo); - // Add Action Scan File in the database - //addActionFile(mapId,lastInsertId, actionPage1); - - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("mp_foldername"); - String serviceActionFolderName = environment.getProperty("mp_action_Foldername"); - - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - - uploadDirectory = uploadDirectory + serviceFolderName + serviceActionFolderName;// + year + "/" + month; - - //fileName = uploadDirectory + "/" + fileName; - String fileSize = "10000"; - String fileType = "application/pdf"; - - actionID = ""+lastInsertId; - - // Save the file path to a database - String sqlQueryFile = "UPDATE `petition_action_taken` SET " - + "`file_name`='"+fileName+"', " - + "`file_size`='"+fileSize+"', " - + "`file_type`='"+fileType+"' " - + "WHERE `solmapid`='"+actionID+"' LIMIT 1"; - jdbcTemplate.update(sqlQueryFile); - - - } - } - return "Success"; - } - catch (DataAccessException e) { - e.printStackTrace(); - return "Fail " + e.getMessage(); - } - } - - public String saveOldData() { - //try (InputStream is = file.getInputStream(); Workbook workbook = new XSSFWorkbook(is)) { - //Sheet sheet = workbook.getSheetAt(0); // Get the first sheet - String oldPetionid = ""; - String petitionType = ""; - String petDate = ""; - String createdBy = ""; - String petitionerName = ""; - String petitionerMobile = ""; - String petitionerComplaint = "50"; - String page1 = null; - String page2 = null; - String page3 = null; - String page4 = null; - String officerId=""; - String complaint_nature=""; - String petitioner_address=""; - String petitioner_pincode=""; - - String SqlQuery = "SELECT PET_ID, " - + "PET_DT, " - + "CASE " - + " WHEN PET_TYPE = 'P' THEN '1' " - + " WHEN PET_TYPE = 'O' THEN '6' " - + " WHEN PET_TYPE = 'N' THEN '5' " - + " ELSE PET_TYPE " // Keep the original PET_TYPE if none of the conditions match - + "END AS PET_TYPE, " - + "PET_NM, " - + "PET_DET, " - + "COMP_TYPE, " - + "FLE, " - + "HQ_DEPT_ID, " - + "OTHR_DEPT, PET_ADD1 ,PET_ADD2 , PET_ADD3, PET_PIN " - + "FROM FAS.MAYOR_PETITION " - + "WHERE PET_DT > TO_DATE('2022-09-01', 'YYYY-MM-DD') " - + "AND PET_ID LIKE 'M%'"; - List> petData = jdbcOracleTemplate.queryForList(SqlQuery); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("mp_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - int countData=0; - // Loop through the database data if necessary - for (Map pet : petData) { - oldPetionid = (String) pet.get("PET_ID"); - countData++; - petitionType = (String) pet.get("PET_TYPE"); - petDate = pet.get("PET_DT").toString(); // Convert date to string - createdBy = "1"; - petitionerName = HtmlDecoder((String) pet.get("PET_NM")); - petitionerMobile = ""; - complaint_nature = HtmlDecoder((String) pet.get("PET_DET")); - petitioner_address = (String) pet.get("PET_ADD1") + " " + pet.get("PET_ADD2") + " "+ pet.get("PET_ADD3"); - petitioner_address = HtmlDecoder(petitioner_address); - petitioner_pincode = (String) pet.get("PET_PIN"); - //petitionerComplaint = ((String) pet.get("COMP_TYPE")); - page1 = (String) pet.get("FLE"); - //officerId = (String) pet.get("OTHR_DEPT"); - // Retrieve the BigDecimal value and convert it to String - BigDecimal officerIdBigDecimal = (BigDecimal) pet.get("OTHR_DEPT"); - if (officerIdBigDecimal != null) { - officerId = officerIdBigDecimal.toString(); // Convert BigDecimal to String - } else { - officerId = ""; // In case the value is null - } - - BigDecimal petitionerComplaintnum = (BigDecimal) pet.get("COMP_TYPE"); - if (petitionerComplaintnum != null) { - petitionerComplaint = petitionerComplaintnum.toString(); // Convert BigDecimal to String - } else { - petitionerComplaint = ""; // In case the value is null - } - System.out.println("OnGoing : "+countData + " == " + oldPetionid); - // Handle each record from the database - importPetition(oldPetionid, petitionType, createdBy, petitionerName, - petitionerMobile, petitionerComplaint, - page1, page2, page3, page4, petDate,officerId,petitioner_address, complaint_nature, petitioner_pincode); - - System.out.println("Completed : "+countData + " == " + oldPetionid); - } - - return "Total Data Completed " + countData; - // } catch (Exception e) { - // throw new RuntimeException("Failed to process Excel file: " + e.getMessage()); - // } - - } - * - */ -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/PetitionMaster.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/PetitionMaster.java deleted file mode 100644 index 86bbf826..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/PetitionMaster.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class PetitionMaster { - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPetitionMasterDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getComplaintType(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `complaint_types` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getOfficerList(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `officer_master` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getPetitionTypes(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `petition_types` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby` ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/package-info.java deleted file mode 100644 index 34d6803c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.m_petition.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/modeldata/Employee.java b/src/main/java/in/gov/chennaicorporation/gccoffice/modeldata/Employee.java deleted file mode 100644 index 3a357900..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/modeldata/Employee.java +++ /dev/null @@ -1,63 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.modeldata; - -import java.util.Date; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Employee { - - @JsonFormat(pattern = "yyyy/MM/dd") - @JsonProperty("start_date") - private Date startDate; - private Integer id; - private String position; - private String name; - private Double salary; - private String office; - private Integer extn; - public Date getStartDate() { - return startDate; - } - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } - public String getPosition() { - return position; - } - public void setPosition(String position) { - this.position = position; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Double getSalary() { - return salary; - } - public void setSalary(Double salary) { - this.salary = salary; - } - public String getOffice() { - return office; - } - public void setOffice(String office) { - this.office = office; - } - public Integer getExtn() { - return extn; - } - public void setExtn(Integer extn) { - this.extn = extn; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/modeldata/ErrorResponse.java b/src/main/java/in/gov/chennaicorporation/gccoffice/modeldata/ErrorResponse.java deleted file mode 100644 index 824e999a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/modeldata/ErrorResponse.java +++ /dev/null @@ -1,55 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.modeldata; - -public class ErrorResponse { - private int status; - private String error; - private String message; - private String exception; - - // Constructors, getters, and setters for the above fields - - public ErrorResponse(int status, String error, String message, String exception) { - this.status = status; - this.error = error; - this.message = message; - this.exception = exception; - } - - public ErrorResponse() { - super(); - // TODO Auto-generated constructor stub - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getError() { - return error; - } - - public void setError(String error) { - this.error = error; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getException() { - return exception; - } - - public void setException(String exception) { - this.exception = exception; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/APIController.java deleted file mode 100644 index 183d34f4..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/APIController.java +++ /dev/null @@ -1,119 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.controller; - -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -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.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("/gcc/api/mtm") -@RestController("mtmapicontroller") -public class APIController { - private final RestTemplate restTemplate; - private final AppConfig appConfig; - String bodyMessage = ""; - - @Autowired - public APIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @GetMapping(value="/setEventId") - public String setEventId(HttpSession session, - @RequestParam("eventid") String eventid){ - if ("0".equals(eventid)) { - session.setAttribute("eventid", null); - }else{ - session.setAttribute("eventid", eventid); - } - - return "success"; - } - - /* - @GetMapping(value = "/dashboard") - public String getFeedbackAssetdetails(@RequestParam String fbId) { - String feedbackId = fbId; - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/feedback/{feedbackId}",String.class,feedbackId); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - */ - - @GetMapping(value = "/getPetitionStatusPublic") - public String getPetitionStatusPublic(@RequestParam String petition_no) { - String baseURL = appConfig.mtm+"/api/getPetitionStatusPublic"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("petition_no", petition_no); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping(value = "/getComMappingDetailsByPetId") - public String getComMappingDetailsByPetId(@RequestParam String petid) { - String baseURL = appConfig.mtm+"/api/getComMappingDetailsByPetId"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("petid", petid); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping(value = "/getComMappingActionByMapId") - public String getComMappingActionByMapId(@RequestParam String mapid) { - String baseURL = appConfig.mtm+"/api/getComMappingActionByMapId"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("mapid", mapid); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping(value = "/petitionFilesBypetitionId") - public String petitionFilesBypetitionId(@RequestParam String pid) { - String baseURL = appConfig.mtm+"/api/petitionFilesBypetitionId"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("pid", pid); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - - @GetMapping(value = "/viewBlobData") - public String viewBlobData(@RequestParam String id,@RequestParam String table) { - String baseURL = appConfig.mtm+"/api/viewBlobData"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("id", id) - .queryParam("table", table); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - - @GetMapping(value = "/getComMappingDetailsByMapId") - public String getComMappingDetailsByMapId(@RequestParam String mapid) { - String baseURL = appConfig.mtm+"/api/getComMappingDetailsByMapId"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("mapid", mapid); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/MainController.java deleted file mode 100644 index 513703f7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/MainController.java +++ /dev/null @@ -1,46 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.controller; - -import java.util.Arrays; -import java.util.List; - -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Asset; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategory; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategoryQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameter; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameterQuestions; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Feedback; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/mtm") -@Controller("mtmController") -public class MainController { - - private final RestTemplate restTemplate; - private final LoginUserInfo loginUserInfo; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate, AppConfig appConfig,LoginUserInfo loginUserInfo) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - this.loginUserInfo = loginUserInfo; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model,HttpSession session) { - session.setAttribute("userName", loginUserInfo.getLoginUserId().toString()); - return "modules/mtm/index"; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/MayorController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/MayorController.java deleted file mode 100644 index f759fe0b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/MayorController.java +++ /dev/null @@ -1,276 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.controller; - - -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.mtm.data.MTMOfficer; -import in.gov.chennaicorporation.gccoffice.mtm.data.MtmEvent; -import in.gov.chennaicorporation.gccoffice.mtm.data.Petition; -import in.gov.chennaicorporation.gccoffice.mtm.data.PetitionComplaint; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/mtm/mayor") -@Controller("mtmMayorController") -public class MayorController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - private final LoginUserInfo loginUserInfo; - private final String basePath = "modules/mtm/mayor"; - - @Autowired - public MayorController(RestTemplate restTemplate, AppConfig appConfig, LoginUserInfo loginUserInfo) { - this.restTemplate = restTemplate; - this.loginUserInfo = loginUserInfo; - this.appConfig = appConfig; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return basePath+"/index"; - } - - @GetMapping({"/petition-list"}) - public String showPetitionList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/petition-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - - Petition[] petitionList = restTemplate.getForObject(builder.toUriString(), Petition[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - - //System.out.println("Length: "+mtmComplaintTypesList.length); - */ - return basePath+"/petition-list"; - } - - @GetMapping({"/completed-petition-list"}) - public String showCompletedPetitionList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/completed-petition-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - - Petition[] petitionList = restTemplate.getForObject(builder.toUriString(), Petition[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - - //System.out.println("Length: "+mtmComplaintTypesList.length); - */ - return basePath+"/completed-petition-list"; - } - - @GetMapping({"/partial-petition-list"}) - public String showPartialPetitionList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/partial-petition-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - - Petition[] petitionList = restTemplate.getForObject(builder.toUriString(), Petition[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - - //System.out.println("Length: "+mtmComplaintTypesList.length); - - */ - return basePath+"/partial-petition-list"; - } - - @GetMapping({"/pending-petition-list"}) - public String showPendingPetitionList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/pending-petition-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - - Petition[] petitionList = restTemplate.getForObject(builder.toUriString(), Petition[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - - //System.out.println("Length: "+mtmComplaintTypesList.length); - * - */ - return basePath+"/pending-petition-list"; - } - - @GetMapping({"/complaint-list"}) - public String showComplaintList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/complaint-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - PetitionComplaint[] petitionList = restTemplate.getForObject(builder.toUriString(), PetitionComplaint[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - */ - - return basePath+"/complaint-list"; - } - - @GetMapping({"/completed-complaint-list"}) - public String showCompletedComplaintList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/completed-complaint-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - PetitionComplaint[] petitionList = restTemplate.getForObject(builder.toUriString(), PetitionComplaint[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - */ - - return basePath+"/completed-complaint-list"; - } - - @GetMapping({"/pending-complaint-list"}) - public String showPendingComplaintList(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/pending-complaint-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - PetitionComplaint[] petitionList = restTemplate.getForObject(builder.toUriString(), PetitionComplaint[].class); - model.addAttribute("petitionlist",petitionList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - /* - baseUrl = appConfig.mtm + "/api/complainttypes"; - MtmComplaintTypes[] mtmComplaintTypesList = restTemplate.getForObject(baseUrl, MtmComplaintTypes[].class); - model.addAttribute("complaintTypesList",mtmComplaintTypesList); - */ - return basePath+"/completed-complaint-list"; - } - - @GetMapping({"/by-event-list"}) - public String showEventListReport(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/by-event-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - MtmEvent[] mtmEventsTableList = restTemplate.getForObject(builder.toUriString(), MtmEvent[].class); - model.addAttribute("mtmEventsTableList",mtmEventsTableList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - - return basePath+"/by-event-list"; - } - - @GetMapping({"/by-officer-list"}) - public String showOfficerListReport(Model model,HttpSession session) { - - String eventid = "0"; - - if(session.getAttribute("eventid")!= null && !session.getAttribute("eventid").equals("0")){ - eventid = session.getAttribute("eventid").toString(); - } - String baseUrl = appConfig.mtm + "/api/mayor/by-officer-list"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("mtmid",eventid); - MTMOfficer[] officerTableList = restTemplate.getForObject(builder.toUriString(), MTMOfficer[].class); - - model.addAttribute("officerTableList",officerTableList); - - baseUrl = appConfig.mtm + "/api/event-list"; - MtmEvent[] mtmEventsList = restTemplate.getForObject(baseUrl, MtmEvent[].class); - model.addAttribute("mtmEventsList",mtmEventsList); - - return basePath+"/by-officer-list"; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/OfficerController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/OfficerController.java deleted file mode 100644 index 34c32f85..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/OfficerController.java +++ /dev/null @@ -1,46 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.controller; - -import java.util.Arrays; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Asset; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategory; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategoryQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameter; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameterQuestions; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Feedback; - -@RequestMapping("/gcc/mtm/officer") -@Controller("mtmOfficerController") -public class OfficerController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - private final String basePath = "modules/mtm/officer"; - - @Autowired - public OfficerController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return basePath+"/index"; - } - - @GetMapping({"/petition-list"}) - public String showPetitionList(Model model) { - return basePath+"/petition-list"; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/package-info.java deleted file mode 100644 index 7951d663..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MTMOfficer.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MTMOfficer.java deleted file mode 100644 index cc8fd3af..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MTMOfficer.java +++ /dev/null @@ -1,191 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class MTMOfficer { - private String mapId; - private String petitionNumber; - private String mtmEventsPetitionId; - private String mtmEvents; - private String offID; - private String status; - private String mtmComplaintTypes; - private String isDelete; - private String isActive; - private String createdBy; - private String cDate; - private String officerName; - private String eventName; - private String officerPetitionCount; - private String officerCompletedCount; - private String officerPendingCount; - - @JsonCreator - public MTMOfficer( - @JsonProperty("mapId") String mapId, - @JsonProperty("petitionNumber") String petitionNumber, - @JsonProperty("mtmEventsPetitionId") String mtmEventsPetitionId, - @JsonProperty("mtmEvents") String mtmEvents, - @JsonProperty("offID") String offID, - @JsonProperty("status") String status, - @JsonProperty("mtmComplaintTypes") String mtmComplaintTypes, - @JsonProperty("isDelete") String isDelete, - @JsonProperty("isActive") String isActive, - @JsonProperty("createdBy") String createdBy, - @JsonProperty("cDate") String cDate, - @JsonProperty("officer_name") String officerName, - @JsonProperty("event_name") String eventName, - @JsonProperty("officer_petition_count") String officerPetitionCount, - @JsonProperty("officer_completed_count") String officerCompletedCount, - @JsonProperty("officer_pending_count") String officerPendingCount - ) { - this.mapId = mapId; - this.petitionNumber = petitionNumber; - this.mtmEventsPetitionId = mtmEventsPetitionId; - this.mtmEvents = mtmEvents; - this.offID = offID; - this.status = status; - this.mtmComplaintTypes = mtmComplaintTypes; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - this.officerName = officerName; - this.eventName = eventName; - this.officerPetitionCount = officerPetitionCount; - this.officerCompletedCount = officerCompletedCount; - this.officerPendingCount = officerPendingCount; - } - - public String getMapId() { - return mapId; - } - - public void setMapId(String mapId) { - this.mapId = mapId; - } - - public String getPetitionNumber() { - return petitionNumber; - } - - public void setPetitionNumber(String petitionNumber) { - this.petitionNumber = petitionNumber; - } - - public String getMtmEventsPetitionId() { - return mtmEventsPetitionId; - } - - public void setMtmEventsPetitionId(String mtmEventsPetitionId) { - this.mtmEventsPetitionId = mtmEventsPetitionId; - } - - public String getMtmEvents() { - return mtmEvents; - } - - public void setMtmEvents(String mtmEvents) { - this.mtmEvents = mtmEvents; - } - - public String getOffID() { - return offID; - } - - public void setOffID(String offID) { - this.offID = offID; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getMtmComplaintTypes() { - return mtmComplaintTypes; - } - - public void setMtmComplaintTypes(String mtmComplaintTypes) { - this.mtmComplaintTypes = mtmComplaintTypes; - } - - public String getIsDelete() { - return isDelete; - } - - public void setIsDelete(String isDelete) { - this.isDelete = isDelete; - } - - public String getIsActive() { - return isActive; - } - - public void setIsActive(String isActive) { - this.isActive = isActive; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public String getOfficerName() { - return officerName; - } - - public void setOfficerName(String officerName) { - this.officerName = officerName; - } - - public String getEventName() { - return eventName; - } - - public void setEventName(String eventName) { - this.eventName = eventName; - } - - public String getOfficerPetitionCount() { - return officerPetitionCount; - } - - public void setOfficerPetitionCount(String officerPetitionCount) { - this.officerPetitionCount = officerPetitionCount; - } - - public String getOfficerCompletedCount() { - return officerCompletedCount; - } - - public void setOfficerCompletedCount(String officerCompletedCount) { - this.officerCompletedCount = officerCompletedCount; - } - - public String getOfficerPendingCount() { - return officerPendingCount; - } - - public void setOfficerPendingCount(String officerPendingCount) { - this.officerPendingCount = officerPendingCount; - } - - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MtmComplaintTypes.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MtmComplaintTypes.java deleted file mode 100644 index 895fcd6c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MtmComplaintTypes.java +++ /dev/null @@ -1,83 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameterQuestions.AssetCategory; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameterQuestions.AssetParameter; - -public class MtmComplaintTypes { - private Long complaintTypeId; - private String complaintType; - private Boolean isDelete; - private Boolean isActive; - private Long createdBy; - private String cDate; - - @JsonCreator - public MtmComplaintTypes( - @JsonProperty("complaintTypeId") Long complaintTypeId, - @JsonProperty("complaintType") String complaintType, - @JsonProperty("isDelete") Boolean isDelete, - @JsonProperty("isActive") Boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.complaintTypeId = complaintTypeId; - this.complaintType = complaintType; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getComplaintTypeId() { - return complaintTypeId; - } - - public void setComplaintTypeId(Long complaintTypeId) { - this.complaintTypeId = complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } - - public void setComplaintType(String complaintType) { - this.complaintType = complaintType; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MtmEvent.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MtmEvent.java deleted file mode 100644 index d1ade56f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/MtmEvent.java +++ /dev/null @@ -1,226 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class MtmEvent { - private Long mtmId; - private String eventName; - private String eventAddress; - private String eventDate; - private String zone; - private String ackNo; - private Long startPetId; - private Boolean isDelete; - private Boolean isActive; - private Long createdBy; - private String cDate; - private String event_date; - private Long total_petitions; - private Long petitions_completed; - private Long petition_partially_completed; - private Long petitions_pending; - private Long total_compliants; - private Long compliants_completed; - private Long compliants_pending; - - // Constructors, getters, and setters - - @JsonCreator - public MtmEvent( - @JsonProperty("mtmId") Long mtmId, - @JsonProperty("eventName") String eventName, - @JsonProperty("eventAddress") String eventAddress, - @JsonProperty("eventDate") String eventDate, - @JsonProperty("zone") String zone, - @JsonProperty("ackNo") String ackNo, - @JsonProperty("startPetId") Long startPetId, - @JsonProperty("isDelete") Boolean isDelete, - @JsonProperty("isActive") Boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate, - @JsonProperty("event_date") String event_date, - @JsonProperty("total_petitions") Long total_petitions, - @JsonProperty("petitions_completed") Long petitions_completed, - @JsonProperty("petition_partially_completed") Long petition_partially_completed, - @JsonProperty("petitions_pending") Long petitions_pending, - @JsonProperty("total_compliants") Long total_compliants, - @JsonProperty("compliants_completed") Long compliants_completed, - @JsonProperty("compliants_pending") Long compliants_pending - ) { - this.mtmId = mtmId; - this.eventName = eventName; - this.eventAddress = eventAddress; - this.eventDate = eventDate; - this.zone = zone; - this.ackNo = ackNo; - this.startPetId = startPetId; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - this.event_date = event_date; - this.total_petitions = total_petitions; - this.petitions_completed = petitions_completed; - this.petition_partially_completed = petition_partially_completed; - this.petitions_pending = petitions_pending; - this.total_compliants = total_compliants; - this.compliants_completed = compliants_completed; - this.compliants_pending = compliants_pending; - } - - public Long getMtmId() { - return mtmId; - } - - public void setMtmId(Long mtmId) { - this.mtmId = mtmId; - } - - public String getEventName() { - return eventName; - } - - public void setEventName(String eventName) { - this.eventName = eventName; - } - - public String getEventAddress() { - return eventAddress; - } - - public void setEventAddress(String eventAddress) { - this.eventAddress = eventAddress; - } - - public String getEventDate() { - return eventDate; - } - - public void setEventDate(String eventDate) { - this.eventDate = eventDate; - } - - public String getZone() { - return zone; - } - - public void setZone(String zone) { - this.zone = zone; - } - - public String getAckNo() { - return ackNo; - } - - public void setAckNo(String ackNo) { - this.ackNo = ackNo; - } - - public Long getStartPetId() { - return startPetId; - } - - public void setStartPetId(Long startPetId) { - this.startPetId = startPetId; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public String getEvent_date() { - return event_date; - } - - public void setEvent_date(String event_date) { - this.event_date = event_date; - } - - public Long getTotal_petitions() { - return total_petitions; - } - - public void setTotal_petitions(Long total_petitions) { - this.total_petitions = total_petitions; - } - - public Long getPetitions_completed() { - return petitions_completed; - } - - public void setPetitions_completed(Long petitions_completed) { - this.petitions_completed = petitions_completed; - } - - public Long getPetition_partially_completed() { - return petition_partially_completed; - } - - public void setPetition_partially_completed(Long petition_partially_completed) { - this.petition_partially_completed = petition_partially_completed; - } - - public Long getPetitions_pending() { - return petitions_pending; - } - - public void setPetitions_pending(Long petitions_pending) { - this.petitions_pending = petitions_pending; - } - - public Long getTotal_compliants() { - return total_compliants; - } - - public void setTotal_compliants(Long total_compliants) { - this.total_compliants = total_compliants; - } - - public Long getCompliants_completed() { - return compliants_completed; - } - - public void setCompliants_completed(Long compliants_completed) { - this.compliants_completed = compliants_completed; - } - - public Long getCompliants_pending() { - return compliants_pending; - } - - public void setCompliants_pending(Long compliants_pending) { - this.compliants_pending = compliants_pending; - } - - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/Petition.java deleted file mode 100644 index cc300f7b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/Petition.java +++ /dev/null @@ -1,472 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Petition { - private Long petitionId; - private MtmEvents mtmEvents; - private String petitionNumber; - private String petitionerName; - private String petitionerMobile; - private String petitionerComplaint; - private String petitionerAddress; - private String petitionerPincode; - private String petitionerNatureOfComplaint; - private String tableNo; - private Boolean isDelete; - private Boolean isActive; - private Long createdBy; - private String cDate; - private String status; - private String petitionerComplaint_txt; - - @JsonCreator - public Petition( - @JsonProperty("petitionId") Long petitionId, - @JsonProperty("mtmEvents") MtmEvents mtmEvents, - @JsonProperty("petitionNumber") String petitionNumber, - @JsonProperty("petitionerName") String petitionerName, - @JsonProperty("petitionerMobile") String petitionerMobile, - @JsonProperty("petitionerComplaint") String petitionerComplaint, - @JsonProperty("petitionerAddress") String petitionerAddress, - @JsonProperty("petitionerPincode") String petitionerPincode, - @JsonProperty("petitionerNatureOfComplaint") String petitionerNatureOfComplaint, - @JsonProperty("tableNo") String tableNo, - @JsonProperty("isDelete") Boolean isDelete, - @JsonProperty("isActive") Boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate, - @JsonProperty("status") String status, - @JsonProperty("petitionerComplaint_txt") String petitionerComplaint_txt - ) { - this.petitionId = petitionId; - this.mtmEvents = mtmEvents; - this.petitionNumber = petitionNumber; - this.petitionerName = petitionerName; - this.petitionerMobile = petitionerMobile; - this.petitionerComplaint = petitionerComplaint; - this.petitionerAddress = petitionerAddress; - this.petitionerPincode = petitionerPincode; - this.petitionerNatureOfComplaint = petitionerNatureOfComplaint; - this.tableNo = tableNo; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - this.status = status; - this.petitionerComplaint_txt = petitionerComplaint_txt; - } - - - - public Long getPetitionId() { - return petitionId; - } - - - - public void setPetitionId(Long petitionId) { - this.petitionId = petitionId; - } - - - - public MtmEvents getMtmEvents() { - return mtmEvents; - } - - - - public void setMtmEvents(MtmEvents mtmEvents) { - this.mtmEvents = mtmEvents; - } - - - - public String getPetitionNumber() { - return petitionNumber; - } - - - - public void setPetitionNumber(String petitionNumber) { - this.petitionNumber = petitionNumber; - } - - - - public String getPetitionerName() { - return petitionerName; - } - - - - public void setPetitionerName(String petitionerName) { - this.petitionerName = petitionerName; - } - - - - public String getPetitionerMobile() { - return petitionerMobile; - } - - - - public void setPetitionerMobile(String petitionerMobile) { - this.petitionerMobile = petitionerMobile; - } - - - - public String getPetitionerComplaint() { - return petitionerComplaint; - } - - - - public void setPetitionerComplaint(String petitionerComplaint) { - this.petitionerComplaint = petitionerComplaint; - } - - - - public String getPetitionerAddress() { - return petitionerAddress; - } - - - - public void setPetitionerAddress(String petitionerAddress) { - this.petitionerAddress = petitionerAddress; - } - - - - public String getPetitionerPincode() { - return petitionerPincode; - } - - - - public void setPetitionerPincode(String petitionerPincode) { - this.petitionerPincode = petitionerPincode; - } - - - - public String getPetitionerNatureOfComplaint() { - return petitionerNatureOfComplaint; - } - - - - public void setPetitionerNatureOfComplaint(String petitionerNatureOfComplaint) { - this.petitionerNatureOfComplaint = petitionerNatureOfComplaint; - } - - - - public String getTableNo() { - return tableNo; - } - - - - public void setTableNo(String tableNo) { - this.tableNo = tableNo; - } - - - - public Boolean getIsDelete() { - return isDelete; - } - - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - - public Boolean getIsActive() { - return isActive; - } - - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - - public Long getCreatedBy() { - return createdBy; - } - - - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - - - public String getcDate() { - return cDate; - } - - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - - - public String getStatus() { - return status; - } - - - - public void setStatus(String status) { - this.status = status; - } - - - - public String getPetitionerComplaint_txt() { - return petitionerComplaint_txt; - } - - - - public void setPetitionerComplaint_txt(String petitionerComplaint_txt) { - this.petitionerComplaint_txt = petitionerComplaint_txt; - } - - - - // Define the nested classes for mtmEvents - public static class MtmEvents { - private Long mtmId; - private String eventName; - private String eventAddress; - private String eventDate; - private String zone; - private String ackNo; - private Long startPetId; - private Boolean isDelete; - private Boolean isActive; - private Long createdBy; - private String cDate; - private String event_date; - private Long total_petitions; - private Long petitions_completed; - private Long petition_partially_completed; - private Long petitions_pending; - private Long total_compliants; - private Long compliants_completed; - private Long compliants_pending; - - @JsonCreator - public MtmEvents( - @JsonProperty("mtmId") Long mtmId, - @JsonProperty("eventName") String eventName, - @JsonProperty("eventAddress") String eventAddress, - @JsonProperty("eventDate") String eventDate, - @JsonProperty("zone") String zone, - @JsonProperty("ackNo") String ackNo, - @JsonProperty("startPetId") Long startPetId, - @JsonProperty("isDelete") Boolean isDelete, - @JsonProperty("isActive") Boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate, - @JsonProperty("event_date") String event_date, - @JsonProperty("total_petitions") Long total_petitions, - @JsonProperty("petitions_completed") Long petitions_completed, - @JsonProperty("petition_partially_completed") Long petition_partially_completed, - @JsonProperty("petitions_pending") Long petitions_pending, - @JsonProperty("total_compliants") Long total_compliants, - @JsonProperty("compliants_completed") Long compliants_completed, - @JsonProperty("compliants_pending") Long compliants_pending - ) { - this.mtmId = mtmId; - this.eventName = eventName; - this.eventAddress = eventAddress; - this.eventDate = eventDate; - this.zone = zone; - this.ackNo = ackNo; - this.startPetId = startPetId; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - this.event_date = event_date; - this.total_petitions = total_petitions; - this.petitions_completed = petitions_completed; - this.petition_partially_completed = petition_partially_completed; - this.petitions_pending = petitions_pending; - this.total_compliants = total_compliants; - this.compliants_completed = compliants_completed; - this.compliants_pending = compliants_pending; - } - - public Long getMtmId() { - return mtmId; - } - - public void setMtmId(Long mtmId) { - this.mtmId = mtmId; - } - - public String getEventName() { - return eventName; - } - - public void setEventName(String eventName) { - this.eventName = eventName; - } - - public String getEventAddress() { - return eventAddress; - } - - public void setEventAddress(String eventAddress) { - this.eventAddress = eventAddress; - } - - public String getEventDate() { - return eventDate; - } - - public void setEventDate(String eventDate) { - this.eventDate = eventDate; - } - - public String getZone() { - return zone; - } - - public void setZone(String zone) { - this.zone = zone; - } - - public String getAckNo() { - return ackNo; - } - - public void setAckNo(String ackNo) { - this.ackNo = ackNo; - } - - public Long getStartPetId() { - return startPetId; - } - - public void setStartPetId(Long startPetId) { - this.startPetId = startPetId; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public String getEvent_date() { - return event_date; - } - - public void setEvent_date(String event_date) { - this.event_date = event_date; - } - - public Long getTotal_petitions() { - return total_petitions; - } - - public void setTotal_petitions(Long total_petitions) { - this.total_petitions = total_petitions; - } - - public Long getPetitions_completed() { - return petitions_completed; - } - - public void setPetitions_completed(Long petitions_completed) { - this.petitions_completed = petitions_completed; - } - - public Long getPetition_partially_completed() { - return petition_partially_completed; - } - - public void setPetition_partially_completed(Long petition_partially_completed) { - this.petition_partially_completed = petition_partially_completed; - } - - public Long getPetitions_pending() { - return petitions_pending; - } - - public void setPetitions_pending(Long petitions_pending) { - this.petitions_pending = petitions_pending; - } - - public Long getTotal_compliants() { - return total_compliants; - } - - public void setTotal_compliants(Long total_compliants) { - this.total_compliants = total_compliants; - } - - public Long getCompliants_completed() { - return compliants_completed; - } - - public void setCompliants_completed(Long compliants_completed) { - this.compliants_completed = compliants_completed; - } - - public Long getCompliants_pending() { - return compliants_pending; - } - - public void setCompliants_pending(Long compliants_pending) { - this.compliants_pending = compliants_pending; - } - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/PetitionComplaint.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/PetitionComplaint.java deleted file mode 100644 index b9a9aa4e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/PetitionComplaint.java +++ /dev/null @@ -1,461 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class PetitionComplaint { - private int mapId; - private String petitionNumber; - private MtmEventsPetitionId mtmEventsPetitionId; - private MtmEvents mtmEvents; - private String offID; - private String status; - private MtmComplaintTypes mtmComplaintTypes; - private boolean isDelete; - private boolean isActive; - private int createdBy; - private String cDate; - private String officer_name; - private String event_name; - private Integer officer_petition_count; - private Integer officer_completed_count; - private Integer officer_pending_count; - - // Getters and setters for the above fields - - public int getMapId() { - return mapId; - } - - public void setMapId(int mapId) { - this.mapId = mapId; - } - - public String getPetitionNumber() { - return petitionNumber; - } - - public void setPetitionNumber(String petitionNumber) { - this.petitionNumber = petitionNumber; - } - - public MtmEventsPetitionId getMtmEventsPetitionId() { - return mtmEventsPetitionId; - } - - public void setMtmEventsPetitionId(MtmEventsPetitionId mtmEventsPetitionId) { - this.mtmEventsPetitionId = mtmEventsPetitionId; - } - - public MtmEvents getMtmEvents() { - return mtmEvents; - } - - public void setMtmEvents(MtmEvents mtmEvents) { - this.mtmEvents = mtmEvents; - } - - public String getOffID() { - return offID; - } - - public void setOffID(String offID) { - this.offID = offID; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public MtmComplaintTypes getMtmComplaintTypes() { - return mtmComplaintTypes; - } - - public void setMtmComplaintTypes(MtmComplaintTypes mtmComplaintTypes) { - this.mtmComplaintTypes = mtmComplaintTypes; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public int getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(int createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public String getOfficer_name() { - return officer_name; - } - - public void setOfficer_name(String officer_name) { - this.officer_name = officer_name; - } - - public String getEvent_name() { - return event_name; - } - - public void setEvent_name(String event_name) { - this.event_name = event_name; - } - - public Integer getOfficer_petition_count() { - return officer_petition_count; - } - - public void setOfficer_petition_count(Integer officer_petition_count) { - this.officer_petition_count = officer_petition_count; - } - - public Integer getOfficer_completed_count() { - return officer_completed_count; - } - - public void setOfficer_completed_count(Integer officer_completed_count) { - this.officer_completed_count = officer_completed_count; - } - - public Integer getOfficer_pending_count() { - return officer_pending_count; - } - - public void setOfficer_pending_count(Integer officer_pending_count) { - this.officer_pending_count = officer_pending_count; - } - - public static class MtmEventsPetitionId { - private int petitionId; - private MtmEvents mtmEvents; - private String petitionNumber; - private String petitionerName; - private long petitionerMobile; - private String petitionerComplaint; - private String petitionerAddress; - private String petitionerPincode; - private String petitionerNatureOfComplaint; - private String tableNo; - private boolean isDelete; - private boolean isActive; - private long createdBy; - private String cDate; - private String status; - private String petitionerComplaint_txt; - - // Getters and setters for the above fields - public int getPetitionId() { - return petitionId; - } - public void setPetitionId(int petitionId) { - this.petitionId = petitionId; - } - public MtmEvents getMtmEvents() { - return mtmEvents; - } - public void setMtmEvents(MtmEvents mtmEvents) { - this.mtmEvents = mtmEvents; - } - public String getPetitionNumber() { - return petitionNumber; - } - public void setPetitionNumber(String petitionNumber) { - this.petitionNumber = petitionNumber; - } - public String getPetitionerName() { - return petitionerName; - } - public void setPetitionerName(String petitionerName) { - this.petitionerName = petitionerName; - } - public long getPetitionerMobile() { - return petitionerMobile; - } - public void setPetitionerMobile(long petitionerMobile) { - this.petitionerMobile = petitionerMobile; - } - public String getPetitionerComplaint() { - return petitionerComplaint; - } - public void setPetitionerComplaint(String petitionerComplaint) { - this.petitionerComplaint = petitionerComplaint; - } - public String getPetitionerAddress() { - return petitionerAddress; - } - public void setPetitionerAddress(String petitionerAddress) { - this.petitionerAddress = petitionerAddress; - } - public String getPetitionerPincode() { - return petitionerPincode; - } - public void setPetitionerPincode(String petitionerPincode) { - this.petitionerPincode = petitionerPincode; - } - public String getPetitionerNatureOfComplaint() { - return petitionerNatureOfComplaint; - } - public void setPetitionerNatureOfComplaint(String petitionerNatureOfComplaint) { - this.petitionerNatureOfComplaint = petitionerNatureOfComplaint; - } - public String getTableNo() { - return tableNo; - } - public void setTableNo(String tableNo) { - this.tableNo = tableNo; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public long getCreatedBy() { - return createdBy; - } - public void setCreatedBy(long createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - public String getPetitionerComplaint_txt() { - return petitionerComplaint_txt; - } - public void setPetitionerComplaint_txt(String petitionerComplaint_txt) { - this.petitionerComplaint_txt = petitionerComplaint_txt; - } - - - } - - public static class MtmEvents { - private int mtmId; - private String eventName; - private String eventAddress; - private String eventDate; - private String zone; - private String ackNo; - private long startPetId; - private boolean isDelete; - private boolean isActive; - private long createdBy; - private String cDate; - private String event_date; - private Long total_petitions; - private Long petitions_completed; - private Long petition_partially_completed; - private Long petitions_pending; - private Long total_compliants; - private Long compliants_completed; - private Long compliants_pending; - - - // Getters and setters for the above fields - public int getMtmId() { - return mtmId; - } - public void setMtmId(int mtmId) { - this.mtmId = mtmId; - } - public String getEventName() { - return eventName; - } - public void setEventName(String eventName) { - this.eventName = eventName; - } - public String getEventAddress() { - return eventAddress; - } - public void setEventAddress(String eventAddress) { - this.eventAddress = eventAddress; - } - public String getEventDate() { - return eventDate; - } - public void setEventDate(String eventDate) { - this.eventDate = eventDate; - } - public String getZone() { - return zone; - } - public void setZone(String zone) { - this.zone = zone; - } - public String getAckNo() { - return ackNo; - } - public void setAckNo(String ackNo) { - this.ackNo = ackNo; - } - public long getStartPetId() { - return startPetId; - } - public void setStartPetId(long startPetId) { - this.startPetId = startPetId; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public long getCreatedBy() { - return createdBy; - } - public void setCreatedBy(long createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - public String getEvent_date() { - return event_date; - } - public void setEvent_date(String event_date) { - this.event_date = event_date; - } - public Long getTotal_petitions() { - return total_petitions; - } - public void setTotal_petitions(Long total_petitions) { - this.total_petitions = total_petitions; - } - public Long getPetitions_completed() { - return petitions_completed; - } - public void setPetitions_completed(Long petitions_completed) { - this.petitions_completed = petitions_completed; - } - public Long getPetition_partially_completed() { - return petition_partially_completed; - } - public void setPetition_partially_completed(Long petition_partially_completed) { - this.petition_partially_completed = petition_partially_completed; - } - public Long getPetitions_pending() { - return petitions_pending; - } - public void setPetitions_pending(Long petitions_pending) { - this.petitions_pending = petitions_pending; - } - public Long getTotal_compliants() { - return total_compliants; - } - public void setTotal_compliants(Long total_compliants) { - this.total_compliants = total_compliants; - } - public Long getCompliants_completed() { - return compliants_completed; - } - public void setCompliants_completed(Long compliants_completed) { - this.compliants_completed = compliants_completed; - } - public Long getCompliants_pending() { - return compliants_pending; - } - public void setCompliants_pending(Long compliants_pending) { - this.compliants_pending = compliants_pending; - } - - - } - - public static class MtmComplaintTypes { - private int complaintTypeId; - private String complaintType; - private boolean isDelete; - private boolean isActive; - private int createdBy; - private String cDate; - - // Getters and setters for the above fields - public int getComplaintTypeId() { - return complaintTypeId; - } - public void setComplaintTypeId(int complaintTypeId) { - this.complaintTypeId = complaintTypeId; - } - public String getComplaintType() { - return complaintType; - } - public void setComplaintType(String complaintType) { - this.complaintType = complaintType; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public int getCreatedBy() { - return createdBy; - } - public void setCreatedBy(int createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/package-info.java deleted file mode 100644 index 81f451bf..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/package-info.java deleted file mode 100644 index a10f360d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/mtm/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.mtm; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/.DS_Store deleted file mode 100644 index f7769b72..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java deleted file mode 100644 index cfdcf140..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java +++ /dev/null @@ -1,1199 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.controller; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Required; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.nulm.service.NulmService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/api/nulm") -@RestController("nulmAPI") -public class NulmAPIController { - - private final Environment environment; - - @Autowired - private NulmService nulmService; - - @Autowired - private JdbcTemplate nulmJdbcTemplate; - - @Autowired - public NulmAPIController(NulmService nulmService, JdbcTemplate nulmJdbcTemplate, Environment environment) { - this.nulmService = nulmService; - this.nulmJdbcTemplate = nulmJdbcTemplate; - this.environment = environment; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlNulmDataSource") DataSource dataSource) { - this.nulmJdbcTemplate = new JdbcTemplate(dataSource); - } - - @GetMapping("/getYear") - public ResponseEntity>> getYear() { - List> yearList = nulmService.getYearList(); - return ResponseEntity.ok(yearList); - } - - @GetMapping("/getMonth") - public ResponseEntity>> getMonth(int year) { - // System.out.println("year: "+year); - List> monthList = nulmService.getMonthList(year); - return ResponseEntity.ok(monthList); - } - - @GetMapping("/getGender") - public ResponseEntity>> getGender() { - - List> genderList = nulmService.getGenderList(); - return ResponseEntity.ok(genderList); - } - - @GetMapping("/getDivisionList") - public ResponseEntity>> getDivisionList(@RequestParam(required = false) String zone) { - List> divisionList = nulmService.getDivisionList(zone); - return ResponseEntity.ok(divisionList); - } - - @PostMapping("/saveGroup") - public ResponseEntity saveSchemeGroup(@RequestBody Map payload) { - try { - Map groupData = new HashMap<>(payload); - nulmService.saveSchemeGroup(groupData); - return ResponseEntity.ok("Self Help Group Saved Successfully"); - } catch (Exception e) { - return ResponseEntity.status(500).body("Error saving Scheme Group: " + e.getMessage()); - } - } - - @GetMapping("/attendance-dates") // need to add - public ResponseEntity>> getAttendanceDates( - @RequestParam(required = false) String enrollmentId, - @RequestParam(required = false) String fromdate, - @RequestParam(required = false) String todate, - @RequestParam(required = false) String type, - Model model) { - - return ResponseEntity.ok(nulmService.fetchAttendanceDates(enrollmentId, fromdate, todate, type)); - - } - - /* - * @PostMapping("/saveOrder") - * public ResponseEntity saveOrderDetails(@RequestBody Map payload) { - * try { - * Map orderData = new HashMap<>(payload); - * nulmService.saveOrderDetails(orderData); - * return ResponseEntity.ok("Order saved successfully."); - * } catch (IllegalArgumentException e) { - * return ResponseEntity.badRequest().body("Invalid data: " + e.getMessage()); - * } catch (Exception e) { - * return ResponseEntity.status(500).body("Error saving order: " + - * e.getMessage()); - * } - * } - */ - @PostMapping("/saveStaff") - public ResponseEntity saveStaffDetails(@RequestBody Map payload) { - try { - nulmService.saveStaffDetails(payload); - return ResponseEntity.ok("Staff details saved successfully."); - } catch (IllegalArgumentException e) { - return ResponseEntity.badRequest().body("Error: " + e.getMessage()); - } catch (Exception e) { - return ResponseEntity.status(500).body("Error saving staff details: " + e.getMessage()); - } - } - - @PostMapping("/assignAppointment") - public ResponseEntity assignOrderToEnrollments(@RequestBody Map requestBody) { - int orderId = (int) requestBody.get("orderId"); - String inchargePhoneno = ((String) requestBody.get("incharge_phoneno")); - String designation = (String) requestBody.get("designation"); - List enrollmentIds = (List) requestBody.get("enrollmentIds"); - - // Step 1: Retrieve the selected order - String getOrderSql = "SELECT * FROM order_details WHERE order_id = ?"; - Map orderDetails; - - try { - orderDetails = nulmJdbcTemplate.queryForMap(getOrderSql, orderId); - } catch (EmptyResultDataAccessException e) { - // Handle the case where no order is found - return new ResponseEntity<>("No order found with order_id: " + orderId, HttpStatus.NOT_FOUND); - } - - if (orderDetails != null) { - // Step 2: Build the SQL for updating enrollments with dynamic IN clause - StringBuilder updateSql = new StringBuilder( - "UPDATE enrollment_table SET order_id = ?, appointed = 'Yes', facial_attendance = 'No', incharge_phoneno = ?, designation = ?, appointed_date = CURRENT_DATE WHERE enrollment_id IN ("); - - // Add placeholders for the IN clause based on the size of the enrollmentIds - // list - for (int i = 0; i < enrollmentIds.size(); i++) { - updateSql.append("?"); - if (i < enrollmentIds.size() - 1) { - updateSql.append(", "); - } - } - updateSql.append(")"); - - // Combine the orderId, inchargePhoneno, designation, and the list of - // enrollmentIds - List parameters = new ArrayList<>(); - parameters.add(orderId); - parameters.add(inchargePhoneno); - parameters.add(designation); - parameters.addAll(enrollmentIds); - - // Execute the update query - try { - nulmJdbcTemplate.update(updateSql.toString(), parameters.toArray()); - return new ResponseEntity<>("Order assigned to enrollments and appointed successfully.", HttpStatus.OK); - } catch (DataAccessException e) { - // Handle any data access exceptions - return new ResponseEntity<>("Error updating enrollments: " + e.getMessage(), - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - return new ResponseEntity<>("Unexpected error occurred.", HttpStatus.INTERNAL_SERVER_ERROR); - } - - @PostMapping("/assignDropout") - public ResponseEntity assignDropout(@RequestBody Map requestBody) { - int orderId = (int) requestBody.get("orderId"); - List enrollmentIds = (List) requestBody.get("enrollmentIds"); - - // Step 1: Retrieve the selected order - String getOrderSql = "SELECT * FROM order_details WHERE order_id = ?"; - Map orderDetails; - - try { - orderDetails = nulmJdbcTemplate.queryForMap(getOrderSql, orderId); - } catch (EmptyResultDataAccessException e) { - // Handle the case where no order is found - return new ResponseEntity<>("No order found with order_id: " + orderId, HttpStatus.NOT_FOUND); - } - - if (orderDetails != null) { - // Step 2: Build the SQL for updating enrollments with dynamic IN clause - StringBuilder updateSql = new StringBuilder( - "UPDATE enrollment_table SET appointed = 'Drop', dropout = 'Yes', dropout_date = CURRENT_DATE WHERE enrollment_id IN ("); - - // Add placeholders for the IN clause based on the size of the enrollmentIds - // list - for (int i = 0; i < enrollmentIds.size(); i++) { - updateSql.append("?"); - if (i < enrollmentIds.size() - 1) { - updateSql.append(", "); - } - } - updateSql.append(") AND order_id = ?"); // Match the order_id in the WHERE clause - - // Combine the list of enrollmentIds and the orderId - List parameters = new ArrayList<>(enrollmentIds); - parameters.add(orderId); // Add orderId at the end of the parameters list - - // Execute the update query - try { - int rowsAffected = nulmJdbcTemplate.update(updateSql.toString(), parameters.toArray()); - if (rowsAffected > 0) { - return new ResponseEntity<>("Order assigned to enrollments has been Dropout successfully.", - HttpStatus.OK); - } else { - return new ResponseEntity<>("No matching records found to update.", HttpStatus.NOT_FOUND); - } - } catch (DataAccessException e) { - // Handle any data access exceptions - return new ResponseEntity<>("Error updating enrollments: " + e.getMessage(), - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - return new ResponseEntity<>("Unexpected error occurred.", HttpStatus.INTERNAL_SERVER_ERROR); - } - - @GetMapping("/getAllSchemeGroupNames") - public ResponseEntity>> getAllSchemeGroupNames() { - try { - List> schemeGroupNames = nulmService.getAllSchemeGroupNames(); - return ResponseEntity.ok(schemeGroupNames); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); - } - } - - @GetMapping("/getAllOrderNumber") - public ResponseEntity> getAllOrderNumber() { - try { - List schemeGroupNames = nulmService.getAllOrderNumber(); - return ResponseEntity.ok(schemeGroupNames); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); - } - } - - @GetMapping("/getAllSchemeGroups") - public ResponseEntity>> getAllSchemeGroups() { - try { - List> groups = nulmService.getAllSchemeGroups(); - return ResponseEntity.ok(groups); - } catch (Exception e) { - return ResponseEntity.status(500).body(null); - } - } - - /////// get all list of orders//////////////////////////// - @GetMapping("/getAllOrders") - public ResponseEntity>> getAllOrders() { - try { - List> groups = nulmService.getAllOrders(); - return ResponseEntity.ok(groups); - } catch (Exception e) { - return ResponseEntity.status(500).body(null); - } - } - - @GetMapping("/getAllStaffNames") - public ResponseEntity> getAllStaffNames() { - try { - List schemeGroupNames = nulmService.getStaffName(); - return ResponseEntity.ok(schemeGroupNames); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); - } - } - - @GetMapping("/appointedCounts") - public ResponseEntity> getAppointedCounts( - @RequestParam(required = false) Integer groupId) { - - try { - // Validate that groupId is provided - if (groupId == null) { - return ResponseEntity.badRequest().body(null); // You can also return a specific error message - } - - // Call the service method to get the counts - Map counts = nulmService.getAppointedCounts(groupId); - - return ResponseEntity.ok(counts); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); // You can also return the error - // message - } - } - - @PostMapping("/markAbsent") - public ResponseEntity markAbsent(@RequestParam int employeeId) { - int result = nulmService.markAbsentEntry(employeeId); - - if (result > 0) { - return ResponseEntity.ok("Employee marked as absent successfully."); - } else { - return ResponseEntity.status(304) - .body("No update made. Employee may already be marked as absent or has attended."); - } - } - - @PostMapping("/markOverDuty") - public ResponseEntity markOverDuty(@RequestParam int employeeId) { - int result = nulmService.markOverDuty(employeeId); - - if (result > 0) { - return ResponseEntity.ok("Over Duty marked successfully."); - } else { - return ResponseEntity.status(304).body("No update made. Employee ID may not exist."); - } - } - - @PostMapping("/markAttendance") - public ResponseEntity markAttendance( - @RequestParam int employeeId, - @RequestParam String markAttendance) { - try { - String result = nulmService.markAttendance(employeeId, markAttendance); - if ("Checked in successfully".equals(result) || "Checked out successfully".equals(result)) { - return ResponseEntity.ok(result); - } else { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); - } - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to mark attendance"); - } - } - - @GetMapping("/getAllOrderDetails") - public ResponseEntity>> getAllOrderDetails() { - try { - List> orderDetails = nulmService.getAllOrderDetails(); - return ResponseEntity.ok(orderDetails); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.emptyList()); - } - } - - @GetMapping("/enrollmentCountsbyorderId") - public ResponseEntity> getEnrollmentCounts(@RequestParam int orderId) { - Map counts = nulmService.getAppointedCounts(orderId); - return ResponseEntity.ok(counts); - } - - @GetMapping("/dropOutCounts") - public ResponseEntity> getDropCounts(@RequestParam int orderId) { - Map counts = nulmService.getDropCounts(orderId); - return ResponseEntity.ok(counts); - } - - @GetMapping("/enrollmentCountsbygroupId") - public ResponseEntity>> getEnrollmentbygroupId(@RequestParam int groupId) { - List> enrollmentDetails = nulmService.getEnrollmentDetails(groupId); - return ResponseEntity.ok(enrollmentDetails); - } - - @GetMapping("/appointmentCountsbygroupId") - public ResponseEntity>> getAppointedDetails(@RequestParam int groupId) { - List> enrollmentDetails = nulmService.getAppointedDetails(groupId); - return ResponseEntity.ok(enrollmentDetails); - } - - @GetMapping("/getDepartment") - public ResponseEntity>> getDepartment() { - List> orderNumbers = nulmService.getDepartment(); - return ResponseEntity.ok(orderNumbers); - } - - @GetMapping("/getEnrollmentdeatilsByID/{enrollmentId}") - public ResponseEntity>> getEnrollmentsById( - @PathVariable("enrollmentId") int enrollmentId) { - List> enrollments = nulmService.getEnrollmentsById(enrollmentId); - - if (enrollments.isEmpty()) { - return ResponseEntity.noContent().build(); // Return 204 No Content if no enrollments are found - } - - return ResponseEntity.ok(enrollments); // Return 200 OK with the list of enrollments - } - - @GetMapping("/selfHelpGroups") - public ResponseEntity>> getSelfHelpGroups() { - List> selfHelpGroups = nulmService.getSelfHelpGroups(); - return ResponseEntity.ok(selfHelpGroups); - } - - @GetMapping("/orderNumbers") - public ResponseEntity>> getOrderNumbers() { - List> orderNumbers = nulmService.getOrderNumbers(); - return ResponseEntity.ok(orderNumbers); - } - - @PostMapping("/updateEnrollment/{id}") - public ResponseEntity updateEnrollment( - @PathVariable("id") int id, - @RequestParam String dateOfBirth, - @RequestParam String gender, - @RequestParam int groupId, // New parameter - @RequestParam int orderId // New parameter - ) { - int rowsAffected = nulmService.updateEnrollment(id, dateOfBirth, gender, groupId, orderId); - - if (rowsAffected > 0) { - return new ResponseEntity<>("Enrollment updated successfully", HttpStatus.OK); - } else { - return new ResponseEntity<>("Enrollment update failed", HttpStatus.NOT_FOUND); - } - } - - @PostMapping("/saveOrder") - public ResponseEntity saveOrderDetails(@RequestParam String order_number, - @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date order_date, - @RequestParam int no_of_staffs, - @RequestParam String order_description, - @RequestParam MultipartFile ordercopyurl, - @RequestParam String order_generated_by, - @RequestParam String category, - @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date validity_date) { - String order_copy_url = ""; - try { - // Fetch the upload directory and folder name from environment - String uploadDirectory = environment.getProperty("file.upload.directory"); - String folderName = environment.getProperty("nulm_foldername"); - String fileName = "OrderCopy_" + ordercopyurl.getOriginalFilename(); - - // Construct the file path - String filepath = uploadDirectory + folderName + "/" + fileName; - Path path = Paths.get(filepath); - - // Ensure the directory exists - Files.createDirectories(path.getParent()); - - // Write the file to the specified path - Files.write(path, ordercopyurl.getBytes()); - - // Set the order_copy_url to the relative file path for storing in DB - order_copy_url = folderName + "/" + fileName; - - // Save the order details using the service method - String savedOrderNumber = nulmService.saveOrderDetails( - order_number, - order_date, - no_of_staffs, - order_description, - order_copy_url, - order_generated_by, - category, - validity_date); - - return ResponseEntity.ok("Order saved successfully with order number: " + savedOrderNumber); - - } catch (Exception e) { - // Handle error scenarios - return ResponseEntity.status(500).body("Error saving order: " + e.getMessage()); - } - } - /* - * @GetMapping("/staffInititeadList") - * public ResponseEntity>> - * getAttendanceWithInitiatedSalaryByGroupId(@RequestParam("inchargeName") - * String inchargeName, - * - * @RequestParam("month") String month) { - * List> staffList = - * nulmService.getAttendanceWithInitiatedSalary(inchargeName, month); - * return ResponseEntity.ok(staffList); - * } - * - * @GetMapping("/staffInititeadList") - * public ResponseEntity>> - * getAttendanceWithInitiatedSalaryByGroupId( - * - * @RequestParam(value = "inchargeId", required = false) String inchargeId, - * - * @RequestParam(value = "month", required = false) String month, - * - * @RequestParam(value = "inchargeName", required = false) String inchargeName, - * - * @RequestParam(value = "zone", required = false) Integer zone) { - * - * List> staffList = - * nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, inchargeName, - * zone); - * return ResponseEntity.ok(staffList); - * } - */ - - @GetMapping("/staffInititeadList") - public ResponseEntity>> getAttendanceWithInitiatedSalaryByGroupId( - @RequestParam(value = "inchargeId", required = false) Integer inchargeId, - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "year", required = false) String year, - @RequestParam(value = "inchargeName", required = false) String inchargeName, - @RequestParam(value = "enrollmentIds", required = false) List enrollmentIds) { - - System.out.println("inchargeName=" + inchargeName); - - List> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, year, - inchargeName, enrollmentIds); - return ResponseEntity.ok(staffList); - } - - ///// - - @GetMapping("/staffInititeadList-park") - public ResponseEntity>> getAttendanceWithInitiatedSalaryByGroupId_Park( - @RequestParam(value = "inchargeId", required = false) Integer inchargeId, - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "year", required = false) String year, - @RequestParam(value = "inchargeName", required = false) String inchargeName, - @RequestParam(value = "enrollmentIds", required = false) List enrollmentIds) { - - List> staffList = nulmService.getAttendanceWithInitiatedSalary_Park(inchargeId, month, year, - inchargeName, enrollmentIds); - return ResponseEntity.ok(staffList); - } - - ///// - /* - * @PostMapping("/salaryDetailUpdate") - * public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { - * System.out.println("Received POST request with data: " + requestList); - * try { - * for (Map request : requestList) { - * int totalDaysPresent = - * Integer.parseInt(request.get("total_days_present").toString()); - * int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); - * int totalDaysSalary = - * Integer.parseInt(request.get("total_days_salary").toString()); - * int totalDaysAbsent = - * Integer.parseInt(request.get("total_days_absent").toString()); - * String month = request.get("month").toString(); - * int year = Integer.parseInt(request.get("year").toString()); - * int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); - * int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); - * int groupId = Integer.parseInt(request.get("group_id").toString()); - * int wageId = Integer.parseInt(request.get("wage_id").toString()); - * - * // Check if the month and year are valid for salary initiation (past month) - * if (isFutureOrCurrentMonth(month, year)) { - * return ResponseEntity.status(HttpStatus.BAD_REQUEST) - * .body("Salary cannot be initiated for the current or future months. Please select a past month." - * ); - * } - * - * String salaryStatus = "Initiated"; - * - * // Call the service method to insert the salary details - * int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, - * totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, - * salaryStatus, enrollmentId, groupId, wageId); - * - * if (rowsAffected <= 0) { - * return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - * .body("Failed to add salary details for enrollment ID: " + enrollmentId); - * } - * } - * return ResponseEntity.status(HttpStatus.CREATED) - * .body("Salary details added successfully for all selected entries."); - * } catch (Exception e) { - * e.printStackTrace(); // Log the exception for debugging - * return ResponseEntity.status(HttpStatus.BAD_REQUEST) - * .body("Invalid request data: " + e.getMessage()); - * } - * } - */ - @PostMapping("/salaryDetailUpdate") - public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { - System.out.println("Received POST request with data: " + requestList); - try { - for (Map request : requestList) { - System.out.println("enrollment_id = " + request.get("enrollment_id").toString()); - int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); - int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); - int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); - int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); - String month = request.get("month").toString(); - int year = Integer.parseInt(request.get("year").toString()); - int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); - int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); - int groupId = Integer.parseInt(request.get("group_id").toString()); - int wageId = Integer.parseInt(request.get("wage_id").toString()); - int inchargeID = 0;// Integer.parseInt(""+request.get("incharge_id")); - - // Check if the month and year are valid for salary initiation (past month) - if (isFutureOrCurrentMonth(month, year)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Salary cannot be initiated for the current or future months. Please select a past month."); - } - - String salaryStatus = "Initiated"; - - boolean checkexist = nulmService.checkSalaryDetails(enrollmentId, month, year); - - System.out.println("checkexist: " + checkexist); - - if (!checkexist) { - // Call the service method to insert the salary details - int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, - totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, - inchargeID); - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to add salary details for enrollment ID: " + enrollmentId); - } - } else { - int rowsAffected = nulmService.updateSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, - totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, - inchargeID); - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to update salary details for enrollment ID: " + enrollmentId); - } - } - } - return ResponseEntity.status(HttpStatus.CREATED) - .body("Salary details added successfully for all selected entries."); - } catch (Exception e) { - e.printStackTrace(); // Log the exception for debugging - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Invalid request data: " + e.getMessage()); - } - } - - /// - - @PostMapping("/salaryDetailUpdate_Park") - public ResponseEntity addSalaryDetails_Park(@RequestBody List> requestList) { - System.out.println("Received POST request with data: " + requestList); - try { - for (Map request : requestList) { - - System.out.println("enrollment_id = " + request.get("enrollment_id").toString()); - int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); - int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); - int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); - int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); - String month = request.get("month").toString(); - int year = Integer.parseInt(request.get("year").toString()); - int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); - int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); - int groupId = Integer.parseInt(request.get("group_id").toString()); - int wageId = Integer.parseInt(request.get("wage_id").toString()); - int inchargeID = 0;// Integer.parseInt(""+request.get("incharge_id")); - - // Check if the month and year are valid for salary initiation (past month) - if (isFutureOrCurrentMonth(month, year)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Salary cannot be initiated for the current or future months. Please select a past month."); - } - - String salaryStatus = "Initiated"; - - boolean checkexist = nulmService.checkSalaryDetails_park(enrollmentId, month, year); - - System.out.println("checkexist: " + checkexist); - - if (!checkexist) { - // Call the service method to insert the salary details - int rowsAffected = nulmService.addSalaryDetails_park(totalDaysPresent, totalDaysOd, totalDaysSalary, - totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, - inchargeID); - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to add salary details for enrollment ID: " + enrollmentId); - } - } else { - int rowsAffected = nulmService.updateSalaryDetails_park(totalDaysPresent, totalDaysOd, - totalDaysSalary, - totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, - inchargeID); - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to update salary details for enrollment ID: " + enrollmentId); - } - } - } - return ResponseEntity.status(HttpStatus.CREATED) - .body("Salary details added successfully for all selected entries."); - } catch (Exception e) { - e.printStackTrace(); // Log the exception for debugging - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Invalid request data: " + e.getMessage()); - } - } - - /// - - // Helper method to check if the month is future or current - private boolean isFutureOrCurrentMonth(String month, int year) { - // Get the current month and year - LocalDate currentDate = LocalDate.now(); - Month currentMonth = currentDate.getMonth(); - int currentYear = currentDate.getYear(); - - // Convert the string month from the request to Month enum - Month requestMonth = Month.valueOf(month.toUpperCase()); // Ensure that month is passed in capitalized format - // like "JANUARY", "FEBRUARY", etc. - - // Compare the request month and year with the current date - if (year > currentYear) { - return true; // Future year - } else if (year == currentYear && requestMonth.compareTo(currentMonth) >= 0) { - return true; // Current or future month in the current year - } - return false; // Past month - } - - // @PostMapping("/salaryDetailUpdate") - // public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { - // System.out.println("Received POST request with data: " + requestList); - // try { - // for (Map request : requestList) { - // int totalDaysPresent = - // Integer.parseInt(request.get("total_days_present").toString()); - // int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); - // int totalDaysSalary = - // Integer.parseInt(request.get("total_days_salary").toString()); - // int totalDaysAbsent = - // Integer.parseInt(request.get("total_days_absent").toString()); - // String month = request.get("month").toString(); - // int year = Integer.parseInt(request.get("year").toString()); - // int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); - // int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); - // int groupId = Integer.parseInt(request.get("group_id").toString()); - // int wageId = Integer.parseInt(request.get("wage_id").toString()); - // - // String salaryStatus = "Initiated"; - // - // // Call the service method to insert the salary details - // int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, - // totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, - // salaryStatus, enrollmentId, groupId, wageId); - // - // if (rowsAffected <= 0) { - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed - // to add salary details for enrollment ID: " + enrollmentId); - // } - // } - // return ResponseEntity.status(HttpStatus.CREATED).body("Salary details added - // successfully for all selected entries."); - // } catch (Exception e) { - // e.printStackTrace(); // Log the exception for debugging - // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request - // data: " + e.getMessage()); - // } - // } - - @PostMapping("/update-salary-status") - public ResponseEntity updateSalaryStatus( - @RequestParam List enrollmentIds, - @RequestParam String month, - @RequestParam int year) { - System.out.println("Enrollment IDs: " + enrollmentIds); - System.out.println("Month: " + month); - System.out.println("Year: " + year); - nulmService.updateSalaryStatusToApproved(enrollmentIds, month, year); - return ResponseEntity.ok("Salary status updated to 'Approved' for the provided enrollments."); - } - - //// - - @GetMapping("/salary-approve-park-testdata") - public List> getsalaryInitiatedCounts(@RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, - @RequestParam(required = false) String LoginUserId) { - - List> salaryInitiatedCounts; - - // Fetch data if both month and year are provided, otherwise return an empty - // list - if (month != null && year != null) { - salaryInitiatedCounts = nulmService.getFilteredSalaryDetails_park(month, year, salaryStatus, LoginUserId); // Pass - // department - // to - // the - // service - // method - } else { - salaryInitiatedCounts = Collections.emptyList(); // Empty list if no month and year are provided - } - return salaryInitiatedCounts; - } - - @PostMapping("/update-salary-status-park") - public ResponseEntity updateSalaryStatus_Park( - @RequestParam List enrollmentIds, - @RequestParam String month, - @RequestParam int year) { - System.out.println("Enrollment IDs: " + enrollmentIds); - System.out.println("Month: " + month); - System.out.println("Year: " + year); - nulmService.updateSalaryStatusToApproved_Park(enrollmentIds, month, year); - return ResponseEntity.ok("Salary status updated to 'Approved' for the provided enrollments."); - } - - //// - - /*************** API For Mobile Application *********************************/ - /* - * @GetMapping("/attendanceWithSalary") - * public ResponseEntity>> - * getAttendanceWithSalaryByInchargeId( - * - * @RequestParam(value = "month", required = false) String month, - * - * @RequestParam(value = "year", required = false) Integer year, - * - * @RequestParam(value = "incharge_id", required = false) Integer inchargeId) { - * - * try { - * // Call the service method to fetch the data - * List> attendanceWithSalary = - * nulmService.getAttendanceWithSalaryByInchargeId(month, year, inchargeId); - * - * // If no data is found, return a NOT FOUND response - * if (attendanceWithSalary.isEmpty()) { - * return ResponseEntity.status(404).body(List.of(Map.of("error", - * "No attendance records found for the specified parameters."))); - * } - * - * // Return the data in the response - * return ResponseEntity.ok(attendanceWithSalary); - * } catch (Exception ex) { - * // Return a 500 Internal Server Error with the error message - * return ResponseEntity.status(500).body(List.of(Map.of("error", - * "An error occurred while fetching attendance data: " + ex.getMessage()))); - * } - * } - */ - - @GetMapping("/attendanceWithSalary") - public ResponseEntity>> getAttendanceWithSalaryByInchargeId( - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "year", required = false) Integer year, - @RequestParam(value = "incharge_id", required = false) Integer inchargeId) { - - try { - - // List> attendanceWithSalary = new ArrayList<>(); - // Integer check = nulmService.checkInchargeID(inchargeId); - // if (check == 1) { - // Call the service method to fetch the data - List> attendanceWithSalary = nulmService.getAttendanceWithSalaryByInchargeId(month, - year, inchargeId); - // } - // If no data is found, return a NOT FOUND response total_days_salary, - // total_salary and total_days_absent - if (attendanceWithSalary.isEmpty()) { - return ResponseEntity.status(404) - .body(List.of(Map.of("error", "No attendance records found for the specified parameters."))); - } - - for (Map aa : attendanceWithSalary) { - long days = ((Number) aa.get("total_days")).longValue(); - long present = ((Number) aa.get("total_days_present")).longValue(); - long od = ((Number) aa.get("total_days_od")).longValue(); - long salaryPerDay = ((Number) aa.get("salary_per_day")).longValue(); - - long totalPresent = present + od; - long totalAbsent = days - totalPresent; - long totalSalary = totalPresent * salaryPerDay; - - aa.put("total_salary", totalSalary); - aa.put("total_days_absent", totalAbsent); - aa.put("total_days_salary", totalPresent); - } - - // Return the data in the response - return ResponseEntity.ok(attendanceWithSalary); - } catch (Exception ex) { - // Return a 500 Internal Server Error with the error message - return ResponseEntity.status(500).body( - List.of(Map.of("error", "An error occurred while fetching attendance data: " + ex.getMessage()))); - } - } - - //// - - @GetMapping("/attendanceWithSalary_New") - public ResponseEntity>> getAttendanceWithSalaryByInchargeId_New( - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "year", required = false) Integer year, - @RequestParam(value = "incharge_id", required = false) Integer inchargeId, - @RequestParam(value = "type", required = false) String type) { - - try { - - List> attendanceWithSalary = new ArrayList<>(); - String ids = nulmService.checkInchargeID(inchargeId); - System.out.println("IDS = " + ids); - if (ids != null || !ids.trim().isEmpty()) { - // Call the service method to fetch the data - attendanceWithSalary = nulmService.getAttendanceWithSalaryByInchargeId_New(month, year, inchargeId, - type, ids); - } - // If no data is found, return a NOT FOUND response total_days_salary, - // total_salary and total_days_absent - if (attendanceWithSalary.isEmpty()) { - return ResponseEntity.status(404) - .body(List.of(Map.of("error", "No attendance records found for the specified parameters."))); - } - - for (Map aa : attendanceWithSalary) { - long days = ((Number) aa.get("total_days")).longValue(); - long present = ((Number) aa.get("total_days_present")).longValue(); - long od = ((Number) aa.get("total_days_od")).longValue(); - long salaryPerDay = ((Number) aa.get("salary_per_day")).longValue(); - - long totalPresent = present + od; - long totalAbsent = days - totalPresent; - long totalSalary = totalPresent * salaryPerDay; - - aa.put("total_salary", totalSalary); - aa.put("total_days_absent", totalAbsent); - aa.put("total_days_salary", totalPresent); - } - - // Return the data in the response - return ResponseEntity.ok(attendanceWithSalary); - } catch (Exception ex) { - // Return a 500 Internal Server Error with the error message - return ResponseEntity.status(500).body( - List.of(Map.of("error", "An error occurred while fetching attendance data: " + ex.getMessage()))); - } - } - - //// - - @PostMapping("/salaryDetailInitiate") - public ResponseEntity addInitiatedSalaryDetails( - @RequestParam("total_days_present") List totalDaysPresentList, - @RequestParam("total_days_od") List totalDaysOdList, - @RequestParam("total_days_salary") List totalDaysSalaryList, - @RequestParam("total_days_absent") List totalDaysAbsentList, - @RequestParam("month") List monthList, - @RequestParam("year") List yearList, - @RequestParam("salary_amount") List salaryAmountList, - @RequestParam("enrollment_id") List enrollmentIdList, - @RequestParam("group_id") List groupIdList, - @RequestParam("wage_id") List wageIdList) { - // System.out.println("Received POST request with form-data"); - - try { - // Iterate through each list to process the form data - for (int i = 0; i < totalDaysPresentList.size(); i++) { - int totalDaysPresent = totalDaysPresentList.get(i); - int totalDaysOd = totalDaysOdList.get(i); - int total_days_salary = totalDaysSalaryList.get(i); - int totalDaysAbsent = totalDaysAbsentList.get(i); - String month = monthList.get(i); - int year = yearList.get(i); - int salaryAmount = salaryAmountList.get(i); - int enrollmentId = enrollmentIdList.get(i); - int groupId = groupIdList.get(i); - int wageId = wageIdList.get(i); - - String salaryStatus = "Initiated"; - - // Call the service method to insert the salary details - int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, total_days_salary, - totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId); - - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to add salary details for enrollment ID: " + enrollmentId); - } - } - return ResponseEntity.status(HttpStatus.CREATED) - .body("Salary details added successfully for all selected entries."); - } catch (Exception e) { - e.printStackTrace(); // Log the exception for debugging - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request data: " + e.getMessage()); - } - } - - //// - - // @PostMapping("/salaryDetailInitiate_park") - // public ResponseEntity addInitiatedSalaryDetails_park( - // @RequestParam("total_days_present") List totalDaysPresentList, - // @RequestParam("total_days_od") List totalDaysOdList, - // @RequestParam("total_days_salary") List totalDaysSalaryList, - // @RequestParam("total_days_absent") List totalDaysAbsentList, - // @RequestParam("month") List monthList, - // @RequestParam("year") List yearList, - // @RequestParam("salary_amount") List salaryAmountList, - // @RequestParam("enrollment_id") List enrollmentIdList, - // @RequestParam("group_id") List groupIdList, - // @RequestParam("wage_id") List wageIdList) { - // // System.out.println("Received POST request with form-data"); - // - // try { - // // Iterate through each list to process the form data - // for (int i = 0; i < totalDaysPresentList.size(); i++) { - // int totalDaysPresent = totalDaysPresentList.get(i); - // int totalDaysOd = totalDaysOdList.get(i); - // int total_days_salary = totalDaysSalaryList.get(i); - // int totalDaysAbsent = totalDaysAbsentList.get(i); - // String month = monthList.get(i); - // int year = yearList.get(i); - // int salaryAmount = salaryAmountList.get(i); - // int enrollmentId = enrollmentIdList.get(i); - // int groupId = groupIdList.get(i); - // int wageId = wageIdList.get(i); - // - // String salaryStatus = "Initiated"; - // - // // Call the service method to insert the salary details - // int rowsAffected = nulmService.addSalaryDetails_park(totalDaysPresent, - // totalDaysOd, total_days_salary, - // totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, - // groupId, wageId); - // - // if (rowsAffected <= 0) { - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body("Failed to add salary details for enrollment ID: " + enrollmentId); - // } - // } - // return ResponseEntity.status(HttpStatus.CREATED) - // .body("Salary details added successfully for all selected entries in park."); - // } catch (Exception e) { - // e.printStackTrace(); // Log the exception for debugging - // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request - // data: " + e.getMessage()); - // } - // } - - //// - - // @GetMapping("/filtered-details") - // public List> getFilteredSalaryDetails( - // @RequestParam(required = false) String month, - // @RequestParam(required = false) Integer year, - // @RequestParam(required = false) String salaryStatus) { - // - // // Call the service method to get the filtered salary details - // return nulmService.getFilteredSalaryDetails(month, year, salaryStatus); - // } - - // ak - // 1. Get Zones - @GetMapping("/zones") - public List getZones() { - return nulmService.getZones(); - } - - // 2. Get Divisions by Zone - @GetMapping("/divisions") - public List getDivisions(@RequestParam int zone) { - return nulmService.getDivisions(zone); - } - - // 3. Get Parks by Zone and Division - @GetMapping("/list") - public List> getParks( - @RequestParam int zone, - // @RequestParam int division) { - @RequestParam(required = false) Integer division) { - - return nulmService.getParks(zone, division); - } - - @GetMapping("/staff") - public List> getStaffByPark(@RequestParam int parkId) { - return nulmService.getStaffByPark(parkId); - } - - @GetMapping("/staff-details") - public Map getStaffDetails(@RequestParam int enrollmentId) { - - return nulmService.getStaffDetails(enrollmentId); - - } - - @PostMapping("/update-staff") - public ResponseEntity updateStaff( - @RequestParam int enrollmentId, - @RequestParam(required = false) String fhName, - @RequestParam(required = false) String designation, - @RequestParam(required = false) Integer designationId, - @RequestParam(required = false) String aadharNo, - @RequestParam(required = false) String bankAccNo, - @RequestParam(required = false) String phoneNumber, - @RequestParam(required = false) String address, - // ak - @RequestParam(required = false) String bankName, - @RequestParam(required = false) String ifscCode, - @RequestParam(required = false) String branch, - @RequestParam(required = false) String branchAddress, - - @RequestParam(required = false) Integer notFound, - @RequestParam(required = false) Integer error, - @RequestParam(required = false) String remarks, - @RequestParam(required = false) MultipartFile uploadform, - @RequestParam(required = false) MultipartFile aadharcard, - @RequestParam(required = false) MultipartFile bankpassbook, @RequestParam String createdBy) { - - return ResponseEntity.ok(nulmService.updateStaff( - enrollmentId, fhName, designation, designationId, - aadharNo, bankAccNo, bankName, ifscCode, branch, branchAddress, phoneNumber, address, - uploadform, aadharcard, bankpassbook, notFound, error, remarks, createdBy)); - } - - @GetMapping("/designations") - @ResponseBody - public List> getDesignations() { - return nulmService.getDesignations(); - } - - /* - * @GetMapping("/parks") - * - * @ResponseBody - * public List> getParks() { - * return nulmService.getParks(); - * } - */ - @GetMapping("/parks") - public List> getParks(@RequestParam int zone) { - return nulmService.getParks(zone); - } - - @PostMapping("/create-employee") - @ResponseBody - public Map createEmployee( - - @RequestParam String name, - @RequestParam String fhName, - @RequestParam String designation, - @RequestParam Integer designationId, - @RequestParam String aadharNo, - @RequestParam String bankAccNo, - @RequestParam String phoneNumber, - @RequestParam String address, - - @RequestParam String bankName, - @RequestParam String ifscCode, - @RequestParam String branch, - @RequestParam String branchAddress, - - @RequestParam Integer parkId, - @RequestParam String parkName, - @RequestParam Integer inchargeId, - @RequestParam String inchargeName, - @RequestParam Integer zone, - @RequestParam String inchargeDesignation, - @RequestParam String inchargePhone, - - @RequestParam(required = false) MultipartFile uploadform, - @RequestParam(required = false) MultipartFile aadharcard, - @RequestParam(required = false) MultipartFile bankpassbook) { - - return nulmService.createEmployee( - name, fhName, designation, designationId, aadharNo, - bankAccNo, phoneNumber, address, - bankName, ifscCode, branch, branchAddress, - parkId, parkName, inchargeId, inchargeName, zone, inchargeDesignation, inchargePhone, - uploadform, aadharcard, bankpassbook); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmController.java deleted file mode 100644 index 79368476..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmController.java +++ /dev/null @@ -1,534 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import in.gov.chennaicorporation.gccoffice.nulm.service.NulmService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@Controller -@RequestMapping("/gcc/nulm") -public class NulmController { - - @Autowired - private NulmService nulmService; - - @GetMapping("/appointment") - public String viewappoinmentMaster(Model model) { - System.out.println("appointment"); - return "modules/nulm/appointment"; - } - - @GetMapping("/self-enrollment") - public String viewselfenrollment(Model model) { - System.out.println("self-enrollment"); - return "modules/nulm/staff-enrollment"; - } - - @GetMapping("/create-order") - public String viewcreateorder(Model model) { - System.out.println("create-order"); - return "modules/nulm/create-order"; - } - - @GetMapping("/scheme-group") - public String viewschemegroup(Model model) { - System.out.println("scheme-group"); - return "modules/nulm/scheme-group"; - } - - @GetMapping("/dropout") - public String viewappointmentscreengroup(Model model) { - System.out.println("dropout"); - return "modules/nulm/dropout"; - } - - @GetMapping("/updateStaff") - public String viewUpdateScreen( - @RequestParam(value = "department", required = false) String department, - @RequestParam(value = "division", required = false) String division, - Model model) { - - // Fetch the full list or filtered list based on parameters - List> enrollments = nulmService.getEnrollments(department, null); - - // Add the list to the model to be accessed in the view - model.addAttribute("enrollments", enrollments); - model.addAttribute("selectedDepartment", department); // Pass the selected department - - // Return the view name - return "modules/nulm/updated-staff"; - } - - /// - - @GetMapping("/updateStaffPark") - public String viewUpdateScreenPark( - @RequestParam(value = "department", required = false) String department, - @RequestParam(value = "division", required = false) String division, - Model model) { - - // Fetch the full list or filtered list based on parameters - List> enrollments = nulmService.getEnrollmentsForPark(department, null); - - // Add the list to the model to be accessed in the view - model.addAttribute("enrollments", enrollments); - model.addAttribute("selectedDepartment", department); // Pass the selected department - - // Return the view name - return "modules/nulm/updated-staff-park"; - } - - /// - - @GetMapping("/salaryDetails") - public String getSalaryDetails( - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "year", required = false) Integer year, // Use Integer instead of int - Model model) { - - List> salaryDetails = new ArrayList<>(); - - // Check if month and year are provided - if (month != null && year != null) { - salaryDetails = nulmService.getAttendanceWithSalary(month, year); - } else { - // Handle case when no month or year is provided - model.addAttribute("message", "Please select a month and year."); - } - - model.addAttribute("salaryCounts", salaryDetails); - System.out.println("salarydetails for month: " + month + ", year: " + year); - return "modules/nulm/salary-details"; - } - - /* - * @GetMapping("/salary-approve") - * public String viewSalaryApproveScreen(@RequestParam(required = false) String - * month, - * - * @RequestParam(required = false) Integer year, - * - * @RequestParam(required = false) String salaryStatus, - * Model model) { - * List> salaryInitiatedCounts; - * - * // If both month and year are provided, fetch the data; otherwise, return an - * empty list - * if (month != null && year != null) { - * salaryInitiatedCounts = nulmService.getFilteredSalaryDetails(month, year, - * salaryStatus); - * } else { - * salaryInitiatedCounts = Collections.emptyList(); // Empty list if no month - * and year are provided - * } - * - * model.addAttribute("salaryInitiatedCounts", salaryInitiatedCounts); - * return "modules/nulm/salary-approve"; - * } - */ - @GetMapping("/salary-approve") - public String viewSalaryApproveScreen(@RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, // Added department parameter - Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - System.out.println("LoginUserId==" + LoginUserId); - - List> salaryInitiatedCounts; - - // Fetch data if both month and year are provided, otherwise return an empty - // list - if (month != null && year != null) { - salaryInitiatedCounts = nulmService.getFilteredSalaryDetails(month, year, salaryStatus, LoginUserId); // Pass - // department - // to - // the - // service - // method - } else { - salaryInitiatedCounts = Collections.emptyList(); // Empty list if no month and year are provided - } - - model.addAttribute("salaryInitiatedCounts", salaryInitiatedCounts); - - return "modules/nulm/salary-approve"; - } - - //// - - @GetMapping("/salary-approve-park") - public String viewSalaryApproveScreen_park(@RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, // Added department parameter - Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - List> salaryInitiatedCounts; - - // Fetch data if both month and year are provided, otherwise return an empty - // list - if (month != null && year != null) { - salaryInitiatedCounts = nulmService.getFilteredSalaryDetails_park(month, year, salaryStatus, LoginUserId); // Pass - // department - // to - // the - // service - // method - } else { - salaryInitiatedCounts = Collections.emptyList(); // Empty list if no month and year are provided - } - - model.addAttribute("salaryInitiatedCounts", salaryInitiatedCounts); - - return "modules/nulm/salary-approve-park"; - } - - //// - - @GetMapping("/salary-report") - public String viewSalaryReport( - @RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, - @RequestParam(required = false) String groupName, - Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - // Initialize an empty salaryReport list - List> salaryReport = new ArrayList<>(); - - // Only fetch the report if month and year are provided - if (month != null && year != null) { - salaryReport = nulmService.getSalaryReport(month, year, salaryStatus, groupName, LoginUserId); - } - - // Add the fetched data to the model - model.addAttribute("salaryReport", salaryReport); - - return "modules/nulm/salary-report"; // Returns the view 'salary-report' - } - - //// - - @GetMapping("/salary-report-park") - public String viewSalaryReport_Park( - @RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, - @RequestParam(required = false) String groupName, - Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - // Initialize an empty salaryReport list - List> salaryReport = new ArrayList<>(); - - // Only fetch the report if month and year are provided - if (month != null && year != null) { - salaryReport = nulmService.getSalaryReport_park(month, year, salaryStatus, groupName, LoginUserId); - } - - // Add the fetched data to the model - model.addAttribute("salaryReport", salaryReport); - - return "modules/nulm/salary-report-park"; // Returns the view 'salary-report' - } - - //// - - @GetMapping("/salary-zonereport") - public String viewZoneWiseReport( - @RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, - @RequestParam(required = false) String groupName, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String division, - Model model) { - // System.out.println("Zone: "+zone); - - // Initialize an empty salaryReport list - List> zoneWiseReport = new ArrayList<>(); - - // Only fetch the report if month, year and zone are provided - if (month != null && year != null && zone != null) { - zoneWiseReport = nulmService.getZoneWiseReport(month, year, salaryStatus, groupName, zone, division); - } - - // Add the fetched data to the model - model.addAttribute("zonewiseReport", zoneWiseReport); - - return "modules/nulm/zone-wise-report"; // Returns the view 'salary-zonereport' - } - - /// - - @GetMapping("/salary-zonereport-park") - public String viewParkZoneWiseReport( - @RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String salaryStatus, - @RequestParam(required = false) String groupName, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String division, - Model model) { - // System.out.println("Zone: "+zone); - - // Initialize an empty salaryReport list - List> zoneWiseReport = new ArrayList<>(); - - // Only fetch the report if month, year and zone are provided - if (month != null && year != null && zone != null) { - zoneWiseReport = nulmService.getZoneWiseReportPark(month, year, salaryStatus, groupName, zone, division); - } - - // Add the fetched data to the model - model.addAttribute("zonewiseReport", zoneWiseReport); - - return "modules/nulm/zone-wise-report-park"; // Returns the view 'salary-zonereport' - } - - /// - - @GetMapping("/attendance-report") - public String viewAttendanceReport( - @RequestParam(required = false) String fromdate, - @RequestParam(required = false) String todate, - @RequestParam(required = false) String groupName, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String division, - Model model) { - - // Initialize an empty salaryReport list - List> attendanceReport = new ArrayList<>(); - - // Only fetch the report if month, year and zone are provided - if (division != null && zone != null) { - attendanceReport = nulmService.getAttendanceReport(fromdate, todate, groupName, zone, division); - } - - // Add the fetched data to the model - model.addAttribute("attendanceReport", attendanceReport); - - return "modules/nulm/attendance-report"; - } - - @GetMapping("/consolidated-attendance-report") // need to add - public String viewConsolidatedAttendanceReport( - @RequestParam(required = false) String fromdate, - @RequestParam(required = false) String todate, - @RequestParam(required = false) String groupName, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String division, - Model model) { - - // Initialize an empty salaryReport list - List> consolidatedAttendanceReport = new ArrayList<>(); - - // Only fetch the report if month, year and zone are provided - if (division != null && zone != null) { - consolidatedAttendanceReport = nulmService.getConsolidatedAttendanceReport(fromdate, todate, groupName, - zone, division); - } - - // Add the fetched data to the model - model.addAttribute("consolidatedAttendanceReport", consolidatedAttendanceReport); - model.addAttribute("fromdate", fromdate); - model.addAttribute("todate", todate); - - return "modules/nulm/attendance-report"; - } - - /// - - @GetMapping("/consolidated-attendance-report-park") // need to add - public String viewParkConsolidatedAttendanceReport( - @RequestParam(required = false) String fromdate, - @RequestParam(required = false) String todate, - @RequestParam(required = false) String groupName, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String division, - Model model) { - - // Initialize an empty salaryReport list - List> consolidatedAttendanceReport = new ArrayList<>(); - - // Only fetch the report if month, year and zone are provided - if (division != null && zone != null) { - consolidatedAttendanceReport = nulmService.getParkConsolidatedAttendanceReport(fromdate, todate, groupName, - zone, division); - } - - // Add the fetched data to the model - model.addAttribute("consolidatedAttendanceReport", consolidatedAttendanceReport); - model.addAttribute("fromdate", fromdate); - model.addAttribute("todate", todate); - - return "modules/nulm/attendance-report-park"; - } - - /// - - - @GetMapping("/attendance-dates") // need to add - @ResponseBody - public ResponseEntity>> getAttendanceDates( - @RequestParam(required = false) String enrollmentId, - @RequestParam(required = false) String fromdate, - @RequestParam(required = false) String todate, - @RequestParam(required = false) String type, - Model model) { - - return ResponseEntity.ok(nulmService.fetchAttendanceDates(enrollmentId, fromdate, todate, type)); - - } - - /// - - @GetMapping("/self-help-group") // need to add - public String viewSelfHelpGroup(Model model) { - - // Fetch the full list or filtered list based on parameters - List> selfHelpGroup = nulmService.getSelfHelpGroupDetails(); - - // Add the list to the model to be accessed in the view - model.addAttribute("selfHelpGroup", selfHelpGroup); - - // Return the view name - return "modules/nulm/selfHelpGroup"; - } - - @GetMapping("/salary-nonInitiated") - public String viewSalaryNotInitiatedReport( - @RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String groupName, - Model model) { - System.out.println(" salary-nonInitiated groupname====" + groupName); - if (groupName != null && !groupName.isEmpty()) { - groupName = URLDecoder.decode(groupName, StandardCharsets.UTF_8); - } - - List> salaryNotInitiatedReport = new ArrayList<>(); - - if (month != null && year != null) { - salaryNotInitiatedReport = nulmService.getSalaryNotInitiatedReport(month, year, groupName); - } - - model.addAttribute("salaryNonInitiatedReport", salaryNotInitiatedReport); - - return "modules/nulm/salary-nonInitiatedreport"; - } - - /// - - @GetMapping("/salary-nonInitiated-park") - public String viewParkSalaryNotInitiatedReport( - @RequestParam(required = false) String month, - @RequestParam(required = false) Integer year, - @RequestParam(required = false) String groupName, - Model model) { - System.out.println(" salary-nonInitiated groupname====" + groupName); - if (groupName != null && !groupName.isEmpty()) { - groupName = URLDecoder.decode(groupName, StandardCharsets.UTF_8); - } - - List> salaryNotInitiatedReport = new ArrayList<>(); - - if (month != null && year != null) { - salaryNotInitiatedReport = nulmService.getSalaryNotInitiatedReportPark(month, year, groupName); - } - - model.addAttribute("salaryNonInitiatedReport", salaryNotInitiatedReport); - - return "modules/nulm/salary-nonInitiatedreport-park"; - } - - /// - - - @GetMapping("/staffupdate") - public String staffupdate(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - System.out.println("===" + LoginUserId); - model.addAttribute("LoginUserId", LoginUserId); - - boolean hasAccess = nulmService.hasStaffUpdateAccess(LoginUserId); - - if (hasAccess) { - - model.addAttribute("LoginUserId", LoginUserId); - return "modules/nulm/staffupdate"; - - } else { - - return "modules/nulm/staffupdatenoacess"; - } - } - - @GetMapping("/addstaff") - public String addstaff(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - System.out.println("===" + LoginUserId); - model.addAttribute("LoginUserId", LoginUserId); - - boolean hasAccess = nulmService.hasStaffUpdateAccess(LoginUserId); - - if (hasAccess) { - - model.addAttribute("LoginUserId", LoginUserId); - return "modules/nulm/addstaff"; - - } else { - - return "modules/nulm/staffupdatenoacess"; - } - } - - /* - * @GetMapping("/staffreport") - * public String staffreport(Model model) { - * - * String LoginUserId = LoginUserInfo.getLoginUserId(); - * System.out.println("===" + LoginUserId); - * // model.addAttribute("LoginUserId", LoginUserId); - * - * boolean hasAccess = nulmService.hasStaffUpdateAccess(LoginUserId); - * - * if (hasAccess) { - * - * model.addAttribute("LoginUserId", LoginUserId); - * return "modules/nulm/staffreport"; - * - * } else { - * - * return "modules/nulm/staffupdatenoacess"; - * } - * } - */ - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/package-info.java deleted file mode 100644 index ed06c393..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/repository/NulmRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/repository/NulmRepository.java deleted file mode 100644 index 556bc0fb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/repository/NulmRepository.java +++ /dev/null @@ -1,279 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.repository; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Repository; - -@Repository -public class NulmRepository { - - @Autowired - private JdbcTemplate nulmJdbcTemplate; - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public NulmRepository(JdbcTemplate nulmJdbcTemplate,JdbcTemplate jdbcTemplate) { - this.nulmJdbcTemplate = nulmJdbcTemplate; - this.jdbcTemplate = jdbcTemplate; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlNulmDataSource") DataSource dataSource) { - this.nulmJdbcTemplate = new JdbcTemplate(dataSource); - } - -/////////////////////////// Order Repository /////////////////////////////// -public void saveOrderDetails(Map orderData) { -String sql = "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, created_date, validity_date, order_status, isactive, isdelete) " + - "VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, " + - "CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)"; -nulmJdbcTemplate.update(sql, - orderData.get("orderNumber"), - orderData.get("orderDate"), - orderData.get("noOfStaffs"), - orderData.get("orderDescription"), - orderData.get("orderCopyUrl"), - orderData.get("orderGeneratedBy"), - orderData.get("validityDate"), - orderData.get("validityDate"), - orderData.get("orderDate")); -} - -/////To get all the list of orders///////////////////////////////// -public List> getAllOrders() { - String sql = "SELECT od.*, " + - "SUM(CASE WHEN ed.appointed = '1' THEN 1 ELSE 0 END) AS appointed_yes_count " + - "FROM order_details od " + - "LEFT JOIN enrollment_table ed ON od.order_id = ed.order_id " + - "GROUP BY od.order_id, od.order_number, od.order_date, od.order_generated_by, od.order_description, od.no_of_staffs, od.category, od.validity_date, od.order_copy_url"; - - // Fetch the list of orders with the appointed counts - List> orderLists = nulmJdbcTemplate.queryForList(sql); - - // Add the calculated value (appointed_yes_count - no_of_staffs) to each order map - for (Map order : orderLists) { - int appointedYesCount = ((Number) order.get("appointed_yes_count")).intValue(); - int noOfStaffs = ((Number) order.get("no_of_staffs")).intValue(); - - // Calculate the output value - int outputValue = noOfStaffs-appointedYesCount; - - // Add the output value to the order map - order.put("output_value", outputValue); - } - - return orderLists; -} -//public List> getAllOrders() { -// String sql = "SELECT od.*, " + -// "SUM(CASE WHEN ed.appointed = 'Yes' THEN 1 ELSE 0 END) AS appointed_yes_count, " + -// "SUM(CASE WHEN ed.appointed = 'No' THEN 1 ELSE 0 END) AS appointed_no_count " + -// "FROM order_details od " + -// "LEFT JOIN enrollment_table ed ON od.order_id = ed.order_id " + -// "GROUP BY od.order_id, od.order_number, od.order_date, od.order_generated_by, od.order_description, od.no_of_staffs, od.validity_date"; -// -// List> orderLists = nulmJdbcTemplate.queryForList(sql); -// return orderLists; -//} - -public List> getAllOrderDetails() { - String sql = "SELECT order_id, order_number FROM order_details"; - - // Use queryForList to fetch the data - return nulmJdbcTemplate.queryForList(sql); -} - -public List getAllOrderNumber() { - String sql = "SELECT order_number FROM order_details"; - - // Use query with a RowMapper to map each row to a String - return nulmJdbcTemplate.query(sql, new RowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getString("order_number"); - } - }); -} - - -/////////////////////////// Scheme Group Repository /////////////////////////////// -public void saveSchemeGroup(Map groupData) { -String sql = "INSERT INTO suyaudavi_kuzhu (group_name, incharge_name, incharge_phoneno, bank_name, bank_branch, ifsc_code, bank_accountno, created_date, isactive, isdelete) " + -"VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 1, 0)"; -nulmJdbcTemplate.update(sql, - groupData.get("groupName"), - groupData.get("inchargeName"), - groupData.get("inchargePhoneNo"), - groupData.get("bankName"), - groupData.get("bankBranch"), - groupData.get("ifscCode"), - groupData.get("bankAccountno")); -} - -public List> getAllSchemeGroupNames() { - String sql = "SELECT group_id,group_name FROM suyaudavi_kuzhu"; - - // Use query with a RowMapper to map each row to a String - return nulmJdbcTemplate.queryForList(sql); -} - -public List> getAllSchemeGroups() { - String sql = "SELECT k.group_name, k.incharge_name, k.incharge_phoneno, k.created_date, " + - "SUM(CASE WHEN e.appointed = '1' THEN 1 ELSE 0 END) AS appointed_count, " + - "SUM(CASE WHEN e.appointed = '0' AND e.isactive = 1 THEN 1 ELSE 0 END) AS available_count, " + - "SUM(CASE WHEN e.isactive = 1 AND e.dropout = '1' THEN 1 ELSE 0 END) AS dropout_count " + - "FROM suyaudavi_kuzhu k " + - "LEFT JOIN enrollment_table e ON k.group_id = e.group_id " + - "GROUP BY k.group_name, k.incharge_name, k.incharge_phoneno, k.created_date"; - - return nulmJdbcTemplate.queryForList(sql); -} - -//public List getAllSchemeGroupNames() { -// String sql = "SELECT group_name FROM suyaudavi_kuzhu"; -// -// // Use query with a RowMapper to map each row to a String -// return nulmJdbcTemplate.query(sql, new RowMapper() { -// @Override -// public String mapRow(ResultSet rs, int rowNum) throws SQLException { -// return rs.getString("group_name"); -// } -// }); -//} - - - -/////////////////////////// Staff Detail Repository /////////////////////////////// -private RowMapper groupIdRowMapper = new RowMapper() { - @Override - public Integer mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getInt("group_id"); - } -}; - -// Method to retrieve group_id based on scheme_group_name -public Integer getGroupIdBySchemeGroupName(String groupName) { - String sql = "SELECT group_id FROM suyaudavi_kuzhu WHERE group_name = ?"; - - // Correct use of queryForObject with RowMapper and parameter - return jdbcTemplate.queryForObject(sql, groupIdRowMapper, groupName); -} - - -public void saveStaffDetails(Map staffData) { - String sql = "INSERT INTO enrollment_table (name, employee_id, phone_number, gender, date_of_birth, education_qualification, address, additional_skills, aadhar_card_url, ration_card_url, bank_passbook_url, staff_photo_url, created_date, group_id, appointed, facial_attendance, isactive, isdelete) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, 'No', 'No', 1, 0)"; - -nulmJdbcTemplate.update(sql, - staffData.get("name"), - staffData.get("employeeId"), - staffData.get("phoneNumber"), - staffData.get("gender"), - staffData.get("dateOfBirth"), - staffData.get("educationQualification"), - staffData.get("address"), // Ensure address is included - staffData.get("additionalSkills"), - staffData.get("aadharCardUrl"), - staffData.get("rationCardUrl"), - staffData.get("bankPassbookUrl"), - staffData.get("staffPhotoUrl"), - staffData.get("groupId")); -} - - -public List getStaffName() { - String sql = "SELECT name FROM enrollment_table "; - - // Use query with a RowMapper to map each row to a String - return nulmJdbcTemplate.query(sql, new RowMapper() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getString("name"); - } - }); -} - - -//////////////////Attendance Repository///////////////////////////////////////////////////////////////////////////// - - - - -////////////////Appointment Repository///////////////////////////////////////////////////////////////// -//Existing RowMappers -//private RowMapper groupIdsRowMapper = new RowMapper() { -// @Override -// public Integer mapRow(ResultSet rs, int rowNum) throws SQLException { -// return rs.getInt("group_id"); -// } -//}; -// -//private RowMapper enrollmentIdRowMapper = new RowMapper() { -// @Override -// public Integer mapRow(ResultSet rs, int rowNum) throws SQLException { -// return rs.getInt("enrollment_id"); -// } -//}; -// -//private RowMapper orderIdRowMapper = new RowMapper() { -// @Override -// public Integer mapRow(ResultSet rs, int rowNum) throws SQLException { -// return rs.getInt("order_id"); -// } -//}; -// -////Method to retrieve group_id based on scheme_group_name -//public Integer getGroupIdsBySchemeGroupName(String schemeGroupName) { -// String sql = "SELECT group_id FROM scheme_group WHERE scheme_group_name = ?"; -// return jdbcTemplate.queryForObject(sql, groupIdsRowMapper, schemeGroupName); -//} -// -////Method to retrieve staff_id based on staff_name -//public Integer getEnrollmentIdByStaffName(String name) { -// String sql = "SELECT enrollment_id FROM enrollment_table WHERE name = ?"; -// return jdbcTemplate.queryForObject(sql, enrollmentIdRowMapper, name); -//} -// -////Method to retrieve order_id based on both order_number and order_title -//public Integer getOrderIdByOrderNumberAndTitle(int orderNumber, String orderTitle) { -// String sql = "SELECT order_id FROM order_details WHERE order_number = ? AND order_title = ?"; -// return jdbcTemplate.queryForObject(sql, orderIdRowMapper, orderNumber, orderTitle); -//} -// -////Method to save appointment -//public void saveAppointment(Map appointmentData) { -// String schemeGroupName = (String) appointmentData.get("schemeGroupName"); -// Integer groupId = getGroupIdsBySchemeGroupName(schemeGroupName); -// -// String name = (String) appointmentData.get("name"); -// Integer staffId = getEnrollmentIdByStaffName(name); -// -// int orderNumber = (int) appointmentData.get("orderNumber"); -// String orderTitle = (String) appointmentData.get("orderTitle"); -// Integer orderId = getOrderIdByOrderNumberAndTitle(orderNumber, orderTitle); -// -// String sql = "INSERT INTO appointment (zone, ward, supervisor_name, department, date_of_appointment, created_at, group_id, staff_id, order_id, is_active, is_delete) " + -// "VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, ?, ?, 1, 0)"; -// nulmJdbcTemplate.update(sql, -// appointmentData.get("zone"), -// appointmentData.get("ward"), -// appointmentData.get("supervisorName"), -// appointmentData.get("department"), -// appointmentData.get("dateOfAppointment"), -// groupId, -// staffId, -// orderId); -//} - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/repository/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/repository/package-info.java deleted file mode 100644 index d6398ad8..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/repository/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.repository; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java deleted file mode 100644 index 91f5e449..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java +++ /dev/null @@ -1,3651 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.service; - -import java.nio.file.Path; -import java.sql.PreparedStatement; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; -import java.nio.file.Files; -import javax.sql.DataSource; -import java.nio.file.Paths; -import java.awt.image.BufferedImage; -import javax.imageio.ImageIO; -import java.io.ByteArrayInputStream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -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.web.multipart.MultipartFile; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.stream.ImageOutputStream; -import java.sql.Statement; -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; -import in.gov.chennaicorporation.gccoffice.nulm.repository.NulmRepository; - -@Service -public class NulmService { - - @Autowired - private NulmRepository nulmRepository; - @Autowired - private Environment environment; - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Value("${fileBaseUrl}") - - private String fileBaseUrl; - - @Autowired - public NulmService(NulmRepository nulmRepository, JdbcTemplate jdbcTemplate) { - this.nulmRepository = nulmRepository; - this.jdbcTemplate = jdbcTemplate; - - } - - /* - * public NulmService(Environment environment) { - * this.environment = environment; - * this.fileBaseUrl = environment.getProperty("fileBaseUrl"); - * } - */ - - @Autowired - public void setDataSource(@Qualifier("mysqlNulmDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public void saveOrderDetails(Map orderData) { - nulmRepository.saveOrderDetails(orderData); - } - - public void saveSchemeGroup(Map groupData) { - nulmRepository.saveSchemeGroup(groupData); - } - - public void saveStaffDetails(Map staffData) { - nulmRepository.saveStaffDetails(staffData); - } - - public List> getYearList() { - String sql = "SELECT DISTINCT year(coalesce(indatetime,oddatetime,leavedatetime)) as year FROM attendance "; - return jdbcTemplate.queryForList(sql); - } - - public List> getMonthList(int year) { - String sql = "SELECT DISTINCT MONTHNAME(coalesce(indatetime,oddatetime,leavedatetime)) as month FROM attendance where " - + "year(coalesce(indatetime,oddatetime,leavedatetime)) = ? "; - return jdbcTemplate.queryForList(sql, year); - } - - public List> getGenderList() { - String sql = "SELECT DISTINCT(gender) as gender FROM enrollment_table "; - return jdbcTemplate.queryForList(sql); - } - - public List> getDivisionList(String zone) { - String sql = "SELECT DISTINCT(division) as division FROM enrollment_table where zone = ? "; - return jdbcTemplate.queryForList(sql, zone); - } - - public void assignOrderToEnrollments(int orderId, List enrollmentIds) { - // Step 1: Retrieve the selected order - String getOrderSql = "SELECT * FROM order_details WHERE order_id = ?"; - Map orderDetails; - try { - orderDetails = jdbcTemplate.queryForMap(getOrderSql, orderId); - } catch (EmptyResultDataAccessException e) { - // Handle the case where no order is found - System.err.println("No order found with order_id: " + orderId); - return; // Exit the method if the order is not found - } - - if (orderDetails != null) { - // Step 2: Build the SQL for updating enrollments with dynamic IN clause - StringBuilder updateSql = new StringBuilder( - "UPDATE enrollment_table SET order_id = ?, appointed = 'Yes', facial_attendance = 'No', appointed_date = CURRENT_DATE WHERE enrollment_id IN ("); - - // Add placeholders for the IN clause based on the size of the enrollmentIds - // list - for (int i = 0; i < enrollmentIds.size(); i++) { - updateSql.append("?"); - if (i < enrollmentIds.size() - 1) { - updateSql.append(", "); - } - } - updateSql.append(")"); - - // Combine the orderId with the list of enrollmentIds - List parameters = new ArrayList<>(); - parameters.add(orderId); - parameters.addAll(enrollmentIds); - - // Execute the update query - try { - jdbcTemplate.update(updateSql.toString(), parameters.toArray()); - } catch (DataAccessException e) { - // Handle any data access exceptions - System.err.println("Error updating enrollments: " + e.getMessage()); - } - } - } - - public Map getAppointedCounts(int orderId) { - // Query to get counts from the enrollment_table - String enrollmentQuery = "SELECT " + - "COUNT(CASE WHEN appointed = 'Yes' THEN 1 END) AS total_yes, " + - "COUNT(CASE WHEN appointed = 'No' THEN 1 END) AS total_no " + - "FROM enrollment_table " + - "WHERE order_id = ?"; - - // Query to get total_count from order_details - String orderDetailsQuery = "SELECT no_of_staffs AS total_count " + - "FROM order_details " + - "WHERE order_id = ?"; - - // Execute the first query - Map counts = jdbcTemplate.queryForObject(enrollmentQuery, new Object[] { orderId }, - (rs, rowNum) -> { - Map result = new HashMap<>(); - result.put("total_yes", rs.getInt("total_yes")); - result.put("total_no", rs.getInt("total_no")); - return result; - }); - - // Execute the second query - Integer totalCount = jdbcTemplate.queryForObject(orderDetailsQuery, new Object[] { orderId }, Integer.class); - - // Add the total_count to the result map - counts.put("total_count", totalCount); - - // Calculate the output value: total_count - total_yes - int outputValue = totalCount - counts.get("total_yes"); - - // Add the output value to the result map - counts.put("output_value", outputValue); - - return counts; - } - - public Map getDropCounts(int orderId) { - // Query to get counts from the enrollment_table - String enrollmentQuery = "SELECT " + - "COUNT(CASE WHEN appointed = 'Yes' THEN 1 END) AS total_yes, " + - "COUNT(CASE WHEN dropout = 'Yes' THEN 1 END) AS total_drop, " + - "COUNT(CASE WHEN appointed IS NULL THEN 1 END) AS total_null " + - "FROM enrollment_table " + - "WHERE order_id = ?"; - - // Query to get total_count from order_details - String orderDetailsQuery = "SELECT no_of_staffs AS total_count " + - "FROM order_details " + - "WHERE order_id = ?"; - - // Execute the first query - Map counts = jdbcTemplate.queryForObject(enrollmentQuery, new Object[] { orderId }, - (rs, rowNum) -> { - Map result = new HashMap<>(); - result.put("total_yes", rs.getInt("total_yes")); - result.put("total_drop", rs.getInt("total_drop")); - result.put("total_null", rs.getInt("total_null")); - return result; - }); - - // Execute the second query - Integer totalCount = jdbcTemplate.queryForObject(orderDetailsQuery, new Object[] { orderId }, Integer.class); - - // Add the total_count to the result map - counts.put("total_count", totalCount); - - return counts; - } - - public List> getAllSchemeGroupNames() { - return nulmRepository.getAllSchemeGroupNames(); - } - - public List> getEnrollmentDetails(int groupId) { - String sql = "SELECT * FROM enrollment_table WHERE group_id = ? AND (appointed IS NULL OR appointed = 'NO')"; - return jdbcTemplate.queryForList(sql, groupId); - } - - public List> getAppointedDetails(int groupId) { - String sql = "SELECT * FROM enrollment_table WHERE group_id = ? AND (appointed IS NULL OR appointed = 'Yes')"; - return jdbcTemplate.queryForList(sql, groupId); - } - - public int markAbsentEntry(int employeeId) { - // Query to check if the employee has already been marked absent for today - String checkAbsentQuery = "SELECT absent FROM attendance WHERE employee_id = ? AND attendance_date = CURDATE()"; - - List absentResults = jdbcTemplate.query( - checkAbsentQuery, - ps -> ps.setInt(1, employeeId), - (rs, rowNum) -> rs.getInt("absent")); - - // If no record found for today, mark as absent - if (absentResults.isEmpty()) { - // Insert a new row to mark the employee as absent for today - String insertAbsentQuery = "INSERT INTO attendance (employee_id, absent, mark_attendance, attendance_date) VALUES (?, 1, 'ABSENT', CURDATE())"; - return jdbcTemplate.update(insertAbsentQuery, employeeId); - } - - // If already marked absent for today, return 0 indicating no action taken - return 0; - } - - public int markOverDuty(int employeeId) { - // Check if the employee ID exists in the attendance table - String checkEmployeeQuery = "SELECT od FROM attendance WHERE employee_id = ?"; - - List odResults = jdbcTemplate.query( - checkEmployeeQuery, - ps -> ps.setInt(1, employeeId), - (rs, rowNum) -> rs.getInt("od")); - - // If the employee ID exists, update the OD field to 1 - if (!odResults.isEmpty()) { - String updateOdQuery = "UPDATE attendance SET od = 1, mark_attendance = 'OD' WHERE employee_id = ?"; - return jdbcTemplate.update(updateOdQuery, employeeId); - } - - // If the employee ID doesn't exist, return 0 to indicate no update - return 0; - } - - public List> getAllOrderDetails() { - return nulmRepository.getAllOrderDetails(); - } - - public String markAttendance(int employeeId, String markAttendance) { - // Get today's date - LocalDate today = LocalDate.now(); - - // Query to check the current status of check_in and check_out for the employee - // on the current date - String checkAttendanceQuery = "SELECT check_in, check_out FROM attendance WHERE employee_id = ? AND attendance_date = ?"; - - List> attendanceResults = jdbcTemplate.query( - checkAttendanceQuery, - ps -> { - ps.setInt(1, employeeId); - ps.setObject(2, today); - }, - (rs, rowNum) -> { - Map result = new HashMap<>(); - result.put("check_in", rs.getInt("check_in")); - result.put("check_out", rs.getInt("check_out")); - return result; - }); - - // If the employee has not checked in today - if (attendanceResults.isEmpty()) { - if ("IN".equalsIgnoreCase(markAttendance)) { - // Mark check-in (entry phase) - String insertAttendanceQuery = "INSERT INTO attendance (employee_id, mark_attendance, check_in, in_time, attendance_date) VALUES (?, 'IN', 1, NOW(), ?)"; - jdbcTemplate.update(insertAttendanceQuery, employeeId, today); - return "Checked in successfully"; - } else { - // Trying to check out without a check-in for today - return "Failed to mark attendance - Cannot check out without checking in first"; - } - } - - // Retrieve the first (and only) result since attendance is checked by employee - // ID and date - Map result = attendanceResults.get(0); - Integer checkInStatus = (Integer) result.get("check_in"); - Integer checkOutStatus = (Integer) result.get("check_out"); - - // If the markAttendance is 'OUT' and check-in is already marked as 1 - if ("OUT".equalsIgnoreCase(markAttendance) && checkInStatus == 1 - && (checkOutStatus == null || checkOutStatus == 0)) { - // Mark check-out (exit phase) - String updateCheckOutQuery = "UPDATE attendance SET check_out = 1, out_time = NOW(), mark_attendance = 'OUT' WHERE employee_id = ? AND attendance_date = ?"; - int rowsUpdated = jdbcTemplate.update(updateCheckOutQuery, employeeId, today); - if (rowsUpdated > 0) { - return "Checked out successfully"; - } else { - return "Failed to mark attendance - Could not update check-out status"; - } - } - - // If trying to check in again when already checked in - if ("IN".equalsIgnoreCase(markAttendance) && checkInStatus == 1) { - return "Failed to mark attendance - Already checked in today"; - } - - // If trying to check out but not meeting the conditions - return "Failed to mark attendance - Invalid conditions for check-out"; - } - - public List getAllOrderNumber() { - return nulmRepository.getAllOrderNumber(); - } - - public List> getAllSchemeGroups() { - return nulmRepository.getAllSchemeGroups(); - } - - public List> getAllOrders() { - return nulmRepository.getAllOrders(); - } - - public List getStaffName() { - return nulmRepository.getStaffName(); - } - - public List> getEnrollments(String department, String division) { - StringBuilder sql = new StringBuilder("SELECT e.*, o.order_number, s.group_name " + - "FROM enrollment_table e " + - "LEFT JOIN order_details o ON e.order_id = o.order_id " + - "LEFT JOIN suyaudavi_kuzhu s ON e.group_id = s.group_id " + - "WHERE e.appointed = '1' AND e.isactive = '1' AND e.isdelete = '0' AND e.emp_type='NULM' "); - - if (department != null && !department.isEmpty()) { - sql.append(" AND e.department = '").append(department).append("'"); - } - if (division != null && !division.isEmpty()) { - sql.append(" AND e.division = '").append(division).append("'"); - } - - return jdbcTemplate.queryForList(sql.toString()); - } - - /// - public List> getEnrollmentsForPark(String department, String division) { - StringBuilder sql = new StringBuilder("SELECT e.*, o.order_number, s.group_name " + - "FROM enrollment_table e " + - "LEFT JOIN order_details o ON e.order_id = o.order_id " + - "LEFT JOIN suyaudavi_kuzhu s ON e.group_id = s.group_id " + - "WHERE e.appointed = '1' AND e.isactive = '1' AND e.isdelete = '0' AND e.emp_type='Park' "); - - if (department != null && !department.isEmpty()) { - sql.append(" AND e.department = '").append(department).append("'"); - } - if (division != null && !division.isEmpty()) { - sql.append(" AND e.division = '").append(division).append("'"); - } - - return jdbcTemplate.queryForList(sql.toString()); - } - /// - - public List> getDepartment() { - String sql = "SELECT DISTINCT department FROM enrollment_table WHERE isactive = 1 AND isdelete = 0"; - return jdbcTemplate.queryForList(sql); - } - - public List> getDivision() { - String sql = "SELECT DISTINCT division FROM enrollment_table WHERE isactive = 1 AND isdelete = 0"; - return jdbcTemplate.queryForList(sql); - } - - public List> getEnrollmentsById(int enrollmentId) { - String sql = "SELECT * FROM enrollment_table " + - "WHERE enrollment_id = ? " + - "AND isactive = 1 " + - "AND isdelete = 0 " + - "AND (appointed = 1 OR appointed IS NULL) " + - "AND (dropout = 0 OR dropout IS NULL) "; - - try { - // Query the database for enrollment details based on the specified conditions - // and enrollment_id - return jdbcTemplate.queryForList(sql, new Object[] { enrollmentId }); - } catch (Exception e) { - // Return an empty list if no enrollments are found - return List.of(); - } - } - - public List> getSelfHelpGroups() { - String sql = "SELECT group_id AS groupId, group_name AS groupName FROM suyaudavi_kuzhu WHERE isactive = 1 AND isdelete = 0 order by group_name asc"; - return jdbcTemplate.queryForList(sql); - } - - public List> getOrderNumbers() { - String sql = "SELECT order_id AS orderId, order_number AS orderNumber FROM order_details WHERE isactive = 1 AND isdelete = 0"; - return jdbcTemplate.queryForList(sql); - } - - public int updateEnrollment( - int enrollmentId, - String dateOfBirth, - String gender, - int groupId, // New parameter - int orderId // New parameter - ) { - String sql = "UPDATE enrollment_table SET date_of_birth = ?, gender = ?, group_id = ?, order_id = ? WHERE enrollment_id = ?"; - - return jdbcTemplate.update(sql, dateOfBirth, gender, groupId, orderId, enrollmentId); - } - - /* - * public String saveOrderDetails(String order_number, Date order_date, int - * no_of_staffs, String order_description, String order_copy_url, String - * order_generated_by, String category, Date validity_date) { - * String sql = - * "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " - * + - * "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)" - * ; - * - * try { - * // Parameters array to be passed to the update method - * Object[] params = new Object[] { - * order_number, - * order_date, - * no_of_staffs, - * order_description, - * order_copy_url, - * order_generated_by, - * category, - * validity_date, - * validity_date, // For the CASE WHEN condition - * new Date() // Current date for comparison with validity_date - * }; - * - * // Execute the update - * jdbcTemplate.update(sql, params); - * - * return order_number; - * } catch (Exception e) { - * e.printStackTrace(); - * return "Error in Saving Order Details, give proper input"; - * } - * } - */ - - public String saveOrderDetails(String order_number, Date order_date, int no_of_staffs, String order_description, - String order_copy_url, String order_generated_by, String category, Date validity_date) { - String sql = "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " - + - "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)"; - - try { - // Parameters array to be passed to the update method - Object[] params = new Object[] { - order_number, - order_date, - no_of_staffs, - order_description, - order_copy_url, - order_generated_by, - category, - validity_date, - validity_date, // For the CASE WHEN condition - order_date // Comparison with order_date instead of the current date - }; - - // Log the SQL query for debugging - System.out.println( - "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " - + - "VALUES ('" + order_number + "', '" + order_date + "', '" + no_of_staffs + "', '" - + order_description + "', '" + order_copy_url + "', '" + order_generated_by + "', '" - + category + "', CURRENT_TIMESTAMP, " + - validity_date + ", CASE WHEN " + validity_date + " >= " + order_date - + " THEN 'Active' ELSE 'Expired' END, 1, 0)"); - - // Execute the update - jdbcTemplate.update(sql, params); - - return order_number; - } catch (Exception e) { - e.printStackTrace(); - return "Error in Saving Order Details, give proper input"; - } - } - - public int addSalaryDetails(int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, - String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, int wageId) { - String sql = "INSERT INTO salary_details (total_days_present, total_days_od, total_days_salary, total_days_absent, month, year, salary_amount, salary_status, enrollment_id, group_id, wage_id) " - + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, - salaryAmount, salaryStatus, enrollmentId, groupId, wageId); - } - - //// - - // public int addSalaryDetails_park(int totalDaysPresent, int totalDaysOd, int - // totalDaysSalary, int totalDaysAbsent, - // String month, int year, int salaryAmount, - // String salaryStatus, int enrollmentId, int groupId, int wageId) - // { - // String sql = "INSERT INTO salary_details_park (total_days_present, - // total_days_od, total_days_salary, total_days_absent, month, year, - // salary_amount, salary_status, enrollment_id, group_id, wage_id) " - // + - // "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - // - // return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, - // totalDaysSalary, totalDaysAbsent, month, year, - // salaryAmount, salaryStatus, enrollmentId, groupId, wageId); - // } - - //// - - public List> getAttendanceWithSalary(String month, Integer year) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.enrollment_id, " + - "e.name, " + - "e.incharge_id, " + - "YEAR(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))) AS year, " + - "MONTHNAME(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))) AS month, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + - "COUNT(DISTINCT DATE(a.indatetime)) + " + - "COUNT(DISTINCT DATE(a.leavedatetime)) + " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " - + - "(SELECT sw.wage_id FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS wage_id, " - + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " - + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - + - "sd.salary_status, " + - "sk.group_id, " + - "sk.group_name " + - "FROM enrollment_table e " + - "LEFT JOIN attendance a ON e.enrollment_id = a.enrollment_id " + // Changed JOIN to LEFT JOIN to include - // all enrollments - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "AND YEAR(a.indatetime and a.oddatetime and a.leavedatetime) = sd.year " + - "AND MONTHNAME(a.indatetime and a.oddatetime and a.leavedatetime) = sd.month " + - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Add month condition if month is provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(coalesce((a.indatetime),(a.leavedatetime),(a.oddatetime)))= ? "); - } - - // Add year condition if year is provided - if (year != null) { - sql.append("AND YEAR(coalesce((a.indatetime),(a.leavedatetime),(a.oddatetime))) = ? "); - } - - sql.append("GROUP BY e.enrollment_id, YEAR(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))), " - + "MONTHNAME(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))), sd.salary_status "); - - // Create a list of parameters to pass to the query - List params = new ArrayList<>(); - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Execute the query with the provided parameters - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - // List> results = - // jdbcTemplate.queryForList(sql.toString()); - return results; - } - /* - * public List> getAttendanceWithSalaryByInchargeId(String - * month, Integer year, Integer incharge_id) { - * String sql = - * "SELECT e.enrollment_id, e.emp_id, COALESCE(e.name, '') AS name, YEAR(a.indatetime) AS year, " - * + "MONTHNAME(a.indatetime) AS month, COUNT(a.inby) AS total_days_present, " - * + "COUNT(a.leaveby) AS total_days_absent, COUNT(a.odby) AS total_days_od, " - * + "(COUNT(a.inby) + COUNT(a.leaveby) + COUNT(a.odby)) AS total_days, " - * + "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " - * + - * "COALESCE((SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1), 0) AS salary_per_day, " - * + - * "COALESCE(((COUNT(a.inby) + COUNT(a.odby)) * (SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)), 0) AS total_salary, " - * + - * "COALESCE(sd.salary_status, '') AS salary_status, COALESCE(sk.group_id, '') AS group_id, " - * + "COALESCE(sk.group_name, '') AS group_name " - * + "FROM enrollment_table e " - * + "JOIN attendance a ON e.enrollment_id = a.enrollment_id " - * + "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " - * + "AND YEAR(a.indatetime) = sd.year AND MONTHNAME(a.indatetime) = sd.month " - * + "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " - * + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + "AND e.incharge_id = '" + incharge_id + "' " - * + "AND MONTHNAME(a.indatetime) = '" + month + "' " - * + "AND YEAR(a.indatetime) = '" + year + "' " - * + - * "GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), " - * + "sd.salary_status, sk.group_id, sk.group_name"; - * - * System.out.println(sql); - * - * // Execute the query with the provided parameters - * List> results = jdbcTemplate.queryForList(sql); - * return results; - * } - * - * public List> getAttendanceWithSalary(String month, - * Integer year) { - * StringBuilder sql = new StringBuilder("SELECT " + - * "e.enrollment_id, " + - * "e.name, " + - * "YEAR(a.indatetime) AS year, " + - * "MONTHNAME(a.indatetime) AS month, " + - * "COUNT(a.inby) AS total_days_present, " + - * "COUNT(a.leaveby) AS total_days_absent, " + - * "COUNT(a.odby) AS total_days_od, " + - * "(COUNT(a.inby) + COUNT(a.leaveby) + COUNT(a.odby)) AS total_days, " + - * "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + - * "(SELECT sw.wage_id FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS wage_id, " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + - * "((COUNT(a.inby) + COUNT(a.odby)) * " + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + - * "sd.salary_status, " + - * "sk.group_id, " + - * "sk.group_name " + - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "AND YEAR(a.indatetime) = sd.year " + - * "AND MONTHNAME(a.indatetime) = sd.month " + - * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * ); - * - * // Add month condition if month is provided - * if (month != null && !month.isEmpty()) { - * sql.append("AND MONTHNAME(a.indatetime) = ? "); - * } - * - * // Add year condition if year is provided - * if (year != null) { - * sql.append("AND YEAR(a.indatetime) = ? "); - * } - * - * sql. - * append("GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), sd.salary_status, sk.group_id, sk.group_name" - * ); - * - * // Create a list of parameters to pass to the query - * List params = new ArrayList<>(); - * if (month != null && !month.isEmpty()) { - * params.add(month); - * } - * if (year != null) { - * params.add(year); - * } - * - * // Execute the query with the provided parameters - * List> results = jdbcTemplate.queryForList(sql.toString(), - * params.toArray()); - * return results; - * } - * - * public List> getSalaryReport(String month, int year, - * String salaryStatus,String loginId) { - * - * // Retrieve zone access for the user - * String ZoneWhare; - * String zoneAccessSQL = - * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - * List> getAccess = - * jdbcTemplate.queryForList(zoneAccessSQL, loginId); - * System.out.println(zoneAccessSQL +"->"+ loginId); - * // Extract the zones from getAccess - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - * - * // If the user has zone acc ess, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * ZoneWhare = " AND e.zone IN ("+zoneList+")"; - * // System.out.println("AND e.zone IN ("+zoneList+")"); - * } - * else { - * ZoneWhare = " AND e.zone IN (0)"; - * } - * - * String sql = "SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "e.incharge_name, " + // Fetch incharge_name from enrollment_table - * "e.incharge_designation, " + // Fetch incharge_designation from - * enrollment_table - * "YEAR(a.indatetime) AS year, " + - * "MONTHNAME(a.indatetime) AS month, " + // Use MONTHNAME to get month in words - * "COUNT(a.inby) AS total_days_present, " + - * "COUNT(a.leaveby) AS total_days_absent, " + // Changed to total_days_absent - * "COUNT(a.odby) AS total_days_od, " + - * "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + // Fetch salary_per_day from staff_wages table - * "((COUNT(a.inby) + COUNT(a.odby)) * " + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + // Calculate total salary - * "sd.salary_status, " + - * "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table - * "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "AND YEAR(a.indatetime) = sd.year " + // Match year - * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with - * suyaudavi_kuzhu table on group_id - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + // Removed unauthorizedleaveby - * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - * "AND YEAR(a.indatetime) = ? "+ // Filter by year - * "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // - * Filter by year - * (salaryStatus != null && !salaryStatus.isEmpty() ? - * "AND sd.salary_status = ? " : "") + // Optional filter by salary status - * ZoneWhare - * +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, YEAR(a.indatetime), MONTHNAME(a.indatetime), salary_per_day, sd.salary_status, sk.group_id, sk.group_name" - * ; // Group by new fields - * - * // Prepare the query parameters based on provided inputs - * List params = new ArrayList<>(); - * params.add(month); - * params.add(year); - * if (salaryStatus != null && !salaryStatus.isEmpty()) { - * params.add(salaryStatus); - * } - * - * // Execute the query with dynamic parameters - * List> results = jdbcTemplate.queryForList(sql, - * params.toArray()); - * return results; - * } - */ - - /* - * public List> getSalaryReport(String month, int year, - * String salaryStatus,String loginId) { - * - * // Retrieve zone access for the user - * String ZoneWhare; - * String zoneAccessSQL = - * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - * List> getAccess = - * jdbcTemplate.queryForList(zoneAccessSQL, loginId); - * System.out.println(zoneAccessSQL +"->"+ loginId); - * // Extract the zones from getAccess - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - * - * // If the user has zone acc ess, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * ZoneWhare = " AND e.zone IN ("+zoneList+")"; - * // System.out.println("AND e.zone IN ("+zoneList+")"); - * } - * else { - * ZoneWhare = " AND e.zone IN (0)"; - * } - * - * String sql = "SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "e.incharge_name, " + // Fetch incharge_name from enrollment_table - * "e.incharge_designation, " + // Fetch incharge_designation from - * enrollment_table - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS iyear, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS imonth, " - * + // Use MONTHNAME to get month in words - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + // Changed - * to total_days_absent - * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + // Fetch salary_per_day from staff_wages table - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + // Calculate total salary - * "sd.salary_status, " + - * "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table - * "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "AND YEAR(a.indatetime) = sd.year " + // Match year - * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with - * suyaudavi_kuzhu table on group_id - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + // Removed unauthorizedleaveby - * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - * "AND YEAR(a.indatetime) = ? "+ // Filter by year - * "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // - * Filter by year - * (salaryStatus != null && !salaryStatus.isEmpty() ? - * "AND sd.salary_status = ? " : "") + // Optional filter by salary status - * ZoneWhare - * +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, iyear, imonth, salary_per_day, sd.salary_status, sk.group_id, sk.group_name" - * ; // Group by new fields - * - * // Prepare the query parameters based on provided inputs - * List params = new ArrayList<>(); - * params.add(month); - * params.add(year); - * if (salaryStatus != null && !salaryStatus.isEmpty()) { - * params.add(salaryStatus); - * } - * - * // Execute the query with dynamic parameters - * List> results = jdbcTemplate.queryForList(sql, - * params.toArray()); - * return results; - * } - */ - public List> getSalaryReport(String month, Integer year, String salaryStatus, String groupName, - String loginId) { - - // Retrieve zone access for the user - String ZoneWhare = ""; - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL + "->" + loginId); - /* - * // Extract the zones from getAccess - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - */ - // Extract the zones from getAccess - List zones = new ArrayList(); - - if (getAccess != null) { - for (Map access : getAccess) { - Object zoneObj = access.get("zone"); - if (zoneObj != null) { - zones.add(zoneObj.toString()); - } - } - } - /* - * // If the user has zone access, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * ZoneWhare = " AND en.zone IN ("+zoneList+")"; - * } - * else { - * ZoneWhare = " AND en.zone IN (0)"; - * } - */ - // If the user has zone access, add it to the WHERE clause - // String ZoneWhare = ""; - if (zones != null && !zones.isEmpty()) { - StringBuilder zoneListBuilder = new StringBuilder(); - for (int i = 0; i < zones.size(); i++) { - zoneListBuilder.append("'").append(zones.get(i)).append("'"); - if (i < zones.size() - 1) { - zoneListBuilder.append(", "); - } - } - ZoneWhare = " AND en.zone IN (" + zoneListBuilder.toString() + ")"; - } else { - ZoneWhare = " AND en.zone IN (0)"; - } - - String sql = "select en.emp_id, en.name, en.incharge_name, en.designation, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " - + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " - + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " - + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " - + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " - + "where s.month = ? and s.year =? " - + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") - + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "") - + ZoneWhare; - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /// - - public List> getSalaryReport_park(String month, Integer year, String salaryStatus, - String groupName, - String loginId) { - - // Retrieve zone access for the user - String ZoneWhare = ""; - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL + "->" + loginId); - /* - * // Extract the zones from getAccess - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - */ - // Extract the zones from getAccess - List zones = new ArrayList(); - - if (getAccess != null) { - for (Map access : getAccess) { - Object zoneObj = access.get("zone"); - if (zoneObj != null) { - zones.add(zoneObj.toString()); - } - } - } - /* - * // If the user has zone access, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * ZoneWhare = " AND en.zone IN ("+zoneList+")"; - * } - * else { - * ZoneWhare = " AND en.zone IN (0)"; - * } - */ - // If the user has zone access, add it to the WHERE clause - // String ZoneWhare = ""; - if (zones != null && !zones.isEmpty()) { - StringBuilder zoneListBuilder = new StringBuilder(); - for (int i = 0; i < zones.size(); i++) { - zoneListBuilder.append("'").append(zones.get(i)).append("'"); - if (i < zones.size() - 1) { - zoneListBuilder.append(", "); - } - } - ZoneWhare = " AND en.zone IN (" + zoneListBuilder.toString() + ")"; - } else { - ZoneWhare = " AND en.zone IN (0)"; - } - - String sql = "select en.emp_id, en.name, en.incharge_name, en.designation, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " - + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " - + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details_park s " - + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " - + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " - + "where s.month = ? and s.year =? " - + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") - + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "") - + ZoneWhare; - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /// - - /* - * public List> getSalaryReport(String month, Integer year, - * String salaryStatus, String groupName) { - * String sql = - * "select en.emp_id, en.name, en.incharge_name, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " - * + - * "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " - * + - * "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " - * + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " - * + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " - * + "where s.month = ? and s.year =? " - * + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - * + (salaryStatus != null && !salaryStatus.isEmpty() ? - * "AND s.salary_status = ? " : "") - * + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : - * ""); - * - * // Prepare the query parameters based on provided inputs - * List params = new ArrayList<>(); - * params.add(month); - * params.add(year); - * if (salaryStatus != null && !salaryStatus.isEmpty()) { - * params.add(salaryStatus); - * } - * if (groupName != null && !groupName.isEmpty()) { - * params.add(groupName); - * } - * - * List> results = jdbcTemplate.queryForList(sql.toString(), - * params.toArray()); - * return results; - * } - */ - /* - * public List> getSalaryReport(String month, int year, - * String salaryStatus ,String groupName, String loginId) { - * // Retrieve zone access for the user - * String ZoneWhere; - * String zoneAccessSQL = - * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - * List> getAccess = - * jdbcTemplate.queryForList(zoneAccessSQL, loginId); - * System.out.println(zoneAccessSQL +"->"+ loginId); - * // Extract the zones from getAccess - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - * - * // If the user has zone acc ess, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * ZoneWhere = " AND e.zone IN ("+zoneList+")"; - * // System.out.println("AND e.zone IN ("+zoneList+")"); - * } - * else { - * ZoneWhere = " AND e.zone IN (0)"; - * } - * - * String sql = "SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "e.incharge_name, " + // Fetch incharge_name from enrollment_table - * "e.incharge_designation, " + // Fetch incharge_designation from - * enrollment_table - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS iyear, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS imonth, " - * + // Use MONTHNAME to get month in words - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + // Count of OD days - * "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " - * + // Calculate total days in the month - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " - * + // Calculate total present and OD days - * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " - * + // Calculate total days absent - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " - * + // Calculate total days absent - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + // Fetch salary_per_day from staff_wages table - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + // Calculate total salary - * "sd.salary_status, " + - * "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table - * "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "AND YEAR(a.indatetime) = sd.year " + // Match year - * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with - * suyaudavi_kuzhu table on group_id - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + // Removed unauthorizedleaveby - * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - * "AND YEAR(a.indatetime) = ? " + // Filter by year - * "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // - * Filter by salary status - * (salaryStatus != null && !salaryStatus.isEmpty() ? - * "AND sd.salary_status = ? " : "") + - * (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : - * "")+// Optional filter by salary status - * ZoneWhere - * +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, iyear, imonth, salary_per_day, sd.salary_status, sk.group_id, sk.group_name" - * ; // Group by new fields - * - * // Prepare the query parameters based on provided inputs - * List params = new ArrayList<>(); - * params.add(month); - * params.add(year); - * if (salaryStatus != null && !salaryStatus.isEmpty()) { - * params.add(salaryStatus); - * } - * if (groupName != null && !groupName.isEmpty()) { - * params.add(groupName); - * } - * - * // Execute the query with dynamic parameters - * List> results = jdbcTemplate.queryForList(sql, - * params.toArray()); - * return results; - * } - */ - - /* - * public List> getAttendanceWithInitiatedSalary(String - * inchargeName, String month) { - * String sql = "SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "YEAR(a.indatetime) AS year, " + - * "MONTHNAME(a.indatetime) AS month, " + // Get month in words - * "COUNT(a.inby) AS total_days_present, " + - * "COUNT(a.leaveby) AS total_days_absent, " + // Changed to total_days_absent - * "COUNT(a.odby) AS total_days_od, " + - * "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + // Fetch salary_per_day from staff_wages table - * "((COUNT(a.inby) + COUNT(a.odby)) * " + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + // Calculate total salary - * "sd.salary_status " + - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + // Join with - * attendance table - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + // - * Left join with salary_details - * "AND YEAR(a.indatetime) = sd.year " + // Match year - * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + // Removed unauthorizedleaveby - * "AND e.incharge_name = ? " + // Filter by incharge_name - * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - * "AND sd.salary_status IN ('Initiated', 'Approved') " + // Filter by salary - * status 'Initiated' or 'Approved' - * "GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), salary_per_day, sd.salary_status" - * ; // Group by required fields - * - * List> results = jdbcTemplate.queryForList(sql, - * inchargeName, month); - * return results; - * } - */ - /* - * public List> getAttendanceWithInitiatedSalary(String - * inchargeName, String month) { - * String sql = "SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - * + - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + - * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + - * "sd.salary_status " + - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + - * "AND e.incharge_name = ? " + - * "AND sd.salary_status IN ('Initiated', 'Approved') " + - * "AND (MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? OR ? IS NULL) " - * + // Ensure month matches - * "GROUP BY e.enrollment_id, e.emp_id, e.name, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + // Grouping - * by COALESCE year - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), sd.salary_status" - * ; // Grouping by COALESCE month - * - * List> results = jdbcTemplate.queryForList(sql, - * inchargeName, month, month); - * return results; - * } - */ - /* - * public List> getAttendanceWithInitiatedSalary(String - * inchargeId, String month) { - * String sql = "SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - * + - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - * "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " - * + // Total days in the month - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " - * + - * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " - * + // Total days in the month - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " - * + // Calculate total days absent - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + - * "sd.salary_status " + - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * + - * "AND e.incharge_id = ? " + - * "AND sd.salary_status IN ('Initiated', 'Approved') " + - * "AND sd.month = ? " + // Filtering based on salary_details month - * "AND MONTHNAME(a.indatetime) = ? " + // Additional filtering on attendance - * "GROUP BY e.enrollment_id, e.emp_id, e.name, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), sd.salary_status" - * ; - * - * List> results = jdbcTemplate.queryForList(sql, - * inchargeId, month, month); - * return results; - * } - */ - /* - * public List> getAttendanceWithInitiatedSalary(String - * inchargeId, String month, String inchargeName, Integer zone) { - * StringBuilder sql = new StringBuilder("SELECT " + - * "e.group_id, " + - * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - * + - * "a.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "e.incharge_id, " + - * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " - * + - * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " - * + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - * + - * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " - * + - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " - * + - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " - * + - * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " - * + - * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " - * + - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " - * + - * "IFNULL(s.salary_status, '') AS salary_status " + - * "FROM attendance AS a " + - * "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - * "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - * "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " - * + - * "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * ); - * - * // Append condition for incharge_id - * sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - * - * // Append condition for incharge_name - * sql.append("AND (? IS NULL OR e.incharge_name = ?) "); - * - * // Append condition for zone - * sql.append("AND (? IS NULL OR e.zone = ?) "); - * - * // Append condition for month if provided - * if (month != null && !month.isEmpty()) { - * sql. - * append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " - * ); - * } - * - * // Add condition to filter by salary_status (only 'Initiated' or 'Approved') - * sql.append("AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') "); - * - * // Group by necessary columns - * sql.append("GROUP BY a.enrollment_id, e.group_id, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " - * + - * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " - * + - * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " - * + - * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - * "s.salary_status"); - * - * // Create a list of parameters - * List params = new ArrayList<>(); - * params.add(inchargeId); - * params.add(inchargeId); - * params.add(inchargeName); - * params.add(inchargeName); - * params.add(zone); - * params.add(zone); // Added twice for the conditional check in the SQL - * if (month != null && !month.isEmpty()) { - * params.add(month); - * } - * - * // Log the SQL and parameters (optional for debugging) - * System.out.println("Generated SQL: " + sql.toString()); - * System.out.println("Parameters: " + params); - * - * // Execute the query using JdbcTemplate - * List> results = jdbcTemplate.queryForList(sql.toString(), - * params.toArray()); - * return results; - * } - * - */ - /* - * public List> getAttendanceWithInitiatedSalary(String - * inchargeId, String month, String inchargeName, int zone) { - * StringBuilder sql = new StringBuilder("SELECT " + - * "e.group_id, " + - * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - * + - * "a.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "e.incharge_id, " + - * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " - * + - * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " - * + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - * + - * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " - * + - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " - * + - * "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " - * + - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " - * + - * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " - * + - * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " - * + - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " - * + - * "IFNULL(s.salary_status, '') AS salary_status " + - * "FROM attendance AS a " + - * "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - * "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - * "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " - * + - * "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * ); - * - * // Append condition for incharge_id - * sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - * - * // Append condition for incharge_name - * sql.append("AND (? IS NULL OR e.incharge_name = ?) "); - * - * // Append condition for month if provided - * if (month != null && !month.isEmpty()) { - * sql. - * append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " - * ); - * } - * - * // Add condition to filter by salary_status (only 'Initiated' or 'Approved') - * sql.append("AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') "); - * - * // Group by necessary columns - * sql.append("GROUP BY a.enrollment_id, e.group_id, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " - * + - * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " - * + - * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " - * + - * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - * "s.salary_status"); - * - * // Create a list of parameters - * List params = new ArrayList<>(); - * params.add(inchargeId); - * params.add(inchargeId); // Added twice for the conditional check in the SQL - * params.add(inchargeName); - * params.add(inchargeName); // Added twice for the conditional check in the SQL - * if (month != null && !month.isEmpty()) { - * params.add(month); - * } - * - * // Log the SQL and parameters (optional for debugging) - * System.out.println("Generated SQL: " + sql.toString()); - * System.out.println("Parameters: " + params); - * - * // Execute the query using JdbcTemplate - * List> results = jdbcTemplate.queryForList(sql.toString(), - * params.toArray()); - * return results; - * } - */ - - ///// - - public boolean checkSalaryDetails_park(int enrollmentId, String month, int year) { - String sql = "select enrollment_id from salary_details_park where enrollment_id =? and month = ? and year = ?"; - - List results = jdbcTemplate.queryForList(sql, Integer.class, enrollmentId, month, year); - return !results.isEmpty(); - - } - - public int addSalaryDetails_park( - int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, - String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, int wageId, int inchargeID) { - String sql = "INSERT INTO salary_details_park (total_days_present, total_days_od, total_days_salary, total_days_absent, month, year, " - + "salary_amount, salary_status, enrollment_id, group_id, wage_id, incharge_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, - salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); - } - - public int updateSalaryDetails_park( - int totalDaysPresent, int totalDaysOd, int totalDaysSalary, - int totalDaysAbsent, String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, - int wageId, int inchargeID) { - String sql = "update salary_details_park set total_days_present =?, total_days_od=?, total_days_salary = ? , total_days_absent = ?, month = ?, year = ?, " - + "salary_amount = ?, salary_status = ?, enrollment_id = ?, group_id= ?, wage_id= ?, incharge_id = ? where enrollment_id =? and month = ? and year = ? "; - - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, - salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID, enrollmentId, month, year); - } - - ///// - - public List> getAttendanceWithInitiatedSalary( - int inchargeId, String month, String year, String inchargeName, List enrollmentIds) { - - String sql = "SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - + - "a.enrollment_id, e.emp_id, e.name, e.incharge_id, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " - + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + - "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " - + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " - + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " - + - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " - + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + - "AND (? IS NULL OR e.incharge_id = ?) " + - "AND (? IS NULL OR e.incharge_name = ?) " + - "AND e.emp_type = 'NULM' "; - - if (month != null && !month.isEmpty()) { - sql += "AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; - } - if (year != null && !year.isEmpty()) { - sql += "AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; - } - - // Assuming enrollmentIds is a List or List - StringBuilder placeholders = new StringBuilder(); - for (int i = 0; i < enrollmentIds.size(); i++) { - placeholders.append("?"); - if (i < enrollmentIds.size() - 1) { - placeholders.append(", "); - } - } - String inClause = placeholders.toString() + ") "; - - sql += "AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') " + - "AND e.enrollment_id IN (" + - inClause + - "GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"; - - List params = new ArrayList<>(); - params.add(inchargeId); - params.add(inchargeId); - params.add(inchargeName); - params.add(inchargeName); - - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null && !year.isEmpty()) { - params.add(year); - } - - params.addAll(enrollmentIds); - - System.out.println("SQL = " + sql); - System.out.println("Parameter = " + params); - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - /// - - public List> getAttendanceWithInitiatedSalary_Park( - int inchargeId, String month, String year, String inchargeName, List enrollmentIds) { - - String sql = "SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - + - "a.enrollment_id, e.emp_id, e.name, e.incharge_id, " + - "(SELECT salary_per_day FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id) AS salary_per_day, " - + - "(SELECT wage_id FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id) AS wage_id, " - + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + - "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " - + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " - + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " - + - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " - + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details_park AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + - "AND (? IS NULL OR e.incharge_id = ?) " + - "AND (? IS NULL OR e.incharge_name = ?) " + - "AND e.emp_type = 'Park' "; - - if (month != null && !month.isEmpty()) { - sql += "AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; - } - if (year != null && !year.isEmpty()) { - sql += "AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; - } - - // Assuming enrollmentIds is a List or List - StringBuilder placeholders = new StringBuilder(); - for (int i = 0; i < enrollmentIds.size(); i++) { - placeholders.append("?"); - if (i < enrollmentIds.size() - 1) { - placeholders.append(", "); - } - } - String inClause = placeholders.toString() + ") "; - - sql += "AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') " + - "AND e.enrollment_id IN (" + - inClause + - "GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id), " - + - "(SELECT wage_id FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id), " - + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"; - - List params = new ArrayList<>(); - params.add(inchargeId); - params.add(inchargeId); - params.add(inchargeName); - params.add(inchargeName); - - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null && !year.isEmpty()) { - params.add(year); - } - - params.addAll(enrollmentIds); - - System.out.println("SQL = " + sql); - System.out.println("Parameter = " + params); - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - //// - - @Transactional - public void updateSalaryStatusToApproved(List enrollmentIds, String month, int year) { - String sql = "UPDATE salary_details SET salary_status = 'Approved' WHERE enrollment_id = ? AND month = ? AND year = ?"; - - for (Integer enrollmentId : enrollmentIds) { - // Pass the individual enrollmentId instead of the entire list - jdbcTemplate.update(sql, enrollmentId, month, year); - } - } - - //// - - @Transactional - public void updateSalaryStatusToApproved_Park(List enrollmentIds, String month, int year) { - String sql = "UPDATE salary_details_park SET salary_status = 'Approved' WHERE enrollment_id = ? AND month = ? AND year = ?"; - - for (Integer enrollmentId : enrollmentIds) { - // Pass the individual enrollmentId instead of the entire list - jdbcTemplate.update(sql, enrollmentId, month, year); - } - } - - //// - - /* - * public List> getFilteredSalaryDetails(String month, - * Integer year, String salaryStatus) { - * StringBuilder sql = new StringBuilder("SELECT " + - * "e.incharge_name, " + - * "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - * "COUNT(e.enrollment_id) AS total_staff_count, " + - * "sd.month, " + - * "sd.year, " + - * "sd.salary_status, " + - * "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " - * + - * "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " - * + - * "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount " - * + - * "FROM enrollment_table e " + - * "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "WHERE 1=1 "); // Placeholder for dynamic conditions - * - * if (month != null && !month.isEmpty()) { - * sql.append(" AND sd.month = '").append(month).append("'"); - * } - * if (year != null) { - * sql.append(" AND sd.year = ").append(year); - * } - * if (salaryStatus != null && !salaryStatus.isEmpty()) { - * sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - * } - * - * sql.append(" GROUP BY e.incharge_name, sd.month, sd.year, sd.salary_status " - * ); - * sql.append(" ORDER BY sd.year DESC, sd.month DESC"); - * - * try { - * List> result = jdbcTemplate.queryForList(sql.toString()); - * for (Map row : result) { - * String enrollmentIdsString = (String) row.get("enrollment_ids"); - * if (enrollmentIdsString != null) { - * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - * .map(String::trim) - * .filter(id -> !id.isEmpty()) - * .map(Integer::parseInt) - * .collect(Collectors.toList()); - * row.put("enrollment_ids", enrollmentIds); - * } - * } - * return result; - * } catch (Exception e) { - * e.printStackTrace(); - * return Collections.emptyList(); - * } - * } - */ - /* - * public List> getFilteredSalaryDetails(String month, - * Integer year, String salaryStatus, String department, String loginId) { - * StringBuilder sql = new StringBuilder("SELECT " + - * "e.incharge_name, " + - * "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - * "COUNT(e.enrollment_id) AS total_staff_count, " + - * "sd.month, " + - * "sd.year, " + - * "sd.salary_status, " + - * "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " - * + - * "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " - * + - * "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " - * + - * "e.department " + // Select the department as well - * "FROM enrollment_table e " + - * "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "WHERE 1=1 "); // Placeholder for dynamic conditions - * - * // Add filters for month, year, salary status, and department - * if (month != null && !month.isEmpty()) { - * sql.append(" AND sd.month = '").append(month).append("'"); - * } - * if (year != null) { - * sql.append(" AND sd.year = ").append(year); - * } - * if (salaryStatus != null && !salaryStatus.isEmpty()) { - * sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - * } - * if (department != null && !department.isEmpty()) { - * sql.append(" AND e.department = '").append(department).append("'"); - * } - * - * // Retrieve zone access for the user - * String zoneAccessSQL = - * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - * List> getAccess = - * jdbcTemplate.queryForList(zoneAccessSQL, loginId); - * System.out.println(zoneAccessSQL +"->"+ loginId); - * // Extract the zones from getAccess - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - * - * // If the user has zone acc ess, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * sql.append(" AND e.zone IN (").append(zoneList).append(")"); - * // System.out.println("AND e.zone IN ("+zoneList+")"); - * } - * else { - * sql.append(" AND e.zone IN (").append("0").append(")"); - * } - * - * sql. - * append(" GROUP BY e.incharge_name, sd.month, sd.year, sd.salary_status, e.department " - * ); - * sql.append(" ORDER BY sd.year DESC, sd.month DESC"); - * - * System.out.println(sql); - * - * try { - * List> result = jdbcTemplate.queryForList(sql.toString()); - * for (Map row : result) { - * String enrollmentIdsString = (String) row.get("enrollment_ids"); - * if (enrollmentIdsString != null) { - * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - * .map(String::trim) - * .filter(id -> !id.isEmpty()) - * .map(Integer::parseInt) - * .collect(Collectors.toList()); - * row.put("enrollment_ids", enrollmentIds); - * } - * } - * return result; - * } catch (Exception e) { - * e.printStackTrace(); - * return Collections.emptyList(); - * } - * } - */ - - public List> getFilteredSalaryDetails(String month, Integer year, String salaryStatus, - String loginId) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.incharge_name, " + - "e.incharge_id, " + - "e.zone, " + - "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - "COUNT(e.enrollment_id) AS total_staff_count, " + - "sd.month, " + - "sd.year, " + - "sd.salary_status, " + - "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + - "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + - "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " - + - "e.department " + // Select the department as well - "FROM enrollment_table e " + - "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE 1=1 AND e.emp_type = 'NULM' "); // Placeholder for dynamic conditions - - // Add filters for month, year, salary status, and department - if (month != null && !month.isEmpty()) { - sql.append(" AND sd.month = '").append(month).append("'"); - } - if (year != null) { - sql.append(" AND sd.year = ").append(year); - } - if (salaryStatus != null && !salaryStatus.isEmpty()) { - sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - } - - // Retrieve zone access for the user - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL + "->" + loginId); - // Extract the zones from getAccess - /* - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - * - * // If the user has zone acc ess, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * sql.append(" AND e.zone IN (").append(zoneList).append(")"); - * // System.out.println("AND e.zone IN ("+zoneList+")"); - * } - * else { - * sql.append(" AND e.zone IN (").append("0").append(")"); - * } - */ - // Extract zones from getAccess - List zones = new ArrayList(); - for (Map access : getAccess) { - Object zoneObj = access.get("zone"); - if (zoneObj != null) { - zones.add(zoneObj.toString()); - } - } - - // If the user has zone access, add it to the WHERE clause - if (!zones.isEmpty()) { - StringBuilder zoneList = new StringBuilder(); - for (int i = 0; i < zones.size(); i++) { - zoneList.append("'").append(zones.get(i)).append("'"); - if (i < zones.size() - 1) { - zoneList.append(", "); - } - } - sql.append(" AND e.zone IN (").append(zoneList.toString()).append(")"); - } else { - sql.append(" AND e.zone IN (0)"); - } - sql.append( - " GROUP BY e.incharge_name, e.incharge_id, e.zone, sd.month, sd.year, sd.salary_status, e.department "); - sql.append(" ORDER BY sd.year DESC, sd.month DESC"); - /* - * try { - * List> result = jdbcTemplate.queryForList(sql.toString()); - * for (Map row : result) { - * String enrollmentIdsString = (String) row.get("enrollment_ids"); - * if (enrollmentIdsString != null) { - * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - * .map(String::trim) - * .filter(id -> !id.isEmpty()) - * .map(Integer::parseInt) - * .collect(Collectors.toList()); - * row.put("enrollment_ids", enrollmentIds); - * } - * } - * return result; - * } catch (Exception e) { - * e.printStackTrace(); - * return Collections.emptyList(); - * } - */ - - try { - List> result = jdbcTemplate.queryForList(sql.toString()); - - for (Map row : result) { - String enrollmentIdsString = (String) row.get("enrollment_ids"); - if (enrollmentIdsString != null) { - String[] parts = enrollmentIdsString.split(","); - List enrollmentIds = new ArrayList(); - for (int i = 0; i < parts.length; i++) { - String part = parts[i].trim(); - if (!part.isEmpty()) { - try { - enrollmentIds.add(Integer.parseInt(part)); - } catch (NumberFormatException nfe) { - // Ignore or log invalid integers - nfe.printStackTrace(); - } - } - } - row.put("enrollment_ids", enrollmentIds); - } - } - - return result; - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - - } - - //// - - public List> getFilteredSalaryDetails_park(String month, Integer year, String salaryStatus, - String loginId) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.incharge_name, " + - "e.incharge_id, " + - "e.zone, " + - "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - "COUNT(e.enrollment_id) AS total_staff_count, " + - "sd.month, " + - "sd.year, " + - "sd.salary_status, " + - "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + - "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + - "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " - + - "e.department " + // Select the department as well - "FROM enrollment_table e " + - "JOIN salary_details_park sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE 1=1 AND e.emp_type = 'Park' "); // Placeholder for dynamic conditions - - // Add filters for month, year, salary status, and department - if (month != null && !month.isEmpty()) { - sql.append(" AND sd.month = '").append(month).append("'"); - } - if (year != null) { - sql.append(" AND sd.year = ").append(year); - } - if (salaryStatus != null && !salaryStatus.isEmpty()) { - sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - } - - // Retrieve zone access for the user - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL + "->" + loginId); - // Extract the zones from getAccess - /* - * List zones = getAccess.stream() - * .map(access -> (String) access.get("zone")) - * .filter(Objects::nonNull) - * .collect(Collectors.toList()); - * - * // If the user has zone acc ess, add it to the WHERE clause - * if (!zones.isEmpty()) { - * String zoneList = zones.stream() - * .map(zone -> "'" + zone + "'") - * .collect(Collectors.joining(", ")); - * sql.append(" AND e.zone IN (").append(zoneList).append(")"); - * // System.out.println("AND e.zone IN ("+zoneList+")"); - * } - * else { - * sql.append(" AND e.zone IN (").append("0").append(")"); - * } - */ - // Extract zones from getAccess - List zones = new ArrayList(); - for (Map access : getAccess) { - Object zoneObj = access.get("zone"); - if (zoneObj != null) { - zones.add(zoneObj.toString()); - } - } - - // If the user has zone access, add it to the WHERE clause - if (!zones.isEmpty()) { - StringBuilder zoneList = new StringBuilder(); - for (int i = 0; i < zones.size(); i++) { - zoneList.append("'").append(zones.get(i)).append("'"); - if (i < zones.size() - 1) { - zoneList.append(", "); - } - } - sql.append(" AND e.zone IN (").append(zoneList.toString()).append(")"); - } else { - sql.append(" AND e.zone IN (0)"); - } - sql.append( - " GROUP BY e.incharge_name, e.incharge_id, e.zone, sd.month, sd.year, sd.salary_status, e.department "); - sql.append(" ORDER BY sd.year DESC, sd.month DESC"); - /* - * try { - * List> result = jdbcTemplate.queryForList(sql.toString()); - * for (Map row : result) { - * String enrollmentIdsString = (String) row.get("enrollment_ids"); - * if (enrollmentIdsString != null) { - * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - * .map(String::trim) - * .filter(id -> !id.isEmpty()) - * .map(Integer::parseInt) - * .collect(Collectors.toList()); - * row.put("enrollment_ids", enrollmentIds); - * } - * } - * return result; - * } catch (Exception e) { - * e.printStackTrace(); - * return Collections.emptyList(); - * } - */ - - try { - List> result = jdbcTemplate.queryForList(sql.toString()); - - for (Map row : result) { - String enrollmentIdsString = (String) row.get("enrollment_ids"); - if (enrollmentIdsString != null) { - String[] parts = enrollmentIdsString.split(","); - List enrollmentIds = new ArrayList(); - for (int i = 0; i < parts.length; i++) { - String part = parts[i].trim(); - if (!part.isEmpty()) { - try { - enrollmentIds.add(Integer.parseInt(part)); - } catch (NumberFormatException nfe) { - // Ignore or log invalid integers - nfe.printStackTrace(); - } - } - } - row.put("enrollment_ids", enrollmentIds); - } - } - - return result; - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - - } - - //// - - // public Integer checkInchargeID(Integer inchargeId) { - // - // String sql = "SELECT EXISTS( " + - // "SELECT 1 FROM additional_incharge " + - // "WHERE incharge_id = ? AND is_active = 1 AND is_delete = 0)"; - // - // Integer result = jdbcTemplate.queryForObject(sql, Integer.class, inchargeId); - // - // return result; - // } - - public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, - Integer incharge_id) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - + - "a.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "e.incharge_name, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " - + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - // Subquery to get total_days_od - "(SELECT COUNT(DISTINCT DATE(a2.oddatetime)) " + - " FROM attendance AS a2 " + - " WHERE MONTHNAME(a2.oddatetime) = ? " + // Use placeholder for month - " AND YEAR(a2.oddatetime) = ? " + // Use placeholder for year - " AND a2.enrollment_id = a.enrollment_id " + - " AND DATE(a2.oddatetime) NOT IN ( " + - " SELECT DISTINCT DATE(a3.indatetime) " + - " FROM attendance AS a3 " + - " WHERE MONTHNAME(a3.indatetime) = ? " + // Use placeholder for month - " AND YEAR(a3.indatetime) = ? " + // Use placeholder for year - " AND a3.enrollment_id = a.enrollment_id " + - ")) AS total_days_od, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Append condition for incharge_id - sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - - // Append condition for month if provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Append condition for year if provided - if (year != null) { - sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Group by necessary columns - sql.append("GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"); - - // Create a list of parameters - List params = new ArrayList<>(); - params.add(month); // Add month for total_days_od - params.add(year); // Add year for total_days_od - params.add(month); // Add month for the inner subquery - params.add(year); // Add year for the inner subquery - params.add(incharge_id); - params.add(incharge_id); // Added twice for the conditional check in the SQL - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Log the SQL and parameters (optional for debugging) - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query using JdbcTemplate - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /// - - public List> getAttendanceWithSalaryByInchargeId_New(String month, Integer year, - Integer incharge_id, String type, String ids) { - List> results = new ArrayList<>(); - if (type.equalsIgnoreCase("1")) { - results = getAttendanceWithSalaryByInchargeId_Nulm(month, year, incharge_id); - } else { - StringBuilder sql = new StringBuilder("SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - + - "a.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "e.incharge_name, " + - "(SELECT salary_per_day FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id) AS salary_per_day, " - + - "(SELECT wage_id FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id) AS wage_id, " - + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - // Subquery to get total_days_od - "(SELECT COUNT(DISTINCT DATE(a2.oddatetime)) " + - " FROM attendance AS a2 " + - " WHERE MONTHNAME(a2.oddatetime) = ? " + // Use placeholder for month - " AND YEAR(a2.oddatetime) = ? " + // Use placeholder for year - " AND a2.enrollment_id = a.enrollment_id " + - " AND DATE(a2.oddatetime) NOT IN ( " + - " SELECT DISTINCT DATE(a3.indatetime) " + - " FROM attendance AS a3 " + - " WHERE MONTHNAME(a3.indatetime) = ? " + // Use placeholder for month - " AND YEAR(a3.indatetime) = ? " + // Use placeholder for year - " AND a3.enrollment_id = a.enrollment_id " + - ")) AS total_days_od, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details_park AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) AND e.emp_type = 'Park' "); - - List params = new ArrayList<>(); - params.add(month); // Add month for total_days_od - params.add(year); // Add year for total_days_od - params.add(month); // Add month for the inner subquery - params.add(year); // Add year for the inner subquery - - // Append condition for incharge_id - // sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - if (ids != null && !ids.trim().isEmpty()) { - - List idList = Arrays.stream(ids.split(",")) - .map(String::trim) - .map(Integer::parseInt) - .toList(); - - String placeholders = idList.stream() - .map(i -> "?") - .collect(Collectors.joining(",")); - System.out.println("placeholders = " + placeholders); - - sql.append(" AND e.incharge_id IN (").append(placeholders).append(") "); - - System.out.println("idList = " + idList); - params.addAll(idList); - } - - // Append condition for month if provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - params.add(month); - } - - // Append condition for year if provided - if (year != null) { - sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - params.add(year); - } - - // Group by necessary columns - sql.append("GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id), " - + - "(SELECT wage_id FROM staff_wages_park WHERE isactive = 1 AND e.designation_id = staff_wages_park.designation_id), " - + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"); - - System.out.println("Query = " + sql); - - // Create a list of parameters - - // params.add(incharge_id); - // params.add(incharge_id); // Added twice for the conditional check in the SQL - // if (month != null && !month.isEmpty()) { - // params.add(month); - // } - // if (year != null) { - // params.add(year); - // } - - // Log the SQL and parameters (optional for debugging) - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query using JdbcTemplate - results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - return results; - } - - private List> getAttendanceWithSalaryByInchargeId_Nulm(String month, Integer year, - Integer incharge_id) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " - + - "a.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "e.incharge_name, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " - + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - // Subquery to get total_days_od - "(SELECT COUNT(DISTINCT DATE(a2.oddatetime)) " + - " FROM attendance AS a2 " + - " WHERE MONTHNAME(a2.oddatetime) = ? " + // Use placeholder for month - " AND YEAR(a2.oddatetime) = ? " + // Use placeholder for year - " AND a2.enrollment_id = a.enrollment_id " + - " AND DATE(a2.oddatetime) NOT IN ( " + - " SELECT DISTINCT DATE(a3.indatetime) " + - " FROM attendance AS a3 " + - " WHERE MONTHNAME(a3.indatetime) = ? " + // Use placeholder for month - " AND YEAR(a3.indatetime) = ? " + // Use placeholder for year - " AND a3.enrollment_id = a.enrollment_id " + - ")) AS total_days_od, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) AND e.emp_type = 'NULM' "); - - // Append condition for incharge_id - sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - - // Append condition for month if provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Append condition for year if provided - if (year != null) { - sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Group by necessary columns - sql.append("GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"); - - // Create a list of parameters - List params = new ArrayList<>(); - params.add(month); // Add month for total_days_od - params.add(year); // Add year for total_days_od - params.add(month); // Add month for the inner subquery - params.add(year); // Add year for the inner subquery - params.add(incharge_id); - params.add(incharge_id); // Added twice for the conditional check in the SQL - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Log the SQL and parameters (optional for debugging) - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query using JdbcTemplate - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - //// - - public List> getZoneWiseReport(String month, Integer year, String salaryStatus, - String groupName, String zone, String division) { - String sql = "select en.zone,en.division, en.emp_id, en.name, en.incharge_name, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " - + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " - + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " - + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " - + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " - + "where s.month = ? and s.year =? AND en.emp_type='NULM' " - + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") - + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "") - + (zone != null && !zone.isEmpty() ? "AND en.zone = ? " : "") - + (division != null && !division.isEmpty() ? "AND en.division = ? " : ""); - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /// - - public List> getZoneWiseReportPark(String month, Integer year, String salaryStatus, - String groupName, String zone, String division) { - String sql = "select en.zone,en.division, en.emp_id, en.name, en.incharge_name, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " - + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " - + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details_park s " - + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " - + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " - + "where s.month = ? and s.year =? AND en.emp_type='Park' " - + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") - + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "") - + (zone != null && !zone.isEmpty() ? "AND en.zone = ? " : "") - + (division != null && !division.isEmpty() ? "AND en.division = ? " : ""); - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /// - - public List> getAttendanceReport(String fromdate, String todate, String groupName, String zone, - String division) { - String sql = "select date_format(coalesce(att.indatetime, att.oddatetime, att.leavedatetime),'%d-%m-%Y') as attendance_date, et.emp_id, et.name, " - + " CASE WHEN att.indatetime IS NOT NULL THEN 'Present' WHEN att.leavedatetime IS NOT NULL THEN 'Absent' " - + " WHEN att.oddatetime IS NOT NULL THEN 'On Duty' ELSE 'No Record' END AS attendance_status, " - + " et.incharge_name,et.incharge_phoneno, et.incharge_designation, et.zone, et.division, et.department, sk.group_name from attendance att " - + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " - + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where " - + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d') " - + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d')" - + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d')) " - + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") - + (division != null && !division.isEmpty() ? " and et.division = ? " : "") - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /************************************** - * Updated code working 08-10-2024 - ******************************************/ - // public List> getAttendanceWithSalaryByInchargeId(String - // month, Integer year, Integer incharge_id) { - // StringBuilder sql = new StringBuilder("SELECT " + - // "e.group_id, " + - // "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = - // e.group_id LIMIT 1) AS group_name, " + - // "a.enrollment_id, " + - // "e.emp_id, " + - // "e.name, " + - // "e.incharge_id, " + - // "e.incharge_name, " + - // "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id - // DESC LIMIT 1) AS salary_per_day, " + - // "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC - // LIMIT 1) AS wage_id, " + - // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - // + - // "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS - // total_days, " + - // "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - // "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS - // total_days_salary, " + - // "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * - // " + - // "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id - // DESC LIMIT 1)) AS total_salary, " + - // "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - - // " + - // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) - // AS total_days_absent, " + - // "IFNULL(s.salary_status, '') AS salary_status " + - // "FROM attendance AS a " + - // "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - // "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - // "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, - // a.oddatetime)) " + - // "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - // "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) - // "); - // - // // Append condition for incharge_id - // sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - // - // // Append condition for month if provided - // if (month != null && !month.isEmpty()) { - // sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, - // a.oddatetime)) = ? "); - // } - // - // // Append condition for year if provided - // if (year != null) { - // sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = - // ? "); - // } - // - // // Group by necessary columns - // sql.append("GROUP BY a.enrollment_id, e.group_id, " + - // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - // "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id - // DESC LIMIT 1), " + - // "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC - // LIMIT 1), " + - // "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = - // e.group_id LIMIT 1), " + - // "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - // "s.salary_status"); - // - // // Create a list of parameters - // List params = new ArrayList<>(); - // params.add(incharge_id); - // params.add(incharge_id); // Added twice for the conditional check in the SQL - // if (month != null && !month.isEmpty()) { - // params.add(month); - // } - // if (year != null) { - // params.add(year); - // } - // - // // Log the SQL and parameters (optional for debugging) - // System.out.println("Generated SQL: " + sql.toString()); - // System.out.println("Parameters: " + params); - // - // // Execute the query using JdbcTemplate - // List> results = jdbcTemplate.queryForList(sql.toString(), - // params.toArray()); - // return results; - // } - - // public List> getAttendanceWithSalaryByInchargeId(String - // month, Integer year, Integer incharge_id) { - // StringBuilder sql = new StringBuilder("SELECT " + - // "e.enrollment_id, " + - // "e.emp_id, " + - // "e.name, " + - // "e.incharge_id, " + - // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - // + - // "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - // "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - // "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS - // total_days, " + - // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS - // total_days_salary, " + - // "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - - // " + - // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) - // AS total_days_absent, " + - // "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY - // sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + - // "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * - // " + - // "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY - // sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + - // "IFNULL(sd.salary_status, '') AS salary_status, " + // Modified salary_status - // to return an empty string - // "sk.group_id, " + - // "sk.group_name " + - // "FROM enrollment_table e " + - // "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - // "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - // "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - // "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) - // "); - // - // // Check if incharge_id is present - // sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - // - // // Check if month is provided - // if (month != null && !month.isEmpty()) { - // sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, - // a.oddatetime)) = ? "); - // } - // - // // Check if year is provided - // if (year != null) { - // sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = - // ? "); - // } - // - // // Updated GROUP BY to include all non-aggregated columns - // sql.append("GROUP BY e.enrollment_id, e.emp_id, e.name, e.incharge_id, " + - // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - // "sd.salary_status, sk.group_id, sk.group_name"); - // - // // Create a list of parameters - // List params = new ArrayList<>(); - // params.add(incharge_id); - // params.add(incharge_id); // Added twice for the conditional check in the SQL - // if (month != null && !month.isEmpty()) { - // params.add(month); - // } - // if (year != null) { - // params.add(year); - // } - // - // // Log SQL and parameters - // System.out.println("Generated SQL: " + sql.toString()); - // System.out.println("Parameters: " + params); - // - // // Execute the query - // List> results = jdbcTemplate.queryForList(sql.toString(), - // params.toArray()); - // return results; - // } - /* - * public List> getAttendanceWithSalaryByInchargeId(String - * month, Integer year, Integer incharge_id) { - * - * StringBuilder sql = new StringBuilder("SELECT " + - * "e.enrollment_id, " + - * "e.emp_id, " + - * "e.name, " + - * "e.incharge_id, " + - * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " - * + - * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - * "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + - * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " - * + - * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " - * + - * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " - * + - * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " - * + - * "COALESCE(sd.salary_status, '') AS salary_status, COALESCE(sk.group_id, '') AS group_id, " - * + - * "COALESCE(sk.group_name, '') AS group_name " + - * "FROM enrollment_table e " + - * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - * ); - * - * // Check if incharge_id is present - * sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - * - * // Check if month is provided - * if (month != null && !month.isEmpty()) { - * sql. - * append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " - * ); - * } - * - * // Check if year is provided - * if (year != null) { - * sql. - * append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " - * ); - * } - * - * sql. - * append("GROUP BY e.enrollment_id, e.name, YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), total_days, sd.salary_status, sk.group_id, sk.group_name" - * ); - * - * // Create a list of parameters - * List params = new ArrayList<>(); - * params.add(incharge_id); - * params.add(incharge_id); // Added twice for the conditional check in the SQL - * if (month != null && !month.isEmpty()) { - * params.add(month); - * } - * if (year != null) { - * params.add(year); - * } - * - * // Log SQL and parameters - * System.out.println("Generated SQL: " + sql.toString()); - * System.out.println("Parameters: " + params); - * - * // Execute the query - * List> results = jdbcTemplate.queryForList(sql.toString(), - * params.toArray()); - * return results; - * } - */ - - public List> getConsolidatedAttendanceReport(String fromdate, String todate, String groupName, - String zone, String division) { // newly added - String sql = "select \n" + - "et.emp_id, et.enrollment_id, et.name, " + - "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) AS total_days, " + - "count(distinct date(att.indatetime)) as totaldayspresent, " + - "count(distinct case when att.indatetime is null then date(att.oddatetime) end) as totaldaysod, " + - "count(distinct date(att.leavedatetime)) as totaldaysleave, " + - "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) - " + - "((count(distinct date(att.indatetime)) + " + - "count(distinct case when att.indatetime is null then date(att.oddatetime) end) + " + - "count(distinct date(att.leavedatetime)))) as totaldaysabsent, " + - "et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + - "et.division, et.department, sk.group_name from attendance att " - + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " - + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where et.emp_type='NULM' AND " - + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d') " - + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d')" - + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d')) " - + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") - + (division != null && !division.isEmpty() ? " and et.division = ? " : "") - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : "") - + " group by et.emp_id, et.enrollment_id, et.name, et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " - + " et.division, et.department, sk.group_name"; - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - // params.add(fromdate); - // params.add(todate); - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - /// - - public List> getParkConsolidatedAttendanceReport(String fromdate, String todate, String groupName, - String zone, String division) { // newly added - String sql = "select \n" + - "et.emp_id, et.enrollment_id, et.name, " + - "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) AS total_days, " + - "count(distinct date(att.indatetime)) as totaldayspresent, " + - "count(distinct case when att.indatetime is null then date(att.oddatetime) end) as totaldaysod, " + - "count(distinct date(att.leavedatetime)) as totaldaysleave, " + - "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) - " + - "((count(distinct date(att.indatetime)) + " + - "count(distinct case when att.indatetime is null then date(att.oddatetime) end) + " + - "count(distinct date(att.leavedatetime)))) as totaldaysabsent, " + - "et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + - "et.division, et.department, sk.group_name from attendance att " - + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " - + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where et.emp_type='Park' AND " - + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d') " - + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d')" - + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" - + todate + "', '%Y-%m-%d')) " - + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") - + (division != null && !division.isEmpty() ? " and et.division = ? " : "") - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : "") - + " group by et.emp_id, et.enrollment_id, et.name, et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " - + " et.division, et.department, sk.group_name"; - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - // params.add(fromdate); - // params.add(todate); - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - - /// - - - public Map> fetchAttendanceDates(String enrollmentId, String fromdate, String todate, - String type) { // newly added - Map> attendanceData = new HashMap<>(); - - if ("present".equals(type)) { - String presentQuery = "SELECT DISTINCT DATE_FORMAT(DATE(indatetime), '%d-%m-%Y') AS PresentDates " + - "FROM attendance WHERE enrollment_id = ? AND DATE(indatetime) BETWEEN STR_TO_DATE(? , '%Y-%m-%d') AND " - + - "STR_TO_DATE(? , '%Y-%m-%d')"; - attendanceData.put("presentDates", - jdbcTemplate.queryForList(presentQuery, String.class, enrollmentId, fromdate, todate)); - - } else if ("od".equals(type)) { - String odQuery = "SELECT DISTINCT DATE_FORMAT(DATE(oddatetime), '%d-%m-%Y') AS OdDates " + - "FROM attendance WHERE enrollment_id = ? AND DATE(oddatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; - attendanceData.put("odDates", - jdbcTemplate.queryForList(odQuery, String.class, enrollmentId, fromdate, todate)); - } else if ("leave".equals(type)) { - String leaveQuery = "SELECT DISTINCT DATE_FORMAT(DATE(leavedatetime), '%d-%m-%Y') AS LeaveDates " + - "FROM attendance WHERE enrollment_id = ? AND DATE(leavedatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; - attendanceData.put("leaveDates", - jdbcTemplate.queryForList(leaveQuery, String.class, enrollmentId, fromdate, todate)); - } else if ("absent".equals(type)) { - String absentQuery = ""; - - } - - return attendanceData; - } - - /// - - - - /// - - public List> getSelfHelpGroupDetails() { // newly added - String sql = "select * from suyaudavi_kuzhu where isactive = 1 and isdelete =0 order by group_name asc"; - List> results = jdbcTemplate.queryForList(sql); - return results; - } - - public List> getSalaryNotInitiatedReport(String month, Integer year, String groupName) { - - String sql = "SELECT e.emp_id, e.name, e.designation, e.incharge_name, e.incharge_designation, e.incharge_phoneno, sk.group_name " - + - "FROM enrollment_table e " + - "left join suyaudavi_kuzhu sk on e.group_id = sk.group_id " + - "WHERE e.emp_type='NULM' AND NOT EXISTS ( SELECT 1 " + - " FROM salary_details s " + - " WHERE e.enrollment_id = s.enrollment_id " + - " AND s.month = ? " + - " AND s.year = ? )" - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); - - List params = new ArrayList<>(); - - params.add(month); - params.add(year); - - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - /// - - public List> getSalaryNotInitiatedReportPark(String month, Integer year, String groupName) { - - String sql = "SELECT e.emp_id, e.name, e.designation, e.incharge_name, e.incharge_designation, e.incharge_phoneno, sk.group_name " - + - "FROM enrollment_table e " + - "left join suyaudavi_kuzhu sk on e.group_id = sk.group_id " + - "WHERE e.emp_type='Park' AND NOT EXISTS ( SELECT 1 " + - " FROM salary_details_park s " + - " WHERE e.enrollment_id = s.enrollment_id " + - " AND s.month = ? " + - " AND s.year = ? )" - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); - - List params = new ArrayList<>(); - - params.add(month); - params.add(year); - - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - /// - - public boolean checkSalaryDetails(int enrollmentId, String month, int year) { - String sql = "select enrollment_id from salary_details where enrollment_id =? and month = ? and year = ?"; - // boolean result = jdbcTemplate.update(sql, enrollmentId, month, year) == 1; - List results = jdbcTemplate.queryForList(sql, Integer.class, enrollmentId, month, year); - return !results.isEmpty(); - // return result; - } - - public int addSalaryDetails( - int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, - String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, int wageId, int inchargeID) { - String sql = "INSERT INTO salary_details (total_days_present, total_days_od, total_days_salary, total_days_absent, month, year, " - + "salary_amount, salary_status, enrollment_id, group_id, wage_id, incharge_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, - salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); - } - - public int updateSalaryDetails( - int totalDaysPresent, int totalDaysOd, int totalDaysSalary, - int totalDaysAbsent, String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, - int wageId, int inchargeID) { - String sql = "update salary_details set total_days_present =?, total_days_od=?, total_days_salary = ? , total_days_absent = ?, month = ?, year = ?, " - + "salary_amount = ?, salary_status = ?, enrollment_id = ?, group_id= ?, wage_id= ?, incharge_id = ? where enrollment_id =? and month = ? and year = ?) "; - - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, - salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID, enrollmentId, month, year); - } - - public String checkInchargeID(Integer inchargeId) { - - String sql = "SELECT " + - " CONCAT_WS( " + - " ',', " + - " GROUP_CONCAT(DISTINCT " + - " TRIM(SUBSTRING_INDEX(additional_id, ',', 1)) " + - " ), " + - " incharge_id " + - " ) AS final_ids " + - " FROM gcc_nulm.additional_incharge " + - " WHERE incharge_id = ? " + - " AND is_active = 1 " + - " AND is_delete = 0 " + - " GROUP BY incharge_id "; - - String result = jdbcTemplate.queryForObject(sql, String.class, inchargeId); - - return result; - } - - // ak - public List getZones() { - - String sql = "select distinct zone from park_details " + - "where is_active = 1 and is_delete = 0 order by zone"; - - return jdbcTemplate.queryForList(sql, Integer.class); - } - - // 2. Get Divisions by Zone - public List getDivisions(int zone) { - - String sql = "select distinct division from park_details " + - "where is_active = 1 and is_delete = 0 and zone = ? " + - "order by division"; - - return jdbcTemplate.queryForList(sql, Integer.class, zone); - } - - // 3. Get Parks by Zone and Division - /* - * public List> getParks(int zone, int division) { - * - * String sql = "select park_id, park_name from park_details " + - * "where is_active = 1 and is_delete = 0 " + - * "and zone = ? and division = ? " + - * "order by park_name"; - * - * return jdbcTemplate.queryForList(sql, zone, division); - * } - */ - public List> getParks(int zone, Integer division) { - - String sql = "select park_id, park_name from park_details " + - "where is_active = 1 and is_delete = 0 and zone = ? "; - - List params = new ArrayList<>(); - params.add(zone); - - if (division != null) { - sql += " and division = ? "; - params.add(division); - } - - sql += " order by park_name"; - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - public List> getStaffByPark(int parkId) { - - String sql = "select et.emp_id, et.enrollment_id, pd.park_name, " - + "et.name as empname, et.phone_number, " - + "et.designation, et.incharge_name " - + "from enrollment_table et " - + "left join park_details pd on et.park_id = pd.park_id " - + "where pd.park_id = ? " - + "and et.isactive = 1 " - + "and et.isdelete = 0 " - + "and pd.is_active = 1 " - + "and et.emp_type = 'Park'"; - - return jdbcTemplate.queryForList(sql, parkId); - } - - public Map getStaffDetails(int enrollmentId) { - - String sql = "select pd.park_name, et.incharge_name, et.name as name, et.designation,et.designation_id, " + - "ifnull(sk.group_name,'-') as groupname, et.aadhar_no, ifnull(et.f_h_name,'') as f_h_name, " + - "ifnull(et.bank_acc_no,'-') as bankaccNo, et.phone_number,et.not_found,et.error,et.remarks, " + - "ifnull(et.address,'-') as address, " + - "ifnull(et.bank_name,'') as bank_name, " + - "ifnull(et.ifsc_code,'') as ifsc_code, " + - "ifnull(et.branch,'') as branch, " + - "ifnull(et.branch_address,'') as branch_address, " + - "IFNULL(CONCAT('" + fileBaseUrl + "/gcc/files', et.form_url),'') AS formUrl, " + - "IFNULL(CONCAT('" + fileBaseUrl + "/gcc/files', et.bank_passbook_url),'') AS bankpassbookUrl, " + - "IFNULL(CONCAT('" + fileBaseUrl + "/gcc/files', et.aadhar_card_url),'') AS aadharUrl " + - "from enrollment_table et " + - "left join park_details pd on et.park_id = pd.park_id " + - "left join suyaudavi_kuzhu sk on et.group_id = sk.group_id " + - "where et.isactive = 1 and et.enrollment_id = ?"; - - return jdbcTemplate.queryForMap(sql, enrollmentId); - } - - /* - * public String updateStaff( - * int enrollmentId, - * String fhName, - * String designation, - * Integer designationId, - * String aadharNo, - * String bankAccNo, - * String phoneNumber, - * String address, - * MultipartFile uploadform, - * MultipartFile aadharcard, - * MultipartFile bankpassbook,String createdBy) { - * - * StringBuilder sql = new StringBuilder("UPDATE enrollment_table SET "); - * List params = new ArrayList<>(); - * - * if (fhName != null && !fhName.isEmpty()) { - * sql.append("f_h_name=?, "); - * params.add(fhName); - * } - * - * if (designation != null && !designation.isEmpty()) { - * sql.append("designation=?, "); - * params.add(designation); - * } - * - * if (designationId != null) { - * sql.append("designation_id=?, "); - * params.add(designationId); - * } - * - * if (aadharNo != null && !aadharNo.isEmpty()) { - * sql.append("aadhar_no=?, "); - * params.add(aadharNo); - * } - * - * if (bankAccNo != null && !bankAccNo.isEmpty()) { - * sql.append("bank_acc_no=?, "); - * params.add(bankAccNo); - * } - * - * if (phoneNumber != null && !phoneNumber.isEmpty()) { - * sql.append("phone_number=?, "); - * params.add(phoneNumber); - * } - * - * if (address != null && !address.isEmpty()) { - * sql.append("res_adress=?, "); - * params.add(address); - * } - * - * // File uploads - * if (uploadform != null && !uploadform.isEmpty()) { - * String path = fileUpload("uploadform", String.valueOf(enrollmentId), - * uploadform); - * sql.append("form_url=?, "); - * params.add(path); - * } - * - * if (aadharcard != null && !aadharcard.isEmpty()) { - * String path = fileUpload("aadharcard", String.valueOf(enrollmentId), - * aadharcard); - * sql.append("aadhar_card_url=?, "); - * params.add(path); - * } - * - * if (bankpassbook != null && !bankpassbook.isEmpty()) { - * String path = fileUpload("bankpassbook", String.valueOf(enrollmentId), - * bankpassbook); - * sql.append("bank_passbook_url=?, "); - * params.add(path); - * } - * - * // Remove last comma - * sql.setLength(sql.length() - 2); - * - * sql.append(" WHERE enrollment_id=?"); - * params.add(enrollmentId); - * - * jdbcTemplate.update(sql.toString(), params.toArray()); - * - * return "Updated Successfully"; - * } - */ - @Transactional - public String updateStaff( - int enrollmentId, - String fhName, - String designation, - Integer designationId, - String aadharNo, - String bankAccNo, - String bankName, - String ifscCode, - String branch, - String branchAddress, - String phoneNumber, - String address, - MultipartFile uploadform, - MultipartFile aadharcard, - MultipartFile bankpassbook, - Integer notFound, - Integer error, - String remarks, - String createdBy) { - - // 1️⃣ Fetch existing record - String fetchSql = "SELECT * FROM enrollment_table WHERE enrollment_id = ?"; - Map existing = jdbcTemplate.queryForMap(fetchSql, enrollmentId); - - // 2️⃣ Insert existing record into log table - String logSql = "INSERT INTO enrollment_table_log(" - + "enrollment_id,name,department,division,incharge_id,incharge_name,incharge_designation,RFID_CARD_NO," - + "designation,incharge_phoneno,emp_id,isactive,isdelete,created_date,appointed,facial_attendance," - + "staff_photo_url,order_id,group_id,dropout_date,dropout,registered_date,appointed_date,res_adress," - + "f_h_name,form_url,bank_passbook_url,bank_acc_no,ration_card_url,aadhar_no,aadhar_card_url," - + "additional_skills,education_qualification,address,phone_number,gender,date_of_birth,zone," - + "remarks,emp_type,park_name,park_id,designation_id,not_found,error,updatedby,bank_name,ifsc_code,branch,branch_address)" - + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - jdbcTemplate.update(logSql, - - existing.get("enrollment_id"), - existing.get("name"), - existing.get("department"), - existing.get("division"), - existing.get("incharge_id"), - existing.get("incharge_name"), - existing.get("incharge_designation"), - existing.get("RFID_CARD_NO"), - existing.get("designation"), - existing.get("incharge_phoneno"), - existing.get("emp_id"), - existing.get("isactive"), - existing.get("isdelete"), - existing.get("created_date"), - existing.get("appointed"), - existing.get("facial_attendance"), - existing.get("staff_photo_url"), - existing.get("order_id"), - existing.get("group_id"), - existing.get("dropout_date"), - existing.get("dropout"), - existing.get("registered_date"), - existing.get("appointed_date"), - existing.get("res_adress"), - existing.get("f_h_name"), - existing.get("form_url"), - existing.get("bank_passbook_url"), - existing.get("bank_acc_no"), - existing.get("ration_card_url"), - existing.get("aadhar_no"), - existing.get("aadhar_card_url"), - existing.get("additional_skills"), - existing.get("education_qualification"), - existing.get("address"), - existing.get("phone_number"), - existing.get("gender"), - existing.get("date_of_birth"), - existing.get("zone"), - existing.get("remarks"), - existing.get("emp_type"), - existing.get("park_name"), - existing.get("park_id"), - // existing.get("designation_id"), - existing.get("designation_id") == null ? 0 : existing.get("designation_id"), - existing.get("not_found"), - existing.get("error"), - - createdBy, - existing.get("bank_name"), - existing.get("ifsc_code"), - existing.get("branch"), - existing.get("branch_address")); - - // 3️⃣ Build dynamic update query - StringBuilder sql = new StringBuilder("UPDATE enrollment_table SET "); - List params = new ArrayList<>(); - - if (fhName != null && !fhName.isEmpty()) { - sql.append("f_h_name=?, "); - params.add(fhName); - } - - if (designation != null && !designation.isEmpty()) { - sql.append("designation=?, "); - params.add(designation); - } - - if (designationId != null) { - sql.append("designation_id=?, "); - params.add(designationId); - } - - if (aadharNo != null && !aadharNo.isEmpty()) { - sql.append("aadhar_no=?, "); - params.add(aadharNo); - } - - if (bankAccNo != null && !bankAccNo.isEmpty()) { - sql.append("bank_acc_no=?, "); - params.add(bankAccNo); - } - // ak - if (bankName != null && !bankName.isEmpty()) { - sql.append("bank_name=?, "); - params.add(bankName); - } - - if (ifscCode != null && !ifscCode.isEmpty()) { - sql.append("ifsc_code=?, "); - params.add(ifscCode); - } - - if (branch != null && !branch.isEmpty()) { - sql.append("branch=?, "); - params.add(branch); - } - - if (branchAddress != null && !branchAddress.isEmpty()) { - sql.append("branch_address=?, "); - params.add(branchAddress); - } - - if (phoneNumber != null && !phoneNumber.isEmpty()) { - sql.append("phone_number=?, "); - params.add(phoneNumber); - } - - if (address != null && !address.isEmpty()) { - sql.append("address=?, "); - params.add(address); - } - - // 4️⃣ File Upload Handling - - if (uploadform != null && !uploadform.isEmpty()) { - String path = fileUpload("uploadform", String.valueOf(enrollmentId), uploadform); - sql.append("form_url=?, "); - params.add(path); - } - - if (aadharcard != null && !aadharcard.isEmpty()) { - String path = fileUpload("aadharcard", String.valueOf(enrollmentId), aadharcard); - sql.append("aadhar_card_url=?, "); - params.add(path); - } - - if (bankpassbook != null && !bankpassbook.isEmpty()) { - String path = fileUpload("bankpassbook", String.valueOf(enrollmentId), bankpassbook); - sql.append("bank_passbook_url=?, "); - params.add(path); - } - if (notFound != null) { - sql.append("not_found=?, "); - params.add(notFound); - } - - if (error != null) { - sql.append("error=?, "); - params.add(error); - } - - if (remarks != null) { - sql.append("remarks=?, "); - params.add(remarks); - } - - // Remove last comma - sql.setLength(sql.length() - 2); - - sql.append(" WHERE enrollment_id=?"); - params.add(enrollmentId); - - jdbcTemplate.update(sql.toString(), params.toArray()); - - return "Staff updated successfully"; - } - - 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("nulm_foldername"); - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - var date = DateTimeUtil.getCurrentDay(); - - uploadDirectory = uploadDirectory + serviceFolderName + "/" + year + "/" + month + "/" + date; - - try { - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - // Datetime string - String datetimetxt = DateTimeUtil.getCurrentDateTime(); - // File name - System.out.println(file.getOriginalFilename()); - String fileName = name + "_" + id + "_" + datetimetxt + "_" - + file.getOriginalFilename(); - fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename - - String filePath = uploadDirectory + "/" + fileName; - - String filepath_txt = "/" + serviceFolderName + "/" + year + "/" + month + "/" + date + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Compress the image - BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); - byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality - - // Write the bytes to the file - Files.write(path, bytes); - - System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - 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 boolean hasStaffUpdateAccess(String LoginUserId) { - - String sql = "SELECT COUNT(*) FROM login_mapping_1913 " + - "WHERE appuser_id = ? AND isactive = 1 AND isdelete = 0"; - - Integer count = jdbcTemplate.queryForObject(sql, Integer.class, LoginUserId); - - return count != null && count > 0; - } - - public List> getDesignations() { - - String sql = "SELECT designation_id, designation " + - "FROM designation_master " + - "WHERE is_active = 1 AND is_delete = 0"; - - return jdbcTemplate.queryForList(sql); - } - - /* - * public List> getParks() { - * - * String sql = - * "SELECT park_id, park_name, supervisor_name, supervisor_id,zone,supervisor_designation,supervisor_mobile " - * + - * "FROM park_details WHERE is_active = 1"; - * - * return jdbcTemplate.queryForList(sql); - * } - */ - public List> getParks(int zone) { - - String sql = "SELECT park_id, park_name, supervisor_name, supervisor_id, zone, supervisor_designation, supervisor_mobile " - + "FROM park_details " - + "WHERE is_active = 1 AND zone = ?"; - - return jdbcTemplate.queryForList(sql, zone); - } - - @Transactional - public Map createEmployee( - - String name, - String fhName, - String designation, - Integer designationId, - String aadharNo, - String bankAccNo, - String phoneNumber, - String address, - String bankName, - String ifscCode, - String branch, - String branchAddress, - Integer parkId, - String parkName, - Integer inchargeId, - String inchargeName, - Integer zone, - String inchargeDesignation, - String inchargePhone, - - MultipartFile uploadform, - MultipartFile aadharcard, - MultipartFile bankpassbook) { - - Map response = new HashMap<>(); - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - String insertSql = "INSERT INTO enrollment_table (" + - "name,f_h_name,designation,designation_id," + - "aadhar_no,bank_acc_no,phone_number,address," + - "bank_name,ifsc_code,branch,branch_address," + - "park_id,park_name,incharge_id,incharge_name," + - "zone,emp_type,incharge_designation,incharge_phoneno,appointed,registered_date,appointed_date) " - + - "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'Park',?,?,1,now(),now())"; - - jdbcTemplate.update(connection -> { - - PreparedStatement ps = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); - - ps.setString(1, name); - ps.setString(2, fhName); - ps.setString(3, designation); - ps.setInt(4, designationId); - ps.setString(5, aadharNo); - ps.setString(6, bankAccNo); - ps.setString(7, phoneNumber); - ps.setString(8, address); - ps.setString(9, bankName); - ps.setString(10, ifscCode); - ps.setString(11, branch); - ps.setString(12, branchAddress); - ps.setInt(13, parkId); - ps.setString(14, parkName); - ps.setInt(15, inchargeId); - ps.setString(16, inchargeName); - ps.setInt(17, zone); - ps.setString(18, inchargeDesignation); - ps.setString(19, inchargePhone); - // ps.setString(20, createdBy); - - return ps; - - }, keyHolder); - - int enrollmentId = keyHolder.getKey().intValue(); - - String empSql = "SELECT IFNULL(MAX(emp_id),0) FROM enrollment_table where emp_type = 'Park' "; - - Integer lastEmpId = jdbcTemplate.queryForObject(empSql, Integer.class); - int employeeId = lastEmpId + 1; - - /* - * ============================= - * FILE UPLOAD SECTION - * ============================= - */ - - StringBuilder sql = new StringBuilder("UPDATE enrollment_table SET "); - List params = new ArrayList<>(); - - if (uploadform != null && !uploadform.isEmpty()) { - - String path = fileUpload("uploadform", String.valueOf(enrollmentId), uploadform); - - sql.append("form_url=?, "); - params.add(path); - } - - if (aadharcard != null && !aadharcard.isEmpty()) { - - String path = fileUpload("aadharcard", String.valueOf(enrollmentId), aadharcard); - - sql.append("aadhar_card_url=?, "); - params.add(path); - } - - if (bankpassbook != null && !bankpassbook.isEmpty()) { - - String path = fileUpload("bankpassbook", String.valueOf(enrollmentId), bankpassbook); - - sql.append("bank_passbook_url=?, "); - params.add(path); - } - - sql.append("emp_id=? "); - params.add(employeeId); - - sql.append("WHERE enrollment_id=?"); - params.add(enrollmentId); - - jdbcTemplate.update(sql.toString(), params.toArray()); - - response.put("status", "success"); - response.put("employeeId", employeeId); - - return response; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/package-info.java deleted file mode 100644 index 56a1d9f8..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.nulm.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/.DS_Store deleted file mode 100644 index 218c415f..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/.DS_Store deleted file mode 100644 index 3d00a872..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/CompletedApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/CompletedApiController.java deleted file mode 100644 index e3fcc3cf..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/CompletedApiController.java +++ /dev/null @@ -1,56 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.Map; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.CompletedService; - -@RequestMapping("gcc/api/department/completed") -@RestController -public class CompletedApiController { - - @Autowired - private CompletedService completedService; - - @Autowired - public CompletedApiController(CompletedService completedService) { - this.completedService = completedService; - } - - // Combined method to handle both cases (with and without emp_no parameter) - @GetMapping("/cpslist") - public ResponseEntity getCPSList(@RequestParam(value = "emp_no", required = false) String empNo, - @RequestParam(required = false)Integer file_cat, - @RequestParam(required = false)Integer deptId) { - try { - List> cpsList; - - // If emp_no is provided, fetch filtered records - if (empNo != null && !empNo.isEmpty()) { - cpsList = completedService.getCPSListByEmpNo(empNo); - } else { - // If emp_no is not provided, fetch all records - cpsList = completedService.getCPSList(file_cat,deptId); - } - - // Return response based on the data - if (cpsList.isEmpty()) { - return ResponseEntity.noContent().build(); // No records found - } - - return ResponseEntity.ok(cpsList); // Return the records - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error occurred while fetching completed service records."); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DashboardApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DashboardApiController.java deleted file mode 100644 index c6971a86..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DashboardApiController.java +++ /dev/null @@ -1,149 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DashboardApiService; - -@RequestMapping("/gcc/api/pensionerdashboard") -@RestController -public class DashboardApiController { - @Autowired - private DashboardApiService dashboardApiService; - - @GetMapping("/dashboard") - //@ResponseBody - public List> getDashboardData() { - - return dashboardApiService.fetchCategoryCounts(); - } - - - @GetMapping("/getDepartments") - //@ResponseBody - public List> getDepartment() { - return dashboardApiService.getDepartment(); - } - - @GetMapping("/getEmpNoByFileName") - public List> getEmployeeDetails(@RequestParam("file_id") String FileId) { - //System.out.println("before fetch"); - return dashboardApiService.getEmployeeDetails(FileId); - } - - - //department - - @GetMapping("/departmentdashboard") - //@ResponseBody - public List> getDepartmentDashboardData(@RequestParam(required = false) String deptId) { - //System.out.println("deptid"+ deptId); - return dashboardApiService.DepartmenfetchCategoryCounts(deptId); - } - - - - - - @GetMapping("/stageWiseCounts") - public ResponseEntity>> getDepartmentStageWiseCounts( - @RequestParam(required = false) String deptId, - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - if(startDate.isEmpty()) - { - startDate=null; - } - if(endDate.isEmpty()) - { - endDate=null; - } - List> stageWiseCounts = dashboardApiService.getStageWiseCounts(deptId, startDate, endDate); - - return ResponseEntity.ok(stageWiseCounts); - } - - @GetMapping("/categoryCounts") - public List> getDepartmenCategoryCounts( - @RequestParam(required = false) String deptId, - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate) { - - if(startDate.isEmpty()) - { - startDate=null; - } - if(endDate.isEmpty()) - { - endDate=null; - } - - return dashboardApiService.fetchchartCategoryCounts(deptId, startDate, endDate); - } - - @GetMapping("/dashboardsearch") - //@ResponseBody - public List> fetchDeparmentDashboardData( - @RequestParam(required = false) String startdate, - @RequestParam(required = false) String enddate,@RequestParam(required = false) String deptId) { - if(deptId.isEmpty()) - { - deptId=null; - } - - //System.out.println("Endpoint hit with startdate: " + startdate + ", enddate: " + enddate); - try { - return dashboardApiService.fetchCategorysearchCounts(startdate, enddate,deptId); - } catch (Exception e) { - e.printStackTrace(); // Print fetchCategoryCounts stack trace to the logs - throw e; // Rethrow the exception to propagate the 500 error - } - } - -//pension - - @GetMapping("/pensiondashboard") - //@ResponseBody - public List> getPensionDashboardData(@RequestParam(required = false) String deptId) { - //System.out.println("deptid"+ deptId); - return dashboardApiService.DepartmenfetchCategoryCounts(deptId); - } - - - @GetMapping("/fetchEmpDetails") - public List> getEmpDetails(@RequestParam(required = false) String Empcode) { - //System.out.println("checking"); - //System.out.println(Empcode); - - return dashboardApiService.getEmpDetails(Empcode); - } - - @GetMapping("/fetchPensionEmpDetails") - public List> getPensionEmpDetails(@RequestParam(required = false) String Empcode) { - //System.out.println("checking"); - //System.out.println(Empcode); - - return dashboardApiService.getPensionEmpDetails(Empcode); - } - - - @GetMapping("/fetchTempDetails") - public List> getTempEmpDetails(@RequestParam(required = false) String tempId) { - // System.out.println("checking"); - // System.out.println(tempId); - - return dashboardApiService.getTempEmpDetails(tempId); - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentForwardApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentForwardApiController.java deleted file mode 100644 index ea0bec5e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentForwardApiController.java +++ /dev/null @@ -1,129 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DepartmentForwardService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; - -@RequestMapping("gcc/api/pension/forward") -@RestController -public class DepartmentForwardApiController { - - @Autowired - private DeptAuditService deptAuditService; - - @Autowired - private DepartmentForwardService departmentForwardService; - - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - boolean isSaved = departmentForwardService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=departmentForwardService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File Forward to Department successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - //family pension - @PostMapping("/updateForwardFamilyPension") - public ResponseEntity updateForwardFamilyPension(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = departmentForwardService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=departmentForwardService.saveFamilyPensionForwardHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File Forward to Department successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - @PostMapping("/updateForwardPendency") - public ResponseEntity updateForwardPendency(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = departmentForwardService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=departmentForwardService.savePendencyForwardHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File Forward to Department successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentMainController.java deleted file mode 100644 index 63d8c572..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentMainController.java +++ /dev/null @@ -1,720 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; - -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.CompletedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DepartmentForwardService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DepartmentReceivedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptPartiallyCompService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.NewEntryService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionReceivedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReceivedDeptProvisionalService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReturnFromAuditService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/department") -@Controller("gccpensioner") -public class DepartmentMainController { - - @Autowired - private NewEntryService newEntryService; - - @Autowired - private DeptAuditService deptAuditService; - - @Autowired - private ReturnFromAuditService returnFromAuditService; - - @Autowired - private PensionAuditService pensionAuditService; - - @Autowired - private DepartmentForwardService departmentForwardService; - - @Autowired - private PensionReceivedService pensionReceivedService; - - @Autowired - private DepartmentReceivedService departmentReceivedService; - - @Autowired - private ReceivedDeptProvisionalService receivedDeptProvisionalService; - - @Autowired - private CompletedService completedService; - - @Autowired - public DeptPartiallyCompService deptPartiallyCompleteService; - - - - //////////////////////department pages///////////////////////////////// - - //yogi - @GetMapping("/newentry/retirement") - public String newentryretirement( Model model) { - - - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - return "modules/pensioner/department/newentry/retirement"; - } - - - @GetMapping("/newentry/familypension") - public String newentryfamilypension(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - return "modules/pensioner/department/newentry/familypension"; - } - - - @GetMapping("/newentry/pendency") - public String newentrypendency(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - return "modules/pensioner/department/newentry/pendency"; - } - - - - @GetMapping("/newentry/gis") - public String newentrygis(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getGISFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - return "modules/pensioner/department/newentry/gis"; - } - - - @GetMapping("/newentry/provisionalretirement") - public String newentryprovisional(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getPRFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - return "modules/pensioner/department/newentry/provisionalretirement"; - } - - - @GetMapping("/newentry/contributorypensionscheme") - public String newentrycontributory(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getCPSFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - return "modules/pensioner/department/newentry/contributorypensionscheme"; - } - - - //sanjay//////////////AUDIT LIST PAGES////////////////// - - @GetMapping("/audit/retirement") - public String auditretirement(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>auditlist=deptAuditService.fetchEmployeeDetailsByTable(deptId,file_cat); - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/department/audit/retirement"; - } - - - @GetMapping("/audit/familypension") - public String auditfamilypension(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>auditlist=deptAuditService.fetchEmployeeDetailsByTable(deptId,file_cat); - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - - return "modules/pensioner/department/audit/familypension"; - } - - - @GetMapping("/audit/pendency") - public String auditpendency(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>auditlist=deptAuditService.fetchEmployeeDetailsByTable(deptId,file_cat); - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/department/audit/pendency"; - } - - - ///////////////////PARTIAL LIST PAGES////////////////////// - - @GetMapping("/partial/retirement") - public String partialretirement(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>auditlist=deptPartiallyCompleteService.fetchDepatmentPartialEmpfiles(deptId,file_cat); - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/department/partial/retirement"; - } - - @GetMapping("/partial/familypension") - public String partialfamilypension(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>auditlist=deptPartiallyCompleteService.fetchDepatmentPartialEmpfiles(deptId,file_cat); - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/department/partial/familypension"; - } - - @GetMapping("/partial/pendency") - public String partialpendency(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>auditlist=deptPartiallyCompleteService.fetchDepatmentPartialEmpfiles(deptId,file_cat); - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/department/partial/pendency"; - } - - - - //dizho/////////////RETURN LIST PAGES////////////////// - - @GetMapping("/return/retirement") - public String returnretirement(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>returnlist=returnFromAuditService.fetchReturnEmpfiles(deptId,file_cat); - System.out.println("returnlist===="+returnlist); - model.addAttribute("returnlist", returnlist); - - return "modules/pensioner/department/return/retirement"; - } - - - @GetMapping("/return/familypension") - public String returnfamilypension(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>returnlist=returnFromAuditService.fetchReturnEmpfiles(deptId,file_cat); - System.out.println("returnlist===="+returnlist); - model.addAttribute("returnlist", returnlist); - - return "modules/pensioner/department/return/familypension"; - } - - - @GetMapping("/return/pendency") - public String returnpendency(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>returnlist=returnFromAuditService.fetchReturnEmpfiles(deptId,file_cat); - System.out.println("returnlist===="+returnlist); - model.addAttribute("returnlist", returnlist); - - return "modules/pensioner/department/return/pendency"; - } - - //////////////////RECEIVED LIST PAGES///////////////////// - - - @GetMapping("/received/retirement") - public String receivedretirement(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>receivedlist=pensionReceivedService.fetchReceivedDepartmentEmpfiles(deptId,file_cat); - System.out.println("receivedlist===="+receivedlist); - model.addAttribute("receivedlist", receivedlist); - - return "modules/pensioner/department/received/retirement"; - } - - - @GetMapping("/received/familypension") - public String receivedfamilypension(Model model) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>receivedlist=pensionReceivedService.fetchReceivedDepartmentEmpfiles(deptId,file_cat); - System.out.println("receivedlist===="+receivedlist); - model.addAttribute("receivedlist", receivedlist); - - return "modules/pensioner/department/received/familypension"; - } - - - - @GetMapping("/received/pendency") - public String receivedpendency(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - List>receivedlist=pensionReceivedService.fetchReceivedDepartmentEmpfiles(deptId,file_cat); - System.out.println("receivedlist===="+receivedlist); - model.addAttribute("receivedlist", receivedlist); - - return "modules/pensioner/department/received/pendency"; - } - - - @GetMapping("/received/provisionalretirement") - public String receivedprovisionalretirement(Model model) { - int file_cat= newEntryService.getPRFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>provisionallist= receivedDeptProvisionalService.fetchDetailsProvisionalDepartment(file_cat); - - System.out.println("provisionallist===="+provisionallist); - model.addAttribute("provisionallist", provisionallist); - - return "modules/pensioner/department/received/provisionalretirement"; - } - - - ////////////////COMPLETED LIST PAGES///////////////////////////// - - @GetMapping("/completed/retirement") - public String completedretirement(Model model) { - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>retirementcompletedlist= completedService.fetchDetailsCompletedRetirement(file_cat,deptId); - - System.out.println("provisionallist"+retirementcompletedlist); - model.addAttribute("provisionallist", retirementcompletedlist); - - return "modules/pensioner/department/completed/retirement"; - } - - - @GetMapping("/completed/familypension") - public String completedfamilypension(Model model) { - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>familypensioncompletedlist= completedService.fetchDetailsCompletedFamilyPension(file_cat,deptId); - - System.out.println("provisionallist===="+familypensioncompletedlist); - model.addAttribute("provisionallist", familypensioncompletedlist); - - return "modules/pensioner/department/completed/familypension"; - } - - - @GetMapping("/completed/pendency") - public String completedpendency(Model model) { - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>pendencycompletedlist= completedService.fetchDetailsCompletedPendency(file_cat,deptId); - - System.out.println("provisionallist===="+pendencycompletedlist); - model.addAttribute("provisionallist", pendencycompletedlist); - - return "modules/pensioner/department/completed/pendency"; - } - - - @GetMapping("/completed/gis") - public String completedgis(Model model) { - int file_cat= newEntryService.getGISFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>gislist= completedService.fetchDetailsForrecivedGiscompleted(file_cat,deptId); - - System.out.println("auditlist===="+gislist); - model.addAttribute("auditlist", gislist); - - return "modules/pensioner/department/completed/gis"; - } - - @GetMapping("/completed/provisionalretirement") - public String completedprovisionalretirement(Model model) { - int file_cat= newEntryService.getPRFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>provisionallist= completedService.fetchDetailsProvisionalDepartmentCompleted(file_cat,deptId); - - System.out.println("provisionallist===="+provisionallist); - model.addAttribute("provisionallist", provisionallist); - - return "modules/pensioner/department/completed/provisionalretirement"; - } - - - - @GetMapping("/completed/contributorypensionscheme") - public String completedContributoryPensionScheme( - - Model model) { - // Get logged-in user details - - int file_cat= newEntryService.getCPSFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>completedCPSList= completedService.getCPSList(file_cat,deptId); - - System.out.println("provisionallist===="+completedCPSList); - model.addAttribute("provisionallist", completedCPSList); - // Add the list to the model - model.addAttribute("completedCPSList", completedCPSList); - - return "modules/pensioner/department/completed/contributorypensionscheme"; - } - - - - //Ajith ////////////////REPORTS LIST PAGES////////////////////// - - @GetMapping("/reports") - public String reports(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - return "modules/pensioner/department/reports"; - } - - - @GetMapping("/dashboard") - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - - return "modules/pensioner/department/dashboard"; - } - - -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentReceivedApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentReceivedApiController.java deleted file mode 100644 index b4b71d2c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentReceivedApiController.java +++ /dev/null @@ -1,176 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DepartmentReceivedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; - -@RequestMapping("gcc/api/pension/received") -@RestController -public class DepartmentReceivedApiController { - - @Autowired - private DeptAuditService deptAuditService; - - @Autowired - private DepartmentReceivedService departmentReceivedService; - - @PostMapping("/updateforretirementcompleted") - public ResponseEntity updateRetirementEmployeeDetailsCompleted(@RequestBody Map requestData) { - try { - // Extract request parameters - String tempId = (String) requestData.get("tempId"); - String filemovedby = (String) requestData.get("filemovedby"); - int file_Status = 0; // Initialize file_status - - // Call service method to save the details - boolean isSaved = departmentReceivedService.updateEntryCompletedDetails(requestData); - - if (isSaved) { - // Fetch employee details - List> emp_details = deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:" + emp_details); - - // Fetch pension benefits details - List> pension_details = departmentReceivedService.fetchPensionbenefitsById(tempId); - System.out.println("pension_details:==:" + pension_details); - - // Save retirement completed history - boolean updated = departmentReceivedService.saveRetirementCompletedhistory(emp_details, pension_details, filemovedby); - - // Retrieve file_status from emp_details - if (!emp_details.isEmpty()) { - Map firstEmployeeDetails = emp_details.get(0); - Object fileStatusObj = firstEmployeeDetails.get("file_status"); - - if (fileStatusObj != null) { - try { - file_Status = Integer.parseInt(fileStatusObj.toString()); - System.out.println("Parsed file_status: " + file_Status); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_status: " + fileStatusObj); - } - } else { - System.out.println("file_status is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - // Final response logic - if (updated && file_Status != 0) { - if (file_Status == 11) { - return ResponseEntity.ok("File Completed successfully!"); - } else if(file_Status == 9) { - //return ResponseEntity.ok("File Moved Department to Complete Pending fields!"); - return ResponseEntity.ok("File Moved to Department Partially Completed!"); - } - else { - //return ResponseEntity.ok("File Moved Department to Complete Pending fields!"); - return ResponseEntity.ok("File Moved to Pension Partially Completed!"); - } - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to save details in history or invalid file_status."); - } - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details for completed."); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error occurred while saving details."); - } - } - - - @PostMapping("/updateforretirementpending") - public ResponseEntity updateRetirementEmployeeDetailsPending(@RequestBody Map requestData) { - try { - // Extract request parameters - String tempId = (String) requestData.get("tempId"); - String filemovedby = (String) requestData.get("filemovedby"); - - - // Call service method to save the details - boolean isSaved = departmentReceivedService.updateEntryPendingDetails(requestData); - - if (isSaved) { - // Fetch employee details - List> emp_details = deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:" + emp_details); - - // Fetch pension benefits details - List> pension_details = departmentReceivedService.fetchPensionbenefitsById(tempId); - System.out.println("pension_details:==:" + pension_details); - - // Save retirement completed history - boolean updated = departmentReceivedService.saveRetirementPendinghistory(emp_details, pension_details, filemovedby); - - if(updated) - { - return ResponseEntity.ok("File is Pending!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details for pending."); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error occurred while saving details."); - } - } - - - @PostMapping("/updateforretirementreturn") - public ResponseEntity updateRetirementEmployeeDetailsReturn(@RequestBody Map requestData) { - try { - // Extract request parameters - String tempId = (String) requestData.get("tempId"); - String filemovedby = (String) requestData.get("filemovedby"); - - - // Call service method to save the details - boolean isSaved = departmentReceivedService.updateEntryReturnDetails(requestData); - - if (isSaved) { - // Fetch employee details - List> emp_details = deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:" + emp_details); - - // Save retirement completed history - boolean updated = departmentReceivedService.saveRetirementreturnhistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File Returned to Department!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details for pending."); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptAuditApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptAuditApiController.java deleted file mode 100644 index f2077185..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptAuditApiController.java +++ /dev/null @@ -1,189 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; - -@RequestMapping("gcc/api/department/audit") -@RestController -public class DeptAuditApiController { - - @Autowired - private DeptAuditService deptAuditService; - - - @GetMapping("/getemployeedetails") - public List> getEmployeedetailsbyCode( - @RequestParam String tempId) { - - List> employeeDetails = deptAuditService.fetchEmployeeById(tempId); - System.out.println("employeeDetails==="+employeeDetails); - return employeeDetails; - } - - - - @GetMapping("/getemployeedetailscps") - public List> getEmployeedetailsbyCodeCps( - @RequestParam String tempId) { - - List> employeeDetails = deptAuditService.fetchEmployeeByIdCps(tempId); - System.out.println("employeeDetails==="+employeeDetails); - return employeeDetails; - } - - @GetMapping("/getzonebenefitsdetails") - public List> getdetailsWithZonebenefits( - @RequestParam String tempId) { - - List> zoneBenefitDetails = deptAuditService.fetchDetailsWithZoneBenefitsById(tempId); - System.out.println("zoneBenefitDetails==="+zoneBenefitDetails); - return zoneBenefitDetails; - } - - @GetMapping("/getfilependingbenefits") - public List> getAllBenefitsDetails( - @RequestParam String tempId) { - - List> allBenefitDetails = deptAuditService.fetchFilePendingBenefits(tempId); - System.out.println("allBenefitDetails==="+allBenefitDetails); - return allBenefitDetails; - } - - @GetMapping("/getpartialdetails") - public List> getAllPartialDetails( - @RequestParam String tempId) { - - List> partialDetails = deptAuditService.fetchPartialCompleted(tempId); - System.out.println("partialDetails==="+partialDetails); - return partialDetails; - } - - - - @GetMapping("/fileMovementhistory") - public List> getFileMovementHistory(@RequestParam String tempId) { - List> fileHistory = deptAuditService.fetchFileMovementHistory(tempId); - - return fileHistory; - } - - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = deptAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=deptAuditService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File moved to Return from Audit successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - //update the family pension details - - @PostMapping("/updateFamilyPensionDetails") - public ResponseEntity updateFamilyPensionDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = deptAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=deptAuditService.saveFamilyPensionHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File moved to Return from Audit successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - //pendency - @PostMapping("/updatePendencyDetails") - public ResponseEntity updatePendencyDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = deptAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=deptAuditService.savePendencyHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File moved to Return from Audit successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptPartiallyCompApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptPartiallyCompApiController.java deleted file mode 100644 index b8df21d1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptPartiallyCompApiController.java +++ /dev/null @@ -1,110 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptPartiallyCompService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionReceivedService; - -@RequestMapping("gcc/api/department/partial") -@RestController -public class DeptPartiallyCompApiController { - - @Autowired - public DeptPartiallyCompService deptPartiallyCompleteService; - - @Autowired - public DeptAuditService deptAuditService; - - @Autowired - public PensionReceivedService pensionReceivedService; - - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - int fs1=0; - - boolean isSaved = deptPartiallyCompleteService.updateEntryCompletedDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchPartialCompleted(tempId); - System.out.println("emp_details:==:"+emp_details); - - - List> zone_benefits=pensionReceivedService.fetchZonebenefitsById(tempId); - System.out.println("zone_benefits:==:"+zone_benefits); - - List> pension_benefits=pensionReceivedService.fetchPensionbenefitsById(tempId); - System.out.println("pension_benefits:==:"+pension_benefits); - - - boolean updated=deptPartiallyCompleteService.saveHistory(emp_details,zone_benefits,pension_benefits,filemovedby); - - if (!emp_details.isEmpty()) { // Ensure list is not empty - Map empDetailMap = emp_details.get(0); // Get first map from the list - - // Ensure the key exists in the map - if (empDetailMap.containsKey("file_status")) { - Object fileStatusObj = empDetailMap.get("file_status"); - - if (fileStatusObj != null) { - String fs = fileStatusObj.toString(); // Convert to String safely - fs1 = Integer.parseInt(fs); // Convert to integer if needed - System.out.println("file_status: " + fs1); - } else { - System.out.println("file_status is null"); - } - } else { - System.out.println("Key 'file_status' not found in emp_details"); - } - } else { - System.out.println("emp_details list is empty"); - } - - - if(updated) - { - if(fs1==11 && fs1!=0) - { - return ResponseEntity.ok("File Completed successfully!"); - } - else if(fs1==9 && fs1!=0) { - return ResponseEntity.ok("File Partially Completed!"); - } - else if(fs1==10 && fs1!=0){ - return ResponseEntity.ok("File Moved to Pension Partially Completed!"); - } - else { - return ResponseEntity.ok("File Status is 0!"); - } - - - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DropdownApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DropdownApiController.java deleted file mode 100644 index 227bc15b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DropdownApiController.java +++ /dev/null @@ -1,46 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DropdownService; - -@RequestMapping("gcc/api") -@Controller -public class DropdownApiController { - - @Autowired - private DropdownService dropdownService; - - @GetMapping("/getRetrimentTypes") - @ResponseBody - public List> getRetrimentTypes() { - return dropdownService.getRetrimentTypes(); - } - - @GetMapping("/getCategoryTypes") - @ResponseBody - public List> getCategoryTypes() { - return dropdownService.getCategoryTypes(); - } - - @GetMapping("/getProvisionalReasonTypes") - @ResponseBody - public List> getProvisionalReasonTypes() { - return dropdownService.getProvisionalReasonTypes(); - } - - - @GetMapping("/getGisEntryTypes") - @ResponseBody - public List> getGisEntryTypes() { - return dropdownService.getGisEntryTypes(); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingApiController.java deleted file mode 100644 index e6b2c8aa..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingApiController.java +++ /dev/null @@ -1,120 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.FileClosingService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.NewEntryService; - -@RequestMapping("gcc/api/fileclosing") -@RestController -public class FileClosingApiController { - - - @Autowired - private FileClosingService fileClosingService; - - - @Autowired - private NewEntryService newEntryService; - - @Autowired - private DeptAuditService deptAuditService; - - @GetMapping("/getdetails") - public List> getEmployeedetailsbyCode( @RequestParam String empCode, @RequestParam String deptId){ - - int dept_id=Integer.parseInt(deptId); - - int file_cat= newEntryService.getRetirementFileCategoryId(); - System.out.println("file_cat>>>>>>"+file_cat); - String tempId=fileClosingService.getTempId(empCode,dept_id,file_cat); - - System.out.println("empCode>>>>>"+empCode); - System.out.println("deptId>>>>>>"+dept_id); - System.out.println("tempId>>>>>>"+tempId); - - List> employeeDetails = fileClosingService.fetchEmployeeByTempId(tempId); - System.out.println("employeeDetails==="+employeeDetails); - - return employeeDetails; - } - - - @GetMapping("/getemployeedetails") - public List> getEmployeedetailsbyCode( - @RequestParam String tempId) { - - System.out.println("temporary==="+tempId); - - List> employeeDetails = fileClosingService.fetchEmployeeById(tempId); - System.out.println("employeeDetails==="+employeeDetails); - return employeeDetails; - } - - - @PostMapping("/updateDetails") - public ResponseEntity updateDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - System.out.println("data"+requestData); - - boolean isSaved = fileClosingService.updateEntryDetails(requestData); - - - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=fileClosingService.saveclosinghistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File Closed successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - //closed list api - - @GetMapping("/getcloseddetails") - public List> getClosedEmployeedetails(){ - - List> employeeDetails = fileClosingService.fetchClosingEmployee(); - System.out.println("employeeDetails==="+employeeDetails); - - return employeeDetails; - } - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingMainController.java deleted file mode 100644 index 70cd4ee6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingMainController.java +++ /dev/null @@ -1,60 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.NewEntryService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - - -@RequestMapping("/gcc/departmentfileclosing") -@Controller("gccpensionerfileclosing") - - -public class FileClosingMainController { - - - @Autowired - - private NewEntryService newEntryService; - - - @GetMapping("/fileclosing") - public String searchEmployee(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - - return "modules/pensioner/department/fileclosing"; - } - - @GetMapping("/closedlist") - public String closedEmployeeList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - - return "modules/pensioner/department/closedList"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/NewEntryAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/NewEntryAPIController.java deleted file mode 100644 index 6383ff74..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/NewEntryAPIController.java +++ /dev/null @@ -1,349 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.time.LocalDate; - -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.xmlbeans.impl.xb.xsdschema.Public; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.pensioner.service.NewEntryService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/department/newentry") -@RestController -public class NewEntryAPIController { - - @Autowired - private NewEntryService newEntryService; - - @Autowired - public NewEntryAPIController(NewEntryService newEntryService) { - this.newEntryService = newEntryService; - } - - - @GetMapping("/retirementdetails") - public Map getRetriedDetails( - @RequestParam(value = "deptId", required = false) Integer deptId, - @RequestParam(value = "file_category", required = false) Integer file_category, - @RequestParam(value = "fromDate", required = false) String fromDate1, - @RequestParam(value = "toDate", required = false) String toDate1) - { - - Map response = new HashMap<>(); - if (deptId == null) { - response.put("status", "deptid"); - response.put("message", "Department Id is null"); - return response; - - } - - System.out.println("Received deptId: " + deptId); - System.out.println("Received fromDate: " + fromDate1); - System.out.println("Received toDate: " + toDate1); - - LocalDate fromDate; - LocalDate toDate ; - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - LocalDate now = LocalDate.now(); - int currentYear = now.getYear(); - - if(fromDate1.isEmpty()) { - fromDate = LocalDate.of(currentYear, 4, 1); - } - - if(toDate1.isEmpty()) { - toDate = LocalDate.of(currentYear + 1, 3, 31); // March 31 of the next year - } - - if(fromDate1.isEmpty() && toDate1.isEmpty()) { - fromDate = LocalDate.of(currentYear, 4, 1); // April 1 of the current year - toDate = LocalDate.of(currentYear + 1, 3, 31); // March 31 of the next year - - } - else { - try { - - // Check if the input date is in yyyy-MM-dd format - if (fromDate1.matches("\\d{4}-\\d{2}-\\d{2}") && toDate1.matches("\\d{4}-\\d{2}-\\d{2}")) { - // Parse from yyyy-MM-dd format - fromDate = LocalDate.parse(fromDate1); - toDate = LocalDate.parse(toDate1); - } else { - // Parse from dd-MM-yyyy format - DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - fromDate = LocalDate.parse(fromDate1, formatter1); - toDate = LocalDate.parse(toDate1, formatter1); - } - - } catch (DateTimeParseException e) { - response.put("status", "error"); - response.put("message", "Invalid date format. Expected format: dd-MM-yyyy"); - return response; - } - - } - // Format the dates if needed (e.g., for logging or passing in a specific format) - - String formattedFromDate = fromDate.format(formatter); - String formattedToDate = toDate.format(formatter); - - System.out.println("Received deptId after date: " + deptId); - System.out.println("Fetching data from " + formattedFromDate + " to " + formattedToDate); - - - Map datalist = newEntryService.fetchEmplyeeDetails(formattedFromDate, formattedToDate, deptId); - System.out.println("datalist="+datalist); - List emps= newEntryService.getRegisteredEmps(deptId); - - // Format the dates for frontend in "yyyy-MM-dd" - DateTimeFormatter frontendFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - String frontendFromDate = fromDate.format(frontendFormatter); - String frontendToDate = toDate.format(frontendFormatter); - response.put("fromDate", frontendFromDate); - response.put("toDate", frontendToDate); - - // Extract emp_no values from emps - // Set empNos = emps.stream().map(emp -> (String) emp.get("emp_no")).collect(Collectors.toSet()); - - //System.out.println("rrrrrrrrrrrr"); - if (datalist.containsKey("list") && datalist.get("list") instanceof List) { - List list = (List) datalist.get("list"); - if (list.isEmpty()) { - System.out.println("inside>>>>>"); - response.put("status", "nodata"); - response.put("message", "No data available for the selected date range"); - } - else { - //System.out.println("ttttttttttttt"); - // Filter the datalist "list" to exclude matching EMPLOYEE_CODE values - /* - List> filteredList = ((List>) datalist.get("list")).stream() - .filter(employee -> !emps.contains(employee.get("EMPLOYEE_CODE"))) - .collect(Collectors.toList()); -*/ - - List> originalList = - (List>) datalist.get("list"); - - List> filteredList = new ArrayList>(); - - for (Map employee : originalList) { - Object empCode = employee.get("EMPLOYEE_CODE"); - if (!emps.contains(empCode)) { - filteredList.add(employee); - } - } - - if (filteredList.isEmpty()) { - response.put("status", "nodata"); - response.put("message", "No data available for the selected date range"); - } else { - datalist.put("list", filteredList); - response.put("status", "success"); - response.put("details", datalist); - System.out.println("Received datalist:"+datalist); - System.out.println("Received filteredList:"+filteredList); - } - } - } - - - - return response; - } - - - - @GetMapping("/employeedetails") - public ResponseEntity> getEmployeedetailsbyCode( - @RequestParam String empCode) { - - Map datalistbycode = newEntryService.fetchEmplyeeDetailsbyCode(empCode); - return ResponseEntity.ok(datalistbycode); - } - - @PostMapping("/saveEmployeeDetails") - public ResponseEntity saveRetirementEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save details - boolean isSaved = newEntryService.saveRetirementEmployeeDetails(requestData); - - if (isSaved) { - return ResponseEntity.ok("File moved to Audit successfully!"); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - - - - - //family pension - @PostMapping("/saveFamilyPensionDetails") - public ResponseEntity saveFamilyPensionDetails(@RequestBody Map requestData) { - try { - - - // Call service method to save details - boolean isSaved = newEntryService.saveFamilyPensionDetails(requestData); - - if (isSaved) { - return ResponseEntity.ok("File moved to Audit successfully!"); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - //pendency api - - @PostMapping("/savePendecnyDetails") - public ResponseEntity savePendecnyDetails(@RequestBody Map requestData) { - try { - - // Call service method to save detailstypeOfRetirement - boolean isSaved = newEntryService.savePendencyDetails(requestData); - - if (isSaved) { - return ResponseEntity.ok("File moved to Audit successfully!"); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - //gis saving api controller - @PostMapping("/saveEmployeeDetailsGis") - public ResponseEntity saveEmployeeDetailsingis(@RequestBody Map requestData) { - try { - // Extract data from the request body - - - // Call service method to save details - boolean isSaved = newEntryService.savenewEntryDetailsGis(requestData); - - if (isSaved) { - return ResponseEntity.ok("File moved to Pension successfully!"); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - - - //provsionalretirement saving api controller - @PostMapping("/saveEmployeeDetailsProvisionalretirement") - public ResponseEntity saveEmployeeDetailsProvisionalretirement(@RequestBody Map requestData) { - try { - // Extract data from the request body - - - // Call service method to save details - boolean isSaved = newEntryService.savenewEntryDetailsProvisionalretirement(requestData); - - if (isSaved) { - return ResponseEntity.ok("File moved to Pension successfully!"); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - - //cps saving api controller - @PostMapping("/saveEmployeeDetailsPensionScheme") - public ResponseEntity saveEmployeeDetailspensionscheme(@RequestBody Map requestData) { - try { - // Extract data from the request body - - - // Call service method to save details - boolean isSaved = newEntryService.savenewEntryDetailspensionscheme(requestData); - - if (isSaved) { - return ResponseEntity.ok("File Submitted successfully!"); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - @GetMapping("/exists") - public ResponseEntity> checkEmployeeExists(@RequestParam String empCode) { - boolean exists = newEntryService.doesEmployeeExist(empCode); - Map response = new HashMap<>(); - response.put("exists", exists); - return ResponseEntity.ok(response); - } - - @GetMapping("/cpsexists") - public ResponseEntity> checkEmployeeExistsCps(@RequestParam String empCode) { - boolean exists = newEntryService.doesEmployeeExistgis(empCode); - Map response = new HashMap<>(); - response.put("exists", exists); - return ResponseEntity.ok(response); - } - - @GetMapping("/prexists") - public ResponseEntity> checkEmployeeExistsRpr(@RequestParam String empCode) { - boolean exists = newEntryService.doesEmployeeExistRPR(empCode); - Map response = new HashMap<>(); - response.put("exists", exists); - return ResponseEntity.ok(response); - } - - - - @GetMapping("/familypensionexists") - public ResponseEntity> checkEmployeeExistsfp(@RequestParam String empCode) { - boolean exists = newEntryService.doesEmployeeExistfp(empCode); - Map response = new HashMap<>(); - response.put("exists", exists); - return ResponseEntity.ok(response); - } - - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PendencyAutoConversionApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PendencyAutoConversionApiController.java deleted file mode 100644 index f1c75594..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PendencyAutoConversionApiController.java +++ /dev/null @@ -1,201 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.time.LocalDate; - - -import java.time.Period; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.NewEntryService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PendencyAutoConversionService; - -@RequestMapping("gcc/api/pensioner/autoconversion") -@RestController -public class PendencyAutoConversionApiController { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - -// @Autowired -// private DeptAuditService deptAuditService; -// -// @Autowired -// public PendencyAutoConversionService pendencyAutoConversionService; -// -// @GetMapping("/updateintopendency") -// public boolean updateIfRetirementDateCrossed() { -// try { -// List> covertList = pendencyAutoConversionService.getConvertingTempIds(); -// System.out.println("covertList===" + covertList); -// -// if (!covertList.isEmpty()) { -// for (Map tempIdMap : covertList) { -// try { -// // Extract temp_id and convert it to a String -// Object tempIdRaw = tempIdMap.get("temp_id"); -// String tempId = tempIdRaw != null ? String.valueOf(tempIdRaw) : null; -// -// System.out.println("Converted tempId: " + tempId); -// -// // Ensure tempId is not null before processing -// if (tempId != null && !tempId.trim().isEmpty()) { -// -// String fileMovedBy=pendencyAutoConversionService.getFileMovedByTempId(tempId); -// -// if(fileMovedBy!=null) { -// boolean isProcessed = pendencyAutoConversionService.updateEntryDetails(tempId); -// -// if (isProcessed) { -// List> emp_details = deptAuditService.fetchEmployeeById(tempId); -// System.out.println("emp_details: " + emp_details); -// -// boolean updated = pendencyAutoConversionService.saveHistory(emp_details,fileMovedBy); -// -// if (!updated) { -// System.out.println("Failed to save history for tempId: " + tempId); -// continue; -// } -// } -// } -// else { -// System.out.println("fileMovedBy is NUll for temp_id="+tempId); -// } -// -// } -// } catch (Exception innerEx) { -// System.err.println("Error processing tempId: " + tempIdMap.get("temp_id")); -// innerEx.printStackTrace(); -// continue; // Continue processing the next record -// } -// } -// return true; -// } else { -// System.out.println("No records found for processing."); -// return false; -// } -// } catch (Exception e) { -// System.err.println("Exception in updateIfRetirementDateCrossed: " + e.getMessage()); -// e.printStackTrace(); -// return false; -// } -// } - - @Scheduled(cron = "*/40 * * * * ?") // Runs every 40 seconds - public void scheduledPendencyUpdate() { - System.out.println("Scheduled Task Started: Updating Pensioner Pending Duration 40"); - - Map result = GetRecordsUpdatePendencyDuration(); - - System.out.println("Scheduled Task Completed: " + result); - - // Fetch the pending pensioners count after the update - int pendingCount = getPendingPensionersCount(); - System.out.println("Total pending pensioners after update: " + pendingCount); - } - - public Map GetRecordsUpdatePendencyDuration() { - Map response = new HashMap<>(); - - // Lists to store tempIds based on update success or failure - List successfulUpdates = new ArrayList<>(); - List failedUpdates = new ArrayList<>(); - - String sqlQuery = "SELECT * FROM pensioner_details WHERE file_category=3 AND pending_duration='yes' AND file_status < 11"; - List> details = jdbcTemplate.queryForList(sqlQuery); - - for (Map tempIdMap : details) { - String tempId = tempIdMap.get("temp_id") != null ? String.valueOf(tempIdMap.get("temp_id")) : null; - String retirementDateStr = tempIdMap.get("retirement_date") != null ? String.valueOf(tempIdMap.get("retirement_date")) : null; - - if (retirementDateStr != null && !retirementDateStr.trim().isEmpty()) { - try { - // Convert retirement_date to LocalDate - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate startDate = LocalDate.parse(retirementDateStr, formatter); - LocalDate endDate = LocalDate.now(); // Current date - - System.out.printf("Processing Temp ID: %s | Start Date: %s | End Date: %s%n", tempId, startDate, endDate); - - // Calculate duration - String updateDuration = calculatePendingDuration(startDate, endDate); - System.out.println("Updated Duration: " + updateDuration); - - // Update the record in the database - boolean isUpdated = updatePendingDuration(updateDuration, tempId); - - // Add tempId to the respective list - if (isUpdated) { - successfulUpdates.add(tempId); - } else { - failedUpdates.add(tempId); - } - - } catch (Exception e) { - System.err.println("Error parsing retirement_date for tempId " + tempId + ": " + e.getMessage()); - } - } else { - System.out.println("Skipping: Retirement date is null or empty for tempId: " + tempId); - } - } - - response.put("status", "Success"); - response.put("message", "Pendency duration updated"); - response.put("total_records_processed", details.size()); - response.put("successful_updates_count", successfulUpdates.size()); - response.put("failed_updates_count", failedUpdates.size()); - response.put("successful_updates", successfulUpdates); - response.put("failed_updates", failedUpdates); - - return response; - } - - public String calculatePendingDuration(LocalDate startDate, LocalDate endDate) { - Period period = Period.between(startDate, endDate); - - int years = period.getYears(); - int months = period.getMonths(); - int days = period.getDays(); - - return (years > 0 ? years + " year " : "") + - (months > 0 ? months + " month " : "") + - (days > 0 ? days + " day" : ""); - } - - public boolean updatePendingDuration(String updateDuration, String tempId) { - String sqlQuery = "UPDATE pensioner_details SET reason_for_pending=? WHERE temp_id=?"; - int rowsUpdated = jdbcTemplate.update(sqlQuery, updateDuration, tempId); - System.out.println("Temp ID: " + tempId + " | Rows Updated: " + rowsUpdated); - return rowsUpdated > 0; - } - - // New method to get the count of pending pensioners - public int getPendingPensionersCount() { - String sqlQuery = "SELECT COUNT(*) FROM pensioner_details WHERE file_category=3 AND pending_duration='yes' AND file_status < 11"; - Integer count = jdbcTemplate.queryForObject(sqlQuery, Integer.class); - return count != null ? count : 0; - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionAuditApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionAuditApiController.java deleted file mode 100644 index bdc6b684..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionAuditApiController.java +++ /dev/null @@ -1,134 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionAuditService; - -@RequestMapping("gcc/api/pensioner/audit") -@RestController -public class PensionAuditApiController { - - @Autowired - private DeptAuditService deptAuditService; - - @Autowired - private PensionAuditService pensionAuditService; - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = pensionAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=pensionAuditService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("Audit Certificate Received successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - - @PostMapping("/updateFamilyPensionDetails") - public ResponseEntity updateFamilyPensionDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = pensionAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=pensionAuditService.saveFamilyPensionHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("Audit Certificate Received successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - - //pendency - @PostMapping("/updatePendencyDetails") - public ResponseEntity updatePendencyDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = pensionAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=pensionAuditService.savePendencyHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("Audit Certificate Received successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionPartiallyCompApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionPartiallyCompApiController.java deleted file mode 100644 index e8703e5d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionPartiallyCompApiController.java +++ /dev/null @@ -1,110 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptPartiallyCompService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionPartiallyCompService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionReceivedService; - -@RequestMapping("gcc/api/pensioner/partial") -@RestController -public class PensionPartiallyCompApiController { - - @Autowired - public DeptPartiallyCompService deptPartiallyCompleteService; - - @Autowired - public DeptAuditService deptAuditService; - - @Autowired - public PensionReceivedService pensionReceivedService; - - @Autowired - public PensionPartiallyCompService pensionPartiallyCompService; - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - int fs1=0; - - boolean isSaved = pensionPartiallyCompService.updateEntryCompletedDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchPartialCompleted(tempId); - System.out.println("emp_details:==:"+emp_details); - - - List> zone_benefits=pensionReceivedService.fetchZonebenefitsById(tempId); - System.out.println("zone_benefits:==:"+zone_benefits); - - List> pension_benefits=pensionReceivedService.fetchPensionbenefitsById(tempId); - System.out.println("pension_benefits:==:"+pension_benefits); - - - boolean updated=pensionPartiallyCompService.saveHistory(emp_details,zone_benefits,pension_benefits,filemovedby); - - if (!emp_details.isEmpty()) { // Ensure list is not empty - Map empDetailMap = emp_details.get(0); // Get first map from the list - - // Ensure the key exists in the map - if (empDetailMap.containsKey("file_status")) { - Object fileStatusObj = empDetailMap.get("file_status"); - - if (fileStatusObj != null) { - String fs = fileStatusObj.toString(); // Convert to String safely - fs1 = Integer.parseInt(fs); // Convert to integer if needed - System.out.println("file_status: " + fs1); - } else { - System.out.println("file_status is null"); - } - } else { - System.out.println("Key 'file_status' not found in emp_details"); - } - } else { - System.out.println("emp_details list is empty"); - } - - - if(updated) - { - if(fs1==11 && fs1!=0) - { - return ResponseEntity.ok("File Completed successfully!"); - } - else if(fs1==10 && fs1!=0){ - return ResponseEntity.ok("File Partially Completed!"); - } - else { - return ResponseEntity.ok("File Status is 0!"); - } - - - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionReceivedApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionReceivedApiController.java deleted file mode 100644 index 5d7109f0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionReceivedApiController.java +++ /dev/null @@ -1,94 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionReceivedService; - -@RequestMapping("gcc/api/department/received") -@RestController -public class PensionReceivedApiController { - - @Autowired - private DeptAuditService deptAuditService; - - @Autowired - private PensionReceivedService pensionReceivedService; - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - // Call service method to save - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - boolean isSaved = pensionReceivedService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - List> zone_benefits=pensionReceivedService.fetchZonebenefitsById(tempId); - System.out.println("zone_benefits:==:"+zone_benefits); - - boolean updated=pensionReceivedService.saveHistory(emp_details,zone_benefits,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File moved to Pension successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - //gis - @PostMapping("/updateEmployeeDetailsgis") - public ResponseEntity updateEmployeeDetailsGis(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - boolean isSaved = pensionReceivedService.updateEntryGisDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=pensionReceivedService.savehistoryGis(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File completed successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionerMainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionerMainController.java deleted file mode 100644 index 60a55535..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionerMainController.java +++ /dev/null @@ -1,625 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; - -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.CompletedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DepartmentForwardService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DepartmentReceivedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.NewEntryService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionPartiallyCompService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PensionReceivedService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReceivedDeptProvisionalService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReportApiService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReturnFromAuditService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@Controller -@RequestMapping("/gcc/pensioner") -public class PensionerMainController { - - - @Autowired - private NewEntryService newEntryService; - - @Autowired - private DeptAuditService deptAuditService; - - @Autowired - private ReturnFromAuditService returnFromAuditService; - - @Autowired - private PensionAuditService pensionAuditService; - - @Autowired - private DepartmentForwardService departmentForwardService; - - @Autowired - private PensionReceivedService pensionReceivedService; - - @Autowired - private DepartmentReceivedService departmentReceivedService; - - @Autowired - private ReceivedDeptProvisionalService receivedDeptProvisionalService; - - @Autowired - private CompletedService completedService; - - @Autowired - private PensionPartiallyCompService pensionPartiallyCompService; - - @Autowired - private ReportApiService reportApiService; - - - //////////////////////////////Pensioner pages//////////////////////////////// - - //yogi - @GetMapping("/audit/retirement") - public String pensionerauditretirment(Model model) { - - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>auditlist= pensionAuditService.fetchDetailsForAudit(file_cat); - - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/pensioner/audit/retirement"; - } - - - - @GetMapping("/audit/familypension") - public String pensionerfamilypension(Model model) { - - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - List>auditlist= pensionAuditService.fetchDetailsForAudit(file_cat); - - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/pensioner/audit/familypension"; - } - - - @GetMapping("/audit/pendency") - public String pensionerpendency(Model model) { - - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - - - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - - - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - List>auditlist= pensionAuditService.fetchDetailsForAudit(file_cat); - - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/pensioner/audit/pendency"; - } - - - ///////////////////COMPLETED LIST PAGES////////////// - - @GetMapping("/completed/retirement") - public String pensionerretirement(Model model) { - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>provisionallist= completedService.fetchDetailsCompletedRetirementPensionside(file_cat); - - System.out.println("provisionallist===="+provisionallist); - model.addAttribute("provisionallist", provisionallist); - - return "modules/pensioner/pensioner/completed/retirement"; - } - - - @GetMapping("/completed/familypension") - public String pensionercompleted(Model model) { - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>familypensioncompletedlist= completedService.fetchDetailsCompletedFamilyPensionPensionSide(file_cat); - - System.out.println("provisionallist===="+familypensioncompletedlist); - model.addAttribute("provisionallist", familypensioncompletedlist); - - return "modules/pensioner/pensioner/completed/familypension"; - } - - - - @GetMapping("/completed/pendency") - public String pensionercompletedpendency(Model model) { - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>pendencycompletedlist= completedService.fetchDetailsCompletedPendencyPensionSide(file_cat); - - System.out.println("provisionallist===="+pendencycompletedlist); - model.addAttribute("provisionallist", pendencycompletedlist); - - return "modules/pensioner/pensioner/completed/pendency"; - } - - - @GetMapping("/completed/gis") - public String pensionercompletedgis(Model model) { - int file_cat= newEntryService.getGISFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>gislist= completedService.fetchDetailsForrecivedGiscompletedPensionside(file_cat); - - System.out.println("auditlist===="+gislist); - model.addAttribute("auditlist", gislist); - - return "modules/pensioner/pensioner/completed/gis"; - } - - @GetMapping("/completed/provisionalretirement") - public String pensionercompletedretirement(Model model) { - int file_cat= newEntryService.getPRFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>provisionallist= completedService.fetchDetailsProvisionalDepartmentPensionside(file_cat); - - System.out.println("provisionallist===="+provisionallist); - model.addAttribute("provisionallist", provisionallist); - - - return "modules/pensioner/pensioner/completed/provisionalretirement"; - } - - - - @GetMapping("/completed/contributorypensionscheme") - public String pensionercompletedcontributory( - Model model) { - int file_cat= newEntryService.getCPSFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>completedCPSList= completedService.getCPSListPensionside(file_cat); - - System.out.println("provisionallist===="+completedCPSList); - model.addAttribute("provisionallist", completedCPSList); - // Add the list to the model - model.addAttribute("completedCPSList", completedCPSList); - - return "modules/pensioner/pensioner/completed/contributorypensionscheme"; - } - - - - - //Ajith - - @GetMapping("/forward/retirement") - public String pensioneretirement(Model model) { - - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>forwardlist= departmentForwardService.fetchDepatmentForwardEmpfiles(file_cat); - - System.out.println("forwardlist===="+forwardlist); - model.addAttribute("forwardlist", forwardlist); - - return "modules/pensioner/pensioner/forward/retirement"; - } - - @GetMapping("/forward/familypension") - public String pensionfamily(Model model) { - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>forwardlist= departmentForwardService.fetchDepatmentForwardEmpfiles(file_cat); - - System.out.println("forwardlist===="+forwardlist); - model.addAttribute("forwardlist", forwardlist); - - return "modules/pensioner/pensioner/forward/familypension"; - } - - - @GetMapping("/forward/pendency") - public String pensionerforward(Model model) { - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>forwardlist= departmentForwardService.fetchDepatmentForwardEmpfiles(file_cat); - - System.out.println("forwardlist===="+forwardlist); - model.addAttribute("forwardlist", forwardlist); - - return "modules/pensioner/pensioner/forward/pendency"; - } - - - - - //dizho - - @GetMapping("/received/retirement") - public String pensionerreceivedretirement(Model model) { - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>forwardlist= departmentReceivedService.fetchPensionReceivedEmpfiles(file_cat); - - System.out.println("forwardlist===="+forwardlist); - model.addAttribute("forwardlist", forwardlist); - - return "modules/pensioner/pensioner/received/retirement"; - } - - @GetMapping("/received/familypension") - public String pensionerreceivedfamilypension(Model model) { - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>forwardlist= departmentReceivedService.fetchPensionReceivedEmpfiles(file_cat); - - System.out.println("forwardlist===="+forwardlist); - model.addAttribute("forwardlist", forwardlist); - - return "modules/pensioner/pensioner/received/familypension"; - } - - - @GetMapping("/received/pendency") - public String pensionerreceived(Model model) { - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>forwardlist= departmentReceivedService.fetchPensionReceivedEmpfiles(file_cat); - - System.out.println("forwardlist===="+forwardlist); - model.addAttribute("forwardlist", forwardlist); - - return "modules/pensioner/pensioner/received/pendency"; - } - - @GetMapping("/received/gis") - public String pensionerreceivedgis(Model model) { - int file_cat= newEntryService.getGISFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>gislist= pensionAuditService.fetchDetailsForrecivedGis(file_cat); - - System.out.println("auditlist===="+gislist); - model.addAttribute("auditlist", gislist); - - return "modules/pensioner/pensioner/received/gis"; - } - - - - - @GetMapping("/received/provisionalretirement") - public String pensionerprovisionalretirement(Model model) { - - int file_cat= newEntryService.getPRFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>provisionallist= receivedDeptProvisionalService.fetchDetailsProvisionalPension(file_cat); - - System.out.println("provisionallist===="+provisionallist); - model.addAttribute("provisionallist", provisionallist); - - return "modules/pensioner/pensioner/received/provisionalretirement"; - } - - - //sanjay - - @GetMapping("/partial/pendency") - public String pensionerpartial(Model model) { - int file_cat= newEntryService.getPendencyFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>auditlist= pensionPartiallyCompService.fetchPensionPartialEmpfiles(file_cat); - - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/pensioner/partial/pendency"; - } - - @GetMapping("/partial/retirement") - public String pensionerpartialretirement(Model model) { - int file_cat= newEntryService.getRetirementFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>auditlist= pensionPartiallyCompService.fetchPensionPartialEmpfiles(file_cat); - - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - - - - return "modules/pensioner/pensioner/partial/retirement"; - } - - @GetMapping("/partial/familypension") - public String pensionerpartialfamily(Model model) { - int file_cat= newEntryService.getFamilyPensionFileCategoryId(); - model.addAttribute("filecategory", file_cat); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - Integer deptId = newEntryService.getloginuserDeptId(userId); - String deptname=newEntryService.getDeptNameById(deptId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - System.out.println("deptId:"+ deptId); - model.addAttribute("deptId", deptId); - model.addAttribute("deptname", deptname); - model.addAttribute("userId", userId); - - List>auditlist= pensionPartiallyCompService.fetchPensionPartialEmpfiles(file_cat); - - System.out.println("auditlist===="+auditlist); - model.addAttribute("auditlist", auditlist); - - return "modules/pensioner/pensioner/partial/familypension"; - } - - @GetMapping("/reports") - public String report(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - Integer deptId = newEntryService.getloginuserDeptId(userId); - model.addAttribute("deptId", deptId); - - return "modules/pensioner/pensioner/reports"; - } - - - - @GetMapping("/dashboard") - public String pensionerdashboardpage(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - String UserRole = LoginUserInfo.getUserRole(); - - return "modules/pensioner/pensioner/dashboard"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReceivedDeptProvisionalApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReceivedDeptProvisionalApiController.java deleted file mode 100644 index 0e5ae17e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReceivedDeptProvisionalApiController.java +++ /dev/null @@ -1,145 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReceivedDeptProvisionalService; - -@RestController -@RequestMapping("gcc/api/pensioner/received/provisional") -public class ReceivedDeptProvisionalApiController { - - @Autowired - private ReceivedDeptProvisionalService receivedDeptProvisionalService; - - @Autowired - private DeptAuditService deptAuditService; - - - @Autowired - public ReceivedDeptProvisionalApiController(ReceivedDeptProvisionalService receivedDeptProvisionalService) { - this.receivedDeptProvisionalService = receivedDeptProvisionalService; - } - - //sent to completed list - @PostMapping("/updateEmployeeDetailsCompleted") - public ResponseEntity updateEmployeeDetailsCompleted(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = receivedDeptProvisionalService.updateEntryDetailsCompleted(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=receivedDeptProvisionalService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File Completed successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - - - // returned from pension to department - @PostMapping("/updateEmployeeDetailsReturn") - public ResponseEntity updateEmployeeDetailsReturn(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = receivedDeptProvisionalService.updateEntryDetailsReturntoDepartment(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=receivedDeptProvisionalService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File moved to Department successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - //sent again to pension from department - @PostMapping("/updateEmployeeDetailsSentToPension") - public ResponseEntity updateEntryDetailsSenttoPension(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = receivedDeptProvisionalService.updateEntryDetailsSenttoPension(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=receivedDeptProvisionalService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File moved to Pension successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReportApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReportApiController.java deleted file mode 100644 index 3fbba6d9..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReportApiController.java +++ /dev/null @@ -1,143 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.hibernate.internal.build.AllowSysOut; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReportApiService; - -@RequestMapping("gcc/api/report") -@RestController -public class ReportApiController { - @Autowired - private ReportApiService reportApiService; - - - - //pensioner and report side common dropdown - @GetMapping("/getFileCategories") - @ResponseBody - public ResponseEntity getFileCategories() { - try { - List> categories = reportApiService.getFileCategories(); - return ResponseEntity.ok(categories); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to fetch categories")); - } - } - - - @GetMapping("/getReportData") - @ResponseBody - public List> getReportData(@RequestParam String startDate, - @RequestParam String endDate, - @RequestParam String deptId - ) { - return reportApiService.getReportData(startDate, endDate, deptId); - } - - - - - @GetMapping("/getReportDetails") - @ResponseBody - public List> getReportDetails(@RequestParam String startDate, - @RequestParam String endDate, - @RequestParam Integer deptId, - @RequestParam Integer fileCatId, - @RequestParam(required = false) List fileStatus - ) { - System.out.println("startdate>>>>>"+startDate); - System.out.println("endDate>>>>>"+endDate); - System.out.println("deptId>>>>>"+deptId); - System.out.println("fileCatId>>>>>"+fileCatId); - System.out.println("fileStatus>>>>>"+fileStatus); - - - return reportApiService.getReportDetails(startDate, endDate, deptId,fileCatId,fileStatus); - - } - - - - //pensioner side report dropdown - - @GetMapping("/getdepartment") - @ResponseBody - public ResponseEntity getdepartment() { - try { - List> categories = reportApiService.getdepartment(); - return ResponseEntity.ok(categories); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to fetch categories")); - } - } - - @GetMapping("/getstatus") - @ResponseBody - public ResponseEntity getstatus() { - try { - List> categories = reportApiService.getstatus(); - return ResponseEntity.ok(categories); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to fetch categories")); - } - } - - - - @GetMapping("/getReportDatapension") - @ResponseBody - public List> getReportDatapension(@RequestParam String startDate, - @RequestParam String endDate, - @RequestParam(required = true) String fileCategoryId) - { - System.out.println("fileCategoryId ========>"+fileCategoryId); - return reportApiService.getReportDatapension(startDate, endDate, fileCategoryId); - } - - - - - @GetMapping("/getReportDetailspension") - @ResponseBody - public List> getReportDetailspension(@RequestParam String startDate, - @RequestParam String endDate, - @RequestParam List deptIds, - @RequestParam Integer fileCatId, - @RequestParam(required = false) List fileStatus) { - - System.out.println("startdate>>>>>"+startDate); - System.out.println("endDate>>>>>"+endDate); - System.out.println("deptIds: " + deptIds); - System.out.println("fileCatId>>>>>"+fileCatId); - System.out.println("fileStatus>>>>>"+fileStatus); - - return reportApiService.getReportDetailspension(startDate, endDate, deptIds, fileCatId, fileStatus); - } - - @GetMapping("/getPensionerDetails") - @ResponseBody - public List> getDepartmentpending(@RequestParam int file_category ) { - return reportApiService.getDepartmentpending(file_category); - } - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReturnFromAuditApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReturnFromAuditApiController.java deleted file mode 100644 index 795187f9..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReturnFromAuditApiController.java +++ /dev/null @@ -1,129 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RestController; - -import in.gov.chennaicorporation.gccoffice.pensioner.service.DeptAuditService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReturnFromAuditService; - -@RequestMapping("gcc/api/department/return") -@RestController -public class ReturnFromAuditApiController { - - @Autowired - private ReturnFromAuditService returnFromAuditService; - - @Autowired - private DeptAuditService deptAuditService; - - @PostMapping("/updateEmployeeDetails") - public ResponseEntity updateEmployeeDetails(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - boolean isSaved = returnFromAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=returnFromAuditService.savehistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File sent to Audit successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - @PostMapping("/updateReturnFamilyPension") - public ResponseEntity updateReturnFamilyPension(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = returnFromAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=returnFromAuditService.saveFamilyPensionReturnHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File sent to Audit successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - - - @PostMapping("/updateReturnPendency") - public ResponseEntity updatePendencyPension(@RequestBody Map requestData) { - try { - - // Call service method to save - String tempId = (String) requestData.get("tempId"); - String filemovedby =(String)requestData.get("filemovedby"); - - - - boolean isSaved = returnFromAuditService.updateEntryDetails(requestData); - - if (isSaved) { - List> emp_details=deptAuditService.fetchEmployeeById(tempId); - System.out.println("emp_details:==:"+emp_details); - boolean updated=returnFromAuditService.savePendencyHistory(emp_details,filemovedby); - - if(updated) - { - return ResponseEntity.ok("File sent Audit successfully!"); - } - else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details in history."); - } - - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save details."); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving details."); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/scheduler/PendencyAutoConversionScheduler.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/scheduler/PendencyAutoConversionScheduler.java deleted file mode 100644 index 6ef9aa87..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/scheduler/PendencyAutoConversionScheduler.java +++ /dev/null @@ -1,229 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.scheduler; - -import java.time.LocalDate; -import java.time.Period; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; -import in.gov.chennaicorporation.gccoffice.pensioner.service.PendencyAutoConversionService; -import in.gov.chennaicorporation.gccoffice.pensioner.service.ReceivedDeptProvisionalService; - -@Component -public class PendencyAutoConversionScheduler { - - - @Autowired - private PendencyAutoConversionService pendencyAutoConversionService; - - @Autowired - public ReceivedDeptProvisionalService ReceivedDeptProvisionalservice; - - /** - * Scheduled method that runs every day 3.00am and 4.00 am to process auto-conversion tasks. - */ - - @Scheduled(cron = "0 0 3 * * ?", zone = "Asia/Kolkata")// Runs every 3.00 am - public void executeAutoConversion() { - try { - System.out.println(" Running scheduled auto-conversion task... at 3.00 am"); - - // Step 1: Fetch temp IDs that need processing - List> tempIds = pendencyAutoConversionService.getConvertingTempIds(); - - if (tempIds == null || tempIds.isEmpty()) { - System.out.println(" No records found for auto-conversion."); - return; - } - - System.out.println(" Found " + tempIds.size() + " records for processing."); - - // Step 2: Process each tempId - for (Map tempIdMap : tempIds) { - String tempId = tempIdMap.get("temp_id") != null ? tempIdMap.get("temp_id").toString() : null; - - if (tempId == null || tempId.trim().isEmpty()) { - System.out.println(" Skipping empty temp_id."); - continue; - } - - System.out.println(" Processing tempId: " + tempId); - - // Step 3: Call service method to process auto-conversion - boolean success = pendencyAutoConversionService.processAutoConversionForTempId(tempId); - - if (success) { - System.out.println(" Auto-conversion completed for tempId: " + tempId); - } else { - System.out.println(" Auto-conversion failed for tempId: " + tempId); - } - } - } catch (Exception e) { - System.err.println(" Error during auto-conversion task: " + e.getMessage()); - e.printStackTrace(); - } - } - - - @Scheduled(cron = "0 0 4 * * ?", zone = "Asia/Kolkata") // Runs every day 4.00am - public void scheduledPendencyUpdate() { - System.out.println("Scheduled Task Started 4.00 am: Updating Pensioner Pending Duration"); - - Map result = GetRecordsUpdatePendencyDuration(); - - System.out.println("Scheduled Task Completed: " + result); - - // Fetch the pending pensioners count after the update - int pendingCount = pendencyAutoConversionService.getPendingPensionersCount(); - System.out.println("Total pending pensioners after update: " + pendingCount); - } - - public Map GetRecordsUpdatePendencyDuration() { - Map response = new HashMap<>(); - - // Lists to store tempIds based on update success or failure - List successfulUpdates = new ArrayList<>(); - List failedUpdates = new ArrayList<>(); - - List> details = pendencyAutoConversionService.getPendencyUpdatingDuration(); - - List> prdetails = pendencyAutoConversionService.getProvisionalNoPendingDuration(); - if(!prdetails.isEmpty()) { - - for (Map prdetail : prdetails) { - String tempId1 = prdetail.get("temp_id") != null ? String.valueOf(prdetail.get("temp_id")) : null; - String retirementDateStr1 = prdetail.get("retirement_date") != null ? String.valueOf(prdetail.get("retirement_date")) : null; - - try { - // Convert retirement_date to LocalDate - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate startDate1 = LocalDate.parse(retirementDateStr1, formatter); - LocalDate endDate1 = LocalDate.now(); - - System.out.printf("Processing Temp ID: %s | Start Date: %s | End Date: %s%n", tempId1, startDate1, endDate1); - - String updateDuration1 = pendencyAutoConversionService.calculatePendingDuration(startDate1, endDate1); - System.out.println("Updated Duration: " + updateDuration1); - - boolean isUpdated1 = pendencyAutoConversionService.updatePendingDurationforPR(updateDuration1, tempId1); - - if (isUpdated1) { - successfulUpdates.add(tempId1); - String filemovedby=pendencyAutoConversionService.getFileMovedByTempId(tempId1); - List> empDetails=pendencyAutoConversionService.fetchEmployeeDetails(tempId1); - boolean historySaved = ReceivedDeptProvisionalservice.savehistory(empDetails, filemovedby); - if (!historySaved) { - System.out.println("Failed to save prno history for tempId: " + tempId1); - } - } else { - failedUpdates.add(tempId1); - } - - } - catch (Exception e) { - System.err.println("Error parsing retirement_date for tempId " + tempId1 + ": " + e.getMessage()); - } - } - - } - if(!details.isEmpty()) { - - for (Map tempIdMap : details) { - String tempId = tempIdMap.get("temp_id") != null ? String.valueOf(tempIdMap.get("temp_id")) : null; - String retirementDateStr = tempIdMap.get("retirement_date") != null ? String.valueOf(tempIdMap.get("retirement_date")) : null; - String serviceDeathDate = tempIdMap.get("service_death") != null ? String.valueOf(tempIdMap.get("service_death")) : null; - // Corrected parsing for file_category - int fileCat = tempIdMap.get("file_category") != null ? Integer.parseInt(tempIdMap.get("file_category").toString()) : null; - - if(fileCat==3 || fileCat==5) { - - if (retirementDateStr != null && !retirementDateStr.trim().isEmpty()) { - try { - // Convert retirement_date to LocalDate - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate startDate = LocalDate.parse(retirementDateStr, formatter); - LocalDate endDate = LocalDate.now(); // Current date - - System.out.printf("Processing Temp ID: %s | Start Date: %s | End Date: %s%n", tempId, startDate, endDate); - - // Calculate duration - String updateDuration = pendencyAutoConversionService.calculatePendingDuration(startDate, endDate); - System.out.println("Updated Duration: " + updateDuration); - - // Update the record in the database - boolean isUpdated = pendencyAutoConversionService.updatePendingDuration(updateDuration, tempId); - - // Add tempId to the respective list - if (isUpdated) { - successfulUpdates.add(tempId); - } else { - failedUpdates.add(tempId); - } - - } catch (Exception e) { - System.err.println("Error parsing retirement_date for tempId " + tempId + ": " + e.getMessage()); - } - } else { - System.out.println("Skipping: Retirement date is null or empty for tempId: " + tempId); - } - } - - - if(fileCat==2) { - - if (serviceDeathDate != null && !serviceDeathDate.trim().isEmpty()) { - try { - // Convert retirement_date to LocalDate - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate startDate = LocalDate.parse(serviceDeathDate, formatter); - LocalDate endDate = LocalDate.now(); // Current date - - System.out.printf("Processing Temp ID: %s | Start Date: %s | End Date: %s%n", tempId, startDate, endDate); - - // Calculate duration - String updateDuration = pendencyAutoConversionService.calculatePendingDuration(startDate, endDate); - System.out.println("Updated Duration: " + updateDuration); - - // Update the record in the database - boolean isUpdated = pendencyAutoConversionService.updatePendingDuration(updateDuration, tempId); - - // Add tempId to the respective list - if (isUpdated) { - successfulUpdates.add(tempId); - } else { - failedUpdates.add(tempId); - } - - } catch (Exception e) { - System.err.println("Error parsing service death date for tempId " + tempId + ": " + e.getMessage()); - } - } else { - System.out.println("Skipping: service death date is null or empty for tempId: " + tempId); - } - } - - } - response.put("status", "Success"); - response.put("message", "Pendency duration updated"); - response.put("total_records_processed", details.size()); - response.put("successful_updates_count", successfulUpdates.size()); - response.put("failed_updates_count", failedUpdates.size()); - response.put("successful_updates", successfulUpdates); - response.put("failed_updates", failedUpdates); - - } - - response.put("status", "No Data"); - response.put("message", "No Updation in Pending Duration"); - - return response; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/CompletedService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/CompletedService.java deleted file mode 100644 index e7d0ecfb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/CompletedService.java +++ /dev/null @@ -1,180 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.ArrayList; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class CompletedService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public CompletedService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> getCPSList(Integer file_cat,Integer deptId) { - String query = "SELECT * FROM cps_pensioner_details where file_category = ? and dept_id=? and file_status=11 "; - - try { - return jdbcTemplate.queryForList(query,file_cat,deptId); - } catch (Exception e) { - e.printStackTrace(); - return new ArrayList<>(); - } - } - - ///////////////////CPS completed list method/////////// - - public List> getCPSListPensionside(Integer file_cat) { - String query = "SELECT * FROM cps_pensioner_details where file_category = ? and file_status=11 "; - - try { - return jdbcTemplate.queryForList(query,file_cat); - } catch (Exception e) { - e.printStackTrace(); - return new ArrayList<>(); - } - } - - - public List> getCPSListByEmpNo(String empNo) { - String query = "SELECT * FROM cps_pensioner_details WHERE emp_no = ?"; - - try { - return jdbcTemplate.queryForList(query, empNo); - } catch (Exception e) { - e.printStackTrace(); - return new ArrayList<>(); - } - } - - - //////////////////////////// - - - - - ////////Retirement completed list method/////////////////// - public List> fetchDetailsCompletedRetirement(Integer file_cat,Integer deptId) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND dept_id=? and file_status=11 AND is_closed=0"; - return jdbcTemplate.queryForList(query,file_cat,deptId); - } - - - - public List> fetchDetailsCompletedRetirementPensionside(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? and file_status=11 AND is_closed=0"; - return jdbcTemplate.queryForList(query,file_cat); - } - ///////////////////////// - - - - ///////////////////Family pension completed list method////////////// - public List> fetchDetailsCompletedFamilyPension(Integer file_cat,Integer deptId) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND dept_id=? and file_status=11"; - return jdbcTemplate.queryForList(query,file_cat,deptId); - } - - - - public List> fetchDetailsCompletedFamilyPensionPensionSide(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? and file_status=11"; - return jdbcTemplate.queryForList(query,file_cat); - } - ////////////////////////// - - - - ///////////////Pendency completed method//////////////// - public List> fetchDetailsCompletedPendency(Integer file_cat,Integer deptId) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND dept_id=? and file_status=11"; - return jdbcTemplate.queryForList(query,file_cat,deptId); - } - - - - public List> fetchDetailsCompletedPendencyPensionSide(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? and file_status=11"; - return jdbcTemplate.queryForList(query,file_cat); - } - ////////////////////// - - - - ////////////Gis completed list method - - public List> fetchDetailsForrecivedGiscompleted(Integer file_cat,Integer deptId) { - String query = "SELECT * FROM pensioner_details WHERE file_category = ? AND dept_id=? AND file_status = 11"; - - return jdbcTemplate.queryForList(query,file_cat,deptId); - } - - - public List> fetchDetailsForrecivedGiscompletedPensionside(Integer file_cat) { - String query = "SELECT * FROM pensioner_details WHERE file_category = ? AND file_status = 11"; - - return jdbcTemplate.queryForList(query,file_cat); - } - - - - ////////////////Provisional retirement completed list method - - public List> fetchDetailsProvisionalDepartmentCompleted(Integer file_cat,Integer deptId) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND dept_id=? and file_status=11"; - return jdbcTemplate.queryForList(query,file_cat,deptId); - } - - - - public List> fetchDetailsProvisionalDepartmentPensionside(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? and file_status=11"; - return jdbcTemplate.queryForList(query,file_cat); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DashboardApiService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DashboardApiService.java deleted file mode 100644 index 769d2fb0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DashboardApiService.java +++ /dev/null @@ -1,402 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - - -@Service -public class DashboardApiService { - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> getTempEmpDetails(String tempId) { - System.out.println("service"); - System.out.println(tempId); - - String sql = "SELECT MH.file_moved_date,sm.file_status,MH.remarks FROM file_movement_history MH" - + " inner join file_status_master sm on MH.file_status= sm.id where temp_id=? order by MH.file_moved_date desc "; - - return jdbcTemplate.queryForList(sql, tempId); - } - - - - public List> getEmpDetails(String empNo) { - System.out.println("service"); - System.out.println(empNo); - - String sql = "SELECT dm.dept_name,fm.file_name, sm.file_status ,pd.temp_id " + - "FROM pensioner_details pd " + - "INNER JOIN file_category_master fm ON pd.file_category = fm.id " + - "INNER JOIN file_status_master sm ON sm.id = pd.file_status " + - "inner join department_master dm on dm.id=pd.dept_id "+ - - "WHERE pd.emp_no = ? " + - - "UNION " + - "SELECT dm.dept_name,fm.file_name, sm.file_status ,cps.temp_id " + - "FROM cps_pensioner_details cps " + - "INNER JOIN file_category_master fm ON cps.file_category = fm.id " + - "INNER JOIN file_status_master sm ON sm.id = cps.file_status " + - "inner join department_master dm on dm.id=cps.dept_id "+ - - "WHERE cps.emp_no = ?"; - - return jdbcTemplate.queryForList(sql, empNo, empNo); - } - - public List> getPensionEmpDetails(String empNo) { - System.out.println("service"); - System.out.println(empNo); - - String sql = "SELECT dm.dept_name,fm.file_name, sm.file_status ,pd.temp_id " + - "FROM pensioner_details pd " + - "INNER JOIN file_category_master fm ON pd.file_category = fm.id " + - "INNER JOIN file_status_master sm ON sm.id = pd.file_status " + - "inner join department_master dm on dm.id=pd.dept_id "+ - "WHERE pd.emp_no = ? " + - "UNION " + - "SELECT dm.dept_name,fm.file_name, sm.file_status ,cps.temp_id " + - "FROM cps_pensioner_details cps " + - "INNER JOIN file_category_master fm ON cps.file_category = fm.id " + - "INNER JOIN file_status_master sm ON sm.id = cps.file_status " + - "inner join department_master dm on dm.id=cps.dept_id "+ - "WHERE cps.emp_no = ?"; - - return jdbcTemplate.queryForList(sql, empNo, empNo); - } - - - - /* public List> getEmployeeDetailss(String fileName) { - - - String sql = "SELECT emp_no FROM gcc_pensioner.pensioner_details pd " + - "INNER JOIN gcc_pensioner.file_category_master cm ON pd.file_category = cm.id " + - "WHERE cm.file_name = ?"; - return jdbcTemplate .queryForList(sql, new Object[]{fileName}); - }*/ - /* public List> getStageWiseCounts() { - String sql = - "SELECT category, SUM(category_count) AS category_count FROM (" + - " SELECT " + - " CASE " + - " WHEN sm.id IN (1, 3) THEN 'Audit Pending' " + - " WHEN sm.id IN (2, 5, 6, 9) THEN 'Department Pending' " + - " WHEN sm.id IN (4, 7, 8, 10) THEN 'Pension Pending' " + - " WHEN sm.id = 11 THEN 'Completed' " + - - " END AS category, " + - " COUNT(*) AS category_count " + - " FROM gcc_pensioner.pensioner_details pd " + - " INNER JOIN gcc_pensioner.file_status_master sm ON pd.file_status = sm.id " + - " GROUP BY category " + - - " UNION ALL " + - - " SELECT " + - " CASE " + - " WHEN sm.id IN (1, 3) THEN 'Audit Pending' " + - " WHEN sm.id IN (2, 5, 6, 9) THEN 'Department Pending' " + - " WHEN sm.id IN (4, 7, 8, 10) THEN 'Pension Pending' " + - " WHEN sm.id = 11 THEN 'Completed' " + - - " END AS category, " + - " COUNT(*) AS category_count " + - " FROM gcc_pensioner.cps_pensioner_details cps " + - " INNER JOIN gcc_pensioner.file_status_master sm ON cps.file_status = sm.id " + - " GROUP BY category " + - ") AS combined_results " + - "GROUP BY category;"; - - return jdbcTemplate.queryForList(sql); - - }*/ - - public List> getEmployeeDetails(String FileId) { - String query; - - switch (FileId) { - case "1": - case "2": - case "3": - case "4": - case "5": - query = "SELECT pd.emp_no " + - "FROM pensioner_details pd " + - "INNER JOIN file_category_master cm " + - "ON pd.file_category = cm.id " + - "WHERE cm.id = ?"; - break; - - case "6": - query = "SELECT cps.emp_no " + - "FROM cps_pensioner_details cps " + - "INNER JOIN file_category_master cm " + - "ON cps.file_category = cm.id " + - "WHERE cm.id = ?"; - break; - - default: - return Collections.emptyList(); - } - - return jdbcTemplate.queryForList(query, FileId); - } - - - public List> fetchCategoryCounts() { - String sql = "SELECT file_name, id, COALESCE(SUM(category_count), 0) AS category_count " + - "FROM ( " + - " SELECT cm.file_name, cm.id,COUNT(pd.file_category) AS category_count " + - " FROM file_category_master cm " + - " LEFT JOIN pensioner_details pd " + - " ON pd.file_category = cm.id " + - " AND pd.is_closed='0' " + - - - " GROUP BY cm.file_name,cm.id" + - " UNION ALL " + - " SELECT cm.file_name, cm.id,COUNT(cps.file_category) AS category_count " + - " FROM file_category_master cm " + - " LEFT JOIN cps_pensioner_details cps " + - " ON cps.file_category = cm.id " + - - - " GROUP BY cm.file_name ,cm.id " + - ") combined_counts " + - "GROUP BY file_name,id"; - - return jdbcTemplate.queryForList(sql); - } - - /* - public List> fetchCategorysearchCounts(String startdate, String enddate) { - String sql = "SELECT cm.file_name, COALESCE(SUM(category_count), 0) AS category_count " + - "FROM ( " + - " SELECT cm.file_name, COUNT(pd.file_category) AS category_count " + - " FROM gcc_pensioner.file_category_master cm " + - " LEFT JOIN gcc_pensioner.pensioner_details pd " + - " ON pd.file_category = cm.id " + - " AND (? IS NULL OR (? = ? AND DATE(pd.created_date) = ?) OR (DATE(pd.created_date) >= ? AND DATE(pd.created_date) <= ?)) " + - - " GROUP BY cm.file_name " + - " UNION ALL " + - " SELECT cm.file_name, COUNT(cps.file_category) AS category_count " + - " FROM gcc_pensioner.file_category_master cm " + - " LEFT JOIN gcc_pensioner.cps_pensioner_details cps " + - " ON cps.file_category = cm.id " + - " AND (? IS NULL OR (? = ? AND DATE(cps.created_date) = ?) OR (DATE(cps.created_date) >= ? AND DATE(cps.created_date) <= ?)) " + - - " GROUP BY cm.file_name " + - ") combined_counts " + - "RIGHT JOIN gcc_pensioner.file_category_master cm " + - "ON combined_counts.file_name = cm.file_name " + - - "GROUP BY cm.file_name"; - - return jdbcTemplate.queryForList(sql, new Object[]{ - startdate, startdate, enddate, startdate, // For `pd.created_date` exact match or range - startdate, enddate, // For `pd.created_date` range - startdate, startdate, enddate, startdate, // For `cps.created_date` exact match or range - startdate, enddate // For `cps.created_date` range - }); - - - - - - - - - }//department*/ - public List> getDepartment() { - String sql = "SELECT dept_id,dept_name FROM department_master WHERE dept_id <> 2000"; - return jdbcTemplate.queryForList(sql); - } - - - public List> DepartmenfetchCategoryCounts(String deptId) { - String sql = "SELECT cm.file_name, cm.id, " + - " COALESCE(pd.category_count, 0) + COALESCE(cps.category_count, 0) AS category_count " + - "FROM file_category_master cm " + - "LEFT JOIN ( " + - " SELECT file_category, COUNT(*) AS category_count " + - " FROM pensioner_details " + - " WHERE (? IS NULL OR dept_id = ?) " + - " AND is_closed='0' " + - " GROUP BY file_category " + - ") pd ON cm.id = pd.file_category " + - "LEFT JOIN ( " + - " SELECT file_category, COUNT(*) AS category_count " + - " FROM cps_pensioner_details " + - " WHERE (? IS NULL OR dept_id = ?) " + - " GROUP BY file_category " + - ") cps ON cm.id = cps.file_category"; - - return jdbcTemplate.queryForList(sql, deptId, deptId, deptId, deptId); - - - } public List> fetchchartCategoryCounts(String deptId, String startDate, String endDate) { - String sql = "SELECT cm.file_name, cm.id, " + - " COALESCE(pd.category_count, 0) + COALESCE(cps.category_count, 0) AS category_count " + - "FROM file_category_master cm " + - "LEFT JOIN ( " + - " SELECT file_category, COUNT(*) AS category_count " + - " FROM pensioner_details " + - " WHERE (? IS NULL OR dept_id = ?) " + - " AND (? IS NULL OR date(created_date) >= ?) " + - " AND (? IS NULL OR date(created_date) <= ?) " + - " AND is_closed='0' " + - " GROUP BY file_category " + - ") pd ON cm.id = pd.file_category " + - "LEFT JOIN ( " + - " SELECT file_category, COUNT(*) AS category_count " + - " FROM gcc_pensioner.cps_pensioner_details " + - " WHERE (? IS NULL OR dept_id = ?) " + - " AND (? IS NULL OR date(created_date) >= ?) " + - " AND (? IS NULL OR date(created_date) <= ?) " + - " GROUP BY file_category " + - ") cps ON cm.id = cps.file_category"; - - return jdbcTemplate.queryForList( - sql, deptId, deptId, startDate, startDate, endDate, endDate, - deptId, deptId, startDate, startDate, endDate, endDate - ); - } - public List> getStageWiseCounts(String deptId, String startDate, String endDate) { - String sql = - "WITH categories AS (" + - " SELECT 'Audit Pending' AS category UNION ALL " + - " SELECT 'Department Pending' UNION ALL " + - " SELECT 'Pension Pending' UNION ALL " + - " SELECT 'Completed' " + - ") " + - "SELECT c.category, COALESCE(SUM(cr.category_count), 0) AS category_count " + - "FROM categories c " + - "LEFT JOIN ( " + - " SELECT category, SUM(category_count) AS category_count FROM ( " + - " SELECT " + - " CASE " + - " WHEN sm.id IN (1, 3) THEN 'Audit Pending' " + - " WHEN sm.id IN (2, 5, 6, 9) THEN 'Department Pending' " + - " WHEN sm.id IN (4, 7, 8, 10) THEN 'Pension Pending' " + - " WHEN sm.id = 11 THEN 'Completed' " + - " END AS category, " + - " COUNT(*) AS category_count " + - " FROM gcc_pensioner.pensioner_details pd " + - " INNER JOIN gcc_pensioner.file_status_master sm ON pd.file_status = sm.id " + - " WHERE (? IS NULL OR pd.dept_id = ?) " + - " AND (? IS NULL OR DATE(pd.created_date) >= ?) " + - " AND (? IS NULL OR DATE(pd.created_date) <= ?) " + - " AND pd.is_closed='0' " + - " GROUP BY category " + - - " UNION ALL " + - - " SELECT " + - " CASE " + - " WHEN sm.id IN (1, 3) THEN 'Audit Pending' " + - " WHEN sm.id IN (2, 5, 6, 9) THEN 'Department Pending' " + - " WHEN sm.id IN (4, 7, 8, 10) THEN 'Pension Pending' " + - " WHEN sm.id = 11 THEN 'Completed' " + - " END AS category, " + - " COUNT(*) AS category_count " + - " FROM gcc_pensioner.cps_pensioner_details cps " + - " INNER JOIN gcc_pensioner.file_status_master sm ON cps.file_status = sm.id " + - " WHERE (? IS NULL OR cps.dept_id = ?) " + - " AND (? IS NULL OR DATE(cps.created_date) >= ?) " + - " AND (? IS NULL OR DATE(cps.created_date) <= ?) " + - " GROUP BY category " + - " ) AS combined_results " + - " GROUP BY category " + - ") cr ON c.category = cr.category " + - "GROUP BY c.category;"; - - return jdbcTemplate.queryForList( - sql, deptId, deptId, startDate, startDate, endDate, endDate, - deptId, deptId, startDate, startDate, endDate, endDate - ); - } - - - - //simple - public List> fetchCategorysearchCounts(String startdate, String enddate,String deptId) { - String sql = "SELECT cm.file_name, COALESCE(SUM(category_count), 0) AS category_count " + - "FROM gcc_pensioner.file_category_master cm " + - "LEFT JOIN ( " + - " SELECT pd.file_category, COUNT(pd.file_category) AS category_count " + - " FROM gcc_pensioner.pensioner_details pd " + - " WHERE (? IS NULL OR DATE(pd.created_date) = ? OR (DATE(pd.created_date) BETWEEN ? AND ?)) " + - " AND (? IS NULL OR pd.dept_id = ?) " + - " AND pd.is_closed='0' " + - " GROUP BY pd.file_category " + - - " UNION ALL " + - " SELECT cps.file_category, COUNT(cps.file_category) AS category_count " + - " FROM gcc_pensioner.cps_pensioner_details cps " + - " WHERE (? IS NULL OR DATE(cps.created_date) = ? OR (DATE(cps.created_date) BETWEEN ? AND ?)) " + - " AND (? IS NULL OR cps.dept_id = ?) " + - " GROUP BY cps.file_category " + - ") combined_counts ON cm.id = combined_counts.file_category " + - "GROUP BY cm.file_name"; - - return jdbcTemplate.queryForList(sql, new Object[]{ - startdate, startdate, startdate, enddate, deptId, deptId, // For `pd.created_date` and `dept_id` - startdate, startdate, startdate, enddate, deptId, deptId // For `cps.created_date` and `dept_id` - }); - - } - } -//total 5 changes for is_closed=0 -/* this is with pendency file category - * "SELECT file_name, SUM(category_count) AS category_count " + - "FROM ( " + - " SELECT cm.file_name, COUNT(pd.file_category) AS category_count " + - " FROM gcc_pensioner.file_category_master cm " + - " LEFT JOIN gcc_pensioner.pensioner_details pd " + - " ON pd.file_category = cm.id " + - " GROUP BY cm.file_name " + - " UNION ALL " + - " SELECT cm.file_name, COUNT(cps.file_category) AS category_count " + - " FROM gcc_pensioner.file_category_master cm " + - " LEFT JOIN gcc_pensioner.cps_pensioner_details cps " + - " ON cps.file_category = cm.id " + - " GROUP BY cm.file_name " + - ") combined_counts " + - "GROUP BY file_name";--------------------------------------------------------------------------"SELECT cm.file_name, COALESCE(SUM(category_count), 0) AS category_count " + - "FROM ( " + - " SELECT cm.file_name, COUNT(pd.file_category) AS category_count " + - " FROM gcc_pensioner.file_category_master cm " + - " LEFT JOIN gcc_pensioner.pensioner_details pd " + - " ON pd.file_category = cm.id " + - " AND (? IS NULL OR (? = ? AND DATE(pd.created_date) = ?) OR (DATE(pd.created_date) >= ? AND DATE(pd.created_date) <= ?)) " + - " GROUP BY cm.file_name " + - " UNION ALL " + - " SELECT cm.file_name, COUNT(cps.file_category) AS category_count " + - " FROM gcc_pensioner.file_category_master cm " + - " LEFT JOIN gcc_pensioner.cps_pensioner_details cps " + - " ON cps.file_category = cm.id " + - " AND (? IS NULL OR (? = ? AND DATE(cps.created_date) = ?) OR (DATE(cps.created_date) >= ? AND DATE(cps.created_date) <= ?)) " + - " GROUP BY cm.file_name " + - ") combined_counts " + - "RIGHT JOIN gcc_pensioner.file_category_master cm " + - "ON combined_counts.file_name = cm.file_name " + - "GROUP BY cm.file_name"; */ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentForwardService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentForwardService.java deleted file mode 100644 index 7fed9dc1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentForwardService.java +++ /dev/null @@ -1,221 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class DepartmentForwardService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public DepartmentForwardService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchDepatmentForwardEmpfiles(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_status=4 AND file_category=? AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,file_cat); - } - - @Transactional - public boolean updateEntryDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus5Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - String updateQuery = "UPDATE pensioner_details SET file_status = ?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,dateToAudit, remarks,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - @Transactional - public boolean savehistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String retirement_date = emp.get("retirement_date").toString(); - String retirement_class = emp.get("retirement_class").toString(); - String type_of_retirement = emp.get("type_of_retirement").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,retirement_class,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,type_of_retirement,retirement_date,retirement_class,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - //save the updatedfamilypensionReturn - @Transactional - public boolean saveFamilyPensionForwardHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - String sericeDeath = emp.get("service_death").toString(); - String relationshipDeceased = emp.get("relationship_deceased").toString(); - String sanctionedGis = emp.get("sanctioned_gis_amount").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death,relationship_deceased ,sanctioned_gis_amount,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,sericeDeath,relationshipDeceased,sanctionedGis,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - //update save pendency history - @Transactional - public boolean savePendencyForwardHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String retirementClass = emp.get("retirement_class").toString(); - String retirementDate=emp.get("retirement_date").toString(); - //String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - - String typeOfCategory=emp.get("file_category_name").toString(); - String typeOfRetirement=emp.get("type_of_retirement").toString(); - - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,retirement_class,retirement_date,file_category_name,type_of_retirement,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,retirementClass,retirementDate,typeOfCategory,typeOfRetirement,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentReceivedService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentReceivedService.java deleted file mode 100644 index b38f9125..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentReceivedService.java +++ /dev/null @@ -1,701 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; - -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class DepartmentReceivedService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public DepartmentReceivedService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchPensionReceivedEmpfiles(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND (file_status=7 OR file_status=8) AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,file_cat); - } - - public List> fetchPensionbenefitsById(String tempId) { - String query = "SELECT * " + - "FROM pension_benefits " + - "WHERE temp_id=?"; - - - return jdbcTemplate.queryForList(query,tempId); - } - - @Transactional - public boolean updateEntryCompletedDetails(Map requestData) { - try { - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby = (String) requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - String file_pending = (String) requestData.get("file_pending"); - String pension_number = (String) requestData.get("pension_number"); - String ledger_number = (String) requestData.get("ledger_number"); - String benefit_pension = (String) requestData.get("benefit_pension"); - String benefit_dcrg = requestData.get("benefit_dcrg") != null ? requestData.get("benefit_dcrg").toString() : null; - String benefit_commutation = (String) requestData.get("benefit_commutation"); - - String benefit_pension_amount = (String) requestData.get("benefit_pension_amount")!= null ? requestData.get("benefit_pension_amount").toString() : null; - String benefit_dcrg_amount = requestData.get("benefit_dcrg_amount") != null ? requestData.get("benefit_dcrg_amount").toString() : null; - String benefit_commutation_amount = (String) requestData.get("benefit_commutation_amount") != null ? requestData.get("benefit_commutation_amount").toString() : null; - - int deptId = Integer.parseInt(dept_Id); - int filestatus=0; - String file_entry_type=""; - - boolean check = checkTempPresent(tempId); - - - if (check) { - String updateQuery1 = "UPDATE pension_benefits SET file_pending = ?, pension_number = ?, ledger_number = ?, benefit_pension = ?, benefit_pension_amount = ?, benefit_dcrg = ?, benefit_dcrg_amount = ?, benefit_commutation = ?, benefit_commutation_amount = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; - int rowsUpdated3 = jdbcTemplate.update(updateQuery1, file_pending, pension_number, ledger_number, benefit_pension, benefit_pension_amount, benefit_dcrg, benefit_dcrg_amount, benefit_commutation, benefit_commutation_amount, tempId); - } else { - String benefitQuery = "INSERT INTO pension_benefits (emp_no, temp_id, file_pending, pension_number, ledger_number, benefit_pension, benefit_pension_amount, benefit_dcrg, benefit_dcrg_amount, benefit_commutation, benefit_commutation_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - int rowsUpdated2 = jdbcTemplate.update(benefitQuery, empNo, tempId, file_pending, pension_number, ledger_number, benefit_pension, benefit_pension_amount, benefit_dcrg, benefit_dcrg_amount, benefit_commutation, benefit_commutation_amount); - } - -// if ("yes".equalsIgnoreCase(benefit_dcrg)) { - - - filestatus = CheckFieldsInDept(tempId) ? (CheckFieldsInPensioner(tempId) ? getFileStatus.getFileStatus11Id() : getFileStatus.getFileStatus10Id() ) : getFileStatus.getFileStatus9Id(); - - if(filestatus == 11) { - file_entry_type="FILE_COMPLETED"; - } - else if(filestatus == 10) { - file_entry_type="PENSION_PARTIAL"; - } - else { - file_entry_type="DEPARTMENT_PARTIAL"; - } - -// } -// else if("no".equalsIgnoreCase(benefit_dcrg) || "no".equalsIgnoreCase(benefit_pension)){ -// -// filestatus = getFileStatus.getFileStatus10Id(); -// file_entry_type="PENSION_PARTIAL"; -// } -// else if(benefit_dcrg==null) -// { -// filestatus = getFileStatus.getFileStatus9Id(); -// file_entry_type="DEPARTMENT_PARTIAL"; -// } - - //getFileStatus.getFileStatus2Id(); - - - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - - String updateQuery = "UPDATE pensioner_details SET file_entry_type=?,file_status = ?, file_moved_date = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,file_entry_type, filestatus, dateToAudit, remarks, tempId); - - if (rowsUpdated > 0) { - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks, temp_id) VALUES (?, ?, ?, ?, ?, ?)"; - int rowsUpdated1 = jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks, tempId); - - if (rowsUpdated1 > 0) { - - return true; - } - } - return false; - } catch (NumberFormatException e) { - System.err.println("Error parsing department ID: " + e.getMessage()); - return false; - } catch (DataAccessException e) { - System.err.println("Database operation failed: " + e.getMessage()); - return false; - } catch (Exception e) { - System.err.println("Unexpected error: " + e.getMessage()); - return false; - } - } - - - - private boolean checkTempPresent(String tempId) { - String query = "SELECT EXISTS (SELECT 1 FROM pension_benefits WHERE temp_id = ?)"; - - return Boolean.TRUE.equals(jdbcTemplate.queryForObject(query, Boolean.class, tempId)); - } - - private boolean CheckFieldsInDept(String tempId) { - - // Define the SQL query - String sql = "SELECT CASE " + - "WHEN (gpf = 'yes' OR gpf = '90') AND spfgs = 'yes' AND private_affairs = 'yes' AND dcrg = 'yes' THEN true " + - "ELSE false END AS allYes " + - "FROM zone_benefits " + - "WHERE temp_id = ?"; - - - try { - // Use queryForObject to get a single boolean result - Boolean result = jdbcTemplate.queryForObject(sql, Boolean.class, tempId); - return result != null && result; // Return the result if not null - } catch (Exception e) { - e.printStackTrace(); // Log the exception if needed - } - - return false; // Return false if an exception occurs - } - - private boolean CheckFieldsInPensioner(String tempId) { - - // Define the SQL query - String sql = "SELECT CASE " + - "WHEN benefit_pension = 'yes' AND benefit_dcrg = 'yes' THEN true " + - "ELSE false END AS allYes " + - "FROM pension_benefits " + - "WHERE temp_id = ?"; - - - try { - // Use queryForObject to get a single boolean result - Boolean result = jdbcTemplate.queryForObject(sql, Boolean.class, tempId); - return result != null && result; // Return the result if not null - } catch (Exception e) { - e.printStackTrace(); // Log the exception if needed - } - - return false; // Return false if an exception occurs - } - - @Transactional - public boolean saveRetirementCompletedhistory(List> emp_details,List> pension_details,String filemovedby) { - - try { - - int file_Cat=0; - - if (!emp_details.isEmpty()) { - Map firstEmployeeDetails = emp_details.get(0); - Object fileCatObj = firstEmployeeDetails.get("file_category"); - - if (fileCatObj != null) { - try { - file_Cat = Integer.parseInt(fileCatObj.toString()); - System.out.println("Parsed file_category: " + file_Cat); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_category: " + fileCatObj); - } - } else { - System.out.println("file_category is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - // Batch update for employee details - if(file_Cat==1) { - String empInsertQuery = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, filemovedby); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - }); - } - - if(file_Cat==2) - { - String empInsertQuery1 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death, " + - "relationship_deceased, sanctioned_gis_amount, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery1, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("service_death").toString()); - ps.setString(6, emp.get("relationship_deceased").toString()); - ps.setString(7, emp.get("sanctioned_gis_amount").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, filemovedby); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration").toString()); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for family Pension"); - } - - if(file_Cat==3) - { - String empInsertQuery2 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement, " + - "file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending,retirement_class,retirement_date) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery2, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("file_moved_date").toString()); - ps.setString(7, emp.get("remarks").toString()); - ps.setInt(8, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(9, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(10, emp.get("file_entry_type").toString()); - ps.setString(11, filemovedby); - ps.setInt(12, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(13, emp.get("file_category_name").toString()); - ps.setString(14, emp.get("temp_id").toString()); - ps.setString(15, emp.get("pending_duration").toString()); - ps.setString(16, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - ps.setString(17, emp.get("retirement_class").toString()); - ps.setString(18, emp.get("retirement_date").toString()); - }); - - System.out.println("rows inserted in pd history for pending"); - } - - String pensionInsertQuery = - "INSERT INTO pension_benefits_history (emp_no,temp_id,file_pending,pension_number,ledger_number,benefit_pension,benefit_pension_amount,benefit_dcrg,benefit_dcrg_amount,benefit_commutation,benefit_commutation_amount,file_moved_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; - - jdbcTemplate.batchUpdate(pensionInsertQuery, pension_details, pension_details.size(), (ps, pension) -> { - ps.setString(1, pension.get("emp_no").toString()); - ps.setString(2, pension.get("temp_id").toString()); - ps.setString(3, pension.get("file_pending").toString()); - ps.setString(4, pension.get("pension_number").toString()); - ps.setString(5, pension.get("ledger_number").toString()); - ps.setString(6, pension.get("benefit_pension").toString()); - ps.setString(7, pension.get("benefit_pension_amount") != null ? pension.get("benefit_pension_amount").toString() : null); - ps.setString(8, pension.get("benefit_dcrg") != null ? pension.get("benefit_dcrg").toString() : null); - ps.setString(9, pension.get("benefit_dcrg_amount") != null ? pension.get("benefit_dcrg_amount").toString() : null); - ps.setString(10, pension.get("benefit_commutation").toString()); - ps.setString(11, pension.get("benefit_commutation_amount") != null ? pension.get("benefit_commutation_amount").toString() : null); - ps.setString(12, filemovedby); - - - - }); - - System.out.println("rows inserted in pension history for family Pension"); - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - @Transactional - public boolean updateEntryPendingDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - String file_pending = (String) requestData.get("file_pending"); - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus8Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - - String file_entry_type="FILE_PENDING"; - - String updateQuery = "UPDATE pensioner_details SET file_status = ?,file_entry_type=?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,file_entry_type,dateToAudit, remarks,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - if(rowsUpdated1>0) - { - // Insert into zone benefits - String benefitQuery="INSERT INTO pension_benefits (emp_no,temp_id,file_pending) VALUES (?,?,?)"; - int rowsUpdated2=jdbcTemplate.update(benefitQuery,empNo,tempId,file_pending); - System.out.println("Rows inserted in pb1:"+rowsUpdated2); - return true; - } - else - { - return false; - } - } - else { - return false; - } - - } - - @Transactional - public boolean saveRetirementPendinghistory(List> emp_details,List> pension_details,String filemovedby) { - try { - - int file_Cat=0; - - if (!emp_details.isEmpty()) { - Map firstEmployeeDetails = emp_details.get(0); - Object fileCatObj = firstEmployeeDetails.get("file_category"); - - if (fileCatObj != null) { - try { - file_Cat = Integer.parseInt(fileCatObj.toString()); - System.out.println("Parsed file_category: " + file_Cat); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_category: " + fileCatObj); - } - } else { - System.out.println("file_category is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - // Batch update for employee details - if(file_Cat==1) { - String empInsertQuery = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, filemovedby); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - }); - } - - if(file_Cat==2) - { - String empInsertQuery1 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death, " + - "relationship_deceased, sanctioned_gis_amount, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery1, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("service_death").toString()); - ps.setString(6, emp.get("relationship_deceased").toString()); - ps.setString(7, emp.get("sanctioned_gis_amount").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, filemovedby); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration").toString()); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for family Pension"); - } - - if(file_Cat==3) - { - String empInsertQuery2 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement, " + - "file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery2, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("file_moved_date").toString()); - ps.setString(7, emp.get("remarks").toString()); - ps.setInt(8, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(9, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(10, emp.get("file_entry_type").toString()); - ps.setString(11, filemovedby); - ps.setInt(12, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(13, emp.get("file_category_name").toString()); - ps.setString(14, emp.get("temp_id").toString()); - ps.setString(15, emp.get("pending_duration").toString()); - ps.setString(16, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for pending"); - } - - String pensionInsertQuery = - "INSERT INTO pension_benefits_history (emp_no,temp_id,file_pending,file_moved_by) VALUES (?,?,?,?)"; - - jdbcTemplate.batchUpdate(pensionInsertQuery, pension_details, pension_details.size(), (ps, pension) -> { - ps.setString(1, pension.get("emp_no").toString()); - ps.setString(2, pension.get("temp_id").toString()); - ps.setString(3, pension.get("file_pending").toString()); - ps.setString(4, filemovedby); - - }); - System.out.println("rows inserted in pension history for family Pension"); - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - @Transactional - public boolean updateEntryReturnDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - String file_entry_type="FILE_RETURNED"; - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus6Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - String updateQuery = "UPDATE pensioner_details SET file_status = ?,file_entry_type=?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,file_entry_type,dateToAudit, remarks,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - return true; - - } - else { - return false; - } - - } - - @Transactional - public boolean saveRetirementreturnhistory(List> emp_details,String filemovedby) { - try { - - int file_Cat=0; - - if (!emp_details.isEmpty()) { - Map firstEmployeeDetails = emp_details.get(0); - Object fileCatObj = firstEmployeeDetails.get("file_category"); - - if (fileCatObj != null) { - try { - file_Cat = Integer.parseInt(fileCatObj.toString()); - System.out.println("Parsed file_category: " + file_Cat); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_category: " + fileCatObj); - } - } else { - System.out.println("file_category is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - // Batch update for employee details - if(file_Cat==1) { - String empInsertQuery = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, filemovedby); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - }); - } - - if(file_Cat==2) - { - String empInsertQuery1 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death, " + - "relationship_deceased, sanctioned_gis_amount, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery1, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("service_death").toString()); - ps.setString(6, emp.get("relationship_deceased").toString()); - ps.setString(7, emp.get("sanctioned_gis_amount").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, filemovedby); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration").toString()); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for family Pension"); - } - - if(file_Cat==3) - { - String empInsertQuery2 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement, " + - "file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery2, emp_details, emp_details.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("file_moved_date").toString()); - ps.setString(7, emp.get("remarks").toString()); - ps.setInt(8, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(9, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(10, emp.get("file_entry_type").toString()); - ps.setString(11, filemovedby); - ps.setInt(12, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(13, emp.get("file_category_name").toString()); - ps.setString(14, emp.get("temp_id").toString()); - ps.setString(15, emp.get("pending_duration").toString()); - ps.setString(16, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for pending"); - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptAuditService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptAuditService.java deleted file mode 100644 index 60f625c5..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptAuditService.java +++ /dev/null @@ -1,306 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - - -@Service -public class DeptAuditService { - - - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public DeptAuditService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - - public List> fetchEmployeeDetailsByTable(Integer deptId,Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE dept_id=? AND file_category=? AND (file_status=1 OR file_status=3) AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,deptId,file_cat); - } - - public List> fetchEmployeeById(String tempId) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE temp_id=?"; - - - return jdbcTemplate.queryForList(query,tempId); - } - - - - public List> fetchEmployeeByIdCps(String tempId) { - String query = "SELECT * " + - "FROM cps_pensioner_details " + - "WHERE temp_id=?"; - - - return jdbcTemplate.queryForList(query,tempId); - } - - public List> fetchDetailsWithZoneBenefitsById(String tempId) { - String query = "SELECT pd.*, zb.gpf, zb.gpf_amount, zb.spfgs, zb.spfgs_amount, zb.dcrg, " + - "zb.private_affairs, zb.private_affairs_amount, zb.recovery_emp " + - "FROM pensioner_details pd " + - "LEFT JOIN zone_benefits zb ON pd.temp_id = zb.temp_id " + - "WHERE pd.temp_id = ?"; - - return jdbcTemplate.queryForList(query, tempId); - }// - - public List> fetchFilePendingBenefits(String tempId) { - - String query = "SELECT pd.*, zb.gpf, zb.gpf_amount, zb.spfgs, zb.spfgs_amount, zb.dcrg, " + - "zb.private_affairs, zb.private_affairs_amount, zb.recovery_emp,pb.file_pending " + - "FROM pensioner_details pd " + - "LEFT JOIN zone_benefits zb ON pd.temp_id = zb.temp_id " + - "LEFT JOIN pension_benefits pb ON pd.temp_id = pb.temp_id " + - "WHERE pd.temp_id = ?"; - - return jdbcTemplate.queryForList(query, tempId); - } - - - public List> fetchPartialCompleted(String tempId) { - - String query = "SELECT pd.*, zb.gpf, zb.gpf_amount, zb.spfgs, zb.spfgs_amount, zb.dcrg, " + - "zb.private_affairs, zb.private_affairs_amount, zb.recovery_emp,pb.file_pending," + - "pb.pension_number,pb.ledger_number,pb.benefit_pension,pb.benefit_pension_amount,pb.benefit_dcrg,pb.benefit_dcrg_amount,pb.benefit_commutation,pb.benefit_commutation_amount " + - "FROM pensioner_details pd " + - "LEFT JOIN zone_benefits zb ON pd.temp_id = zb.temp_id " + - "LEFT JOIN pension_benefits pb ON pd.temp_id = pb.temp_id " + - "WHERE pd.temp_id = ?"; - - return jdbcTemplate.queryForList(query, tempId); - } - - - - - public List> fetchFileMovementHistory(String tempId) { - // Query to fetch file movement history - String query = "SELECT fh.file_moved_date AS fileMovedDateHistory, " + - "fm.file_status AS fileStatusHistory, " + - "fh.remarks AS remarksHistory " + - "FROM file_movement_history fh " + - "JOIN file_status_master fm ON fh.file_status = fm.id " + - "WHERE fh.temp_id = ?"; - - return jdbcTemplate.queryForList(query,tempId); - } - - - @Transactional - public boolean updateEntryDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus2Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String file_entry_type="AUDIT_RETURNED"; - - // Update file_status in pensioner_details - String updateQuery = "UPDATE pensioner_details SET file_status = ?, file_entry_type =?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,file_entry_type,dateToAudit, remarks,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - @Transactional - public boolean savehistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String retirement_date = emp.get("retirement_date").toString(); - String retirement_class = emp.get("retirement_class").toString(); - String type_of_retirement = emp.get("type_of_retirement").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,retirement_class,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,type_of_retirement,retirement_date,retirement_class,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - //save the updatedfamilypension details - @Transactional - public boolean saveFamilyPensionHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - String serviceDeath = emp.get("service_death").toString(); - String relationshipDeceased = emp.get("relationship_deceased").toString(); - String sanctionedGis = emp.get("sanctioned_gis_amount").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death,relationship_deceased ,sanctioned_gis_amount,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,serviceDeath,relationshipDeceased,sanctionedGis,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - //save the pendency details - @Transactional - public boolean savePendencyHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String retirementClass = emp.get("retirement_class").toString(); - String retirementDate=emp.get("retirement_date").toString(); - //String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - - String typeOfCategory=emp.get("file_category_name").toString(); - String typeOfRetirement=emp.get("type_of_retirement").toString(); - - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,retirement_class,retirement_date,file_category_name,type_of_retirement,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,retirementClass,retirementDate,typeOfCategory,typeOfRetirement,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptPartiallyCompService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptPartiallyCompService.java deleted file mode 100644 index 8141b4df..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptPartiallyCompService.java +++ /dev/null @@ -1,363 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class DeptPartiallyCompService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public DeptPartiallyCompService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchDepatmentPartialEmpfiles(Integer deptId,Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_status=9 AND dept_id=? AND file_category=? AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,deptId,file_cat); - } - - @Transactional - public boolean updateEntryCompletedDetails(Map requestData) { - try { - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby = (String) requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - - String gpf = (String) requestData.get("gpf"); - String private_affairs = (String) requestData.get("private_affairs"); - String spfgs = (String) requestData.get("spfgs"); - String recovery_emp = requestData.get("recovery_emp") != null ? requestData.get("recovery_emp").toString() : null; - String dcrg = (String) requestData.get("dcrg"); - - String gpfAmount = requestData.get("gpfAmount") != null ? requestData.get("gpfAmount").toString() : null; - String private_affairs_amount = requestData.get("private_affairs_amount") != null ? requestData.get("private_affairs_amount").toString() : null; - String spfgs_amount = requestData.get("spfgs_amount") != null ? requestData.get("spfgs_amount").toString() : null; - - - String pension_number = (String) requestData.get("pension_number"); - String ledger_number = (String) requestData.get("ledger_number"); - String benefit_pension = (String) requestData.get("benefit_pension"); - String benefit_dcrg = (String) requestData.get("benefit_dcrg"); - String benefit_commutation = (String) requestData.get("benefit_commutation"); - - String benefit_pension_amount = requestData.get("benefit_pension_amount")!= null ? requestData.get("benefit_pension_amount").toString() : null; - String benefit_dcrg_amount = requestData.get("benefit_dcrg_amount") != null ? requestData.get("benefit_dcrg_amount").toString() : null; - String benefit_commutation_amount = requestData.get("benefit_commutation_amount") != null ? requestData.get("benefit_commutation_amount").toString() : null; - - - int deptId = Integer.parseInt(dept_Id); - int filestatus; - String file_entry_type=""; - - - - String updateQuery1 = "UPDATE zone_benefits SET gpf = ?, gpf_amount = ?, spfgs = ?, spfgs_amount = ?, dcrg = ?, private_affairs = ?, private_affairs_amount = ?, recovery_emp = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; - int rowsUpdated3 = jdbcTemplate.update(updateQuery1, gpf, gpfAmount, spfgs, spfgs_amount, dcrg, private_affairs, private_affairs_amount, recovery_emp, tempId); - System.out.println("Rows updated in zb: " + rowsUpdated3); - - if (rowsUpdated3 > 0) { - -// String updateQuery2 = "UPDATE pension_benefits SET pension_number = ?, ledger_number = ?, benefit_pension = ?, benefit_pension_amount = ?, benefit_dcrg = ?, benefit_dcrg_amount = ?, benefit_commutation = ?, benefit_commutation_amount = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; -// int rowsUpdated2 = jdbcTemplate.update(updateQuery2, pension_number, ledger_number, benefit_pension, benefit_pension_amount, benefit_dcrg, benefit_dcrg_amount, benefit_commutation, benefit_commutation_amount, tempId); -// System.out.println("Rows updated in pb: " + rowsUpdated2); - - filestatus = CheckFieldsforComplete(tempId) ? getFileStatus.getFileStatus11Id() : CheckFieldsforDept(tempId) ? getFileStatus.getFileStatus10Id() : getFileStatus.getFileStatus9Id(); - System.out.println("filestatus inside service="+filestatus); - - if(filestatus==11) - { - file_entry_type="FILE_COMPLETED"; - } - if(filestatus==9) { - file_entry_type="DEPARTMENT_PARTIAL"; - } - if(filestatus==10) { - file_entry_type="PENSION_PARTIAL"; - } - - - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - - String updateQuery = "UPDATE pensioner_details SET file_entry_type=?,file_status = ?, file_moved_date = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,file_entry_type, filestatus, dateToAudit, remarks, tempId); - System.out.println("Rows updated in pd: " + rowsUpdated); - - if (rowsUpdated > 0) { - - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks, temp_id) VALUES (?, ?, ?, ?, ?, ?)"; - int rowsUpdated1 = jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks, tempId); - System.out.println("Rows updated in fmh: " + rowsUpdated1); - - return true; - } - - } - return false; - } catch (NumberFormatException e) { - System.err.println("Error parsing department ID: " + e.getMessage()); - return false; - } catch (DataAccessException e) { - System.err.println("Database operation failed: " + e.getMessage()); - return false; - } catch (Exception e) { - System.err.println("Unexpected error: " + e.getMessage()); - return false; - } - } - - @Transactional - public boolean saveHistory(List> empDetails, List> zoneBenefits, List> pension_details, String fileMovedBy) { - try { - int file_Cat=0; - - if (!empDetails.isEmpty()) { - Map firstEmployeeDetails = empDetails.get(0); - Object fileCatObj = firstEmployeeDetails.get("file_category"); - - if (fileCatObj != null) { - try { - file_Cat = Integer.parseInt(fileCatObj.toString()); - System.out.println("Parsed file_category: " + file_Cat); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_category: " + fileCatObj); - } - } else { - System.out.println("file_category is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - // Batch update for employee details - if(file_Cat==1) { - String empInsertQuery = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - }); - } - - if(file_Cat==2) - { - String empInsertQuery1 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death, " + - "relationship_deceased, sanctioned_gis_amount, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery1, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("service_death").toString()); - ps.setString(6, emp.get("relationship_deceased").toString()); - ps.setString(7, emp.get("sanctioned_gis_amount").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration").toString()); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for family Pension"); - } - - if(file_Cat==3) - { - String empInsertQuery2 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement, " + - "file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending,retirement_class,retirement_date) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery2, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("file_moved_date").toString()); - ps.setString(7, emp.get("remarks").toString()); - ps.setInt(8, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(9, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(10, emp.get("file_entry_type").toString()); - ps.setString(11, fileMovedBy); - ps.setInt(12, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(13, emp.get("file_category_name").toString()); - ps.setString(14, emp.get("temp_id").toString()); - ps.setString(15, emp.get("pending_duration").toString()); - ps.setString(16, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - ps.setString(17, emp.get("retirement_class").toString()); - ps.setString(18, emp.get("retirement_date").toString()); - - }); - - System.out.println("rows inserted in pd history for pendency"); - } - - // Batch update for zone benefits - String zoneInsertQuery = - "INSERT INTO zone_benefits_history (emp_no, temp_id, gpf, gpf_amount, spfgs, spfgs_amount, dcrg, " + - "private_affairs, private_affairs_amount, recovery_emp, file_moved_by) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(zoneInsertQuery, zoneBenefits, zoneBenefits.size(), (ps, zone) -> { - ps.setString(1, zone.get("emp_no").toString()); - ps.setString(2, zone.get("temp_id").toString()); - ps.setString(3, zone.get("gpf").toString()); - ps.setString(4, zone.get("gpf_amount") != null ? zone.get("gpf_amount").toString() : null); - ps.setString(5, zone.get("spfgs").toString()); - ps.setString(6, zone.get("spfgs_amount") != null ? zone.get("spfgs_amount").toString() : null); - ps.setString(7, zone.get("dcrg").toString()); - ps.setString(8, zone.get("private_affairs").toString()); - ps.setString(9, zone.get("private_affairs_amount") != null ? zone.get("private_affairs_amount").toString() : null); - ps.setString(10, zone.get("recovery_emp") != null ? zone.get("recovery_emp").toString() : null); - ps.setString(11, fileMovedBy); - }); - - // Batch update for pension benefits -// String pensionInsertQuery = -// "INSERT INTO pension_benefits_history (emp_no,temp_id,file_pending,pension_number,ledger_number,benefit_pension,benefit_pension_amount,benefit_dcrg,benefit_dcrg_amount,benefit_commutation,benefit_commutation_amount,file_moved_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; -// -// jdbcTemplate.batchUpdate(pensionInsertQuery, pension_details, pension_details.size(), (ps, pension) -> { -// ps.setString(1, pension.get("emp_no").toString()); -// ps.setString(2, pension.get("temp_id").toString()); -// ps.setString(3, pension.get("file_pending").toString()); -// ps.setString(4, pension.get("pension_number").toString()); -// ps.setString(5, pension.get("ledger_number").toString()); -// ps.setString(6, pension.get("benefit_pension").toString()); -// ps.setString(7, pension.get("benefit_pension_amount") != null ? pension.get("benefit_pension_amount").toString() : null); -// ps.setString(8, pension.get("benefit_dcrg").toString()); -// ps.setString(9, pension.get("benefit_dcrg_amount") != null ? pension.get("benefit_dcrg_amount").toString() : null); -// ps.setString(10, pension.get("benefit_commutation").toString()); -// ps.setString(11, pension.get("benefit_commutation_amount") != null ? pension.get("benefit_commutation_amount").toString() : null); -// ps.setString(12, fileMovedBy); -// -// }); - - return true; // All insertions succeeded - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - private boolean CheckFieldsforComplete(String tempId) { - - // Define the SQL query - String sql = "SELECT \r\n" - + " CASE \r\n" - + " WHEN (zb.gpf = 'yes' OR zb.gpf = '90') AND zb.spfgs = 'yes' AND zb.private_affairs = 'yes' AND zb.dcrg = 'yes' \r\n" - + " AND pb.benefit_pension = 'yes' AND pb.benefit_dcrg = 'yes' THEN 1 ELSE 0 \r\n" - + " END AS allYes \r\n" - + "FROM zone_benefits AS zb\r\n" - + "JOIN pension_benefits AS pb ON zb.temp_id = pb.temp_id \r\n" - + "WHERE zb.temp_id = ? "; - - - try { - // Use queryForObject to get a single boolean result - Boolean result = jdbcTemplate.queryForObject(sql, Boolean.class, tempId); - - System.out.println("result============ "+result); - - return result != null && result; // Return the result if not null - } catch (Exception e) { - e.printStackTrace(); // Log the exception if needed - } - - return false; // Return false if an exception occurs - } - - private boolean CheckFieldsforDept(String tempId) { - - // Define the SQL query - String sql = "SELECT \r\n" - + " CASE \r\n" - + " WHEN (zb.gpf = 'yes' OR zb.gpf = '90') AND zb.spfgs = 'yes' AND zb.private_affairs = 'yes' AND zb.dcrg = 'yes' \r\n" - + " THEN 1 ELSE 0 \r\n" - + " END AS allYes\r\n" - + "FROM zone_benefits AS zb\r\n" - + "WHERE zb.temp_id = ?"; - - - try { - // Use queryForObject to get a single boolean result - Boolean result = jdbcTemplate.queryForObject(sql, Boolean.class, tempId); - - return result != null && result; // Return the result if not null - } catch (Exception e) { - e.printStackTrace(); // Log the exception if needed - } - - return false; // Return false if an exception occurs - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DropdownService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DropdownService.java deleted file mode 100644 index 3997afac..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DropdownService.java +++ /dev/null @@ -1,45 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class DropdownService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> getRetrimentTypes() { - String sql = "SELECT id,retriment_type FROM type_of_retriment"; - return jdbcTemplate.queryForList(sql); - } - - public List> getCategoryTypes() { - String sql = "SELECT id,category_type FROM type_of_category"; - return jdbcTemplate.queryForList(sql); - } - - public List> getProvisionalReasonTypes() { - String sql = "SELECT id,provisional_reason FROM reason_for_provisional"; - return jdbcTemplate.queryForList(sql); - } - - - - public List> getGisEntryTypes() { - String sql = "SELECT id,gis_entry FROM gis_entry_type"; - return jdbcTemplate.queryForList(sql); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/FileClosingService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/FileClosingService.java deleted file mode 100644 index ef1f2704..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/FileClosingService.java +++ /dev/null @@ -1,200 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class FileClosingService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public FileClosingService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - - public List> fetchEmployeeByTempId(String tempId) { - - System.out.println("inside"); - - String sql = "SELECT * " + - "FROM pensioner_details pd " + - "where pd.file_category=1 and pd.file_status <= 8 and pd.temp_id = ? and pd.is_closed=0 " ; - - - System.out.println("outside"); - System.out.println(sql); - - return jdbcTemplate.queryForList(sql,tempId); - - - } - - - public String getTempId(String empCode,Integer deptId,Integer file_cat) { - String query = "SELECT temp_id FROM pensioner_details WHERE emp_no = ? AND file_category = ? AND dept_id = ?"; - - try { - return jdbcTemplate.queryForObject(query, String.class,empCode,file_cat,deptId); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - - } - - - public List> fetchEmployeeById(String tempId) { - - String sql = "SELECT pd.*, zb.gpf, zb.gpf_amount, zb.spfgs, zb.spfgs_amount, zb.dcrg, " + - "zb.private_affairs, zb.private_affairs_amount, zb.recovery_emp, " + - "pb.file_pending, pb.pension_number, pb.ledger_number, pb.benefit_pension, " + - "pb.benefit_pension_amount, pb.benefit_dcrg, pb.benefit_dcrg_amount " + - "FROM pensioner_details pd " + - "LEFT JOIN zone_benefits zb ON pd.temp_id = zb.temp_id " + - "LEFT JOIN pension_benefits pb ON pd.temp_id = pb.temp_id "+ - "where pd.temp_id = ? "; - - - return jdbcTemplate.queryForList(sql,tempId); - } - - - public boolean updateEntryDetails(Map requestData) { - - System.out.println("requestdata"+requestData); - - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - - String serviceDeath =(String)requestData.get("serviceDeath"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - - int deptId = Integer.parseInt(dept_Id); - int filestatus=getFileStatus.getFileStatus12Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - // Update file_status in pensioner_details - String updateQuery = "update pensioner_details set file_status=?,service_death=?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP,is_closed=1 WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,serviceDeath,dateToAudit, remarks,tempId); - - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - - // save fileclosing details - - public boolean saveclosinghistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String serviceDeath=emp.get("service_death").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String retirement_date = emp.get("retirement_date").toString(); - String retirement_class = emp.get("retirement_class").toString(); - String type_of_retirement = emp.get("type_of_retirement").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,serviceDeath,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - //closed list - - public List> fetchClosingEmployee() { - - String sql = "SELECT * " + - "FROM pensioner_details pd " + - "where pd.file_category=1 and pd.is_closed=1 "; - - - return jdbcTemplate.queryForList(sql); - - - } - - - - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/GetFileStatusService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/GetFileStatusService.java deleted file mode 100644 index 4b25da91..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/GetFileStatusService.java +++ /dev/null @@ -1,141 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class GetFileStatusService { - - @Autowired - public JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public Integer getFileStatus1Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Sent to Audit' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus2Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Returned From Audit' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus3Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Rectify and Sent to Audit' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus4Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Audit Certified' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus5Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'File Forwarded to Department' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus6Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Returned to Department' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus7Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'File Forwarded to Pension' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus8Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Pension Pending' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus9Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'File in Department to complete pending values' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus10Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'File in Pension to complete pending values' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus11Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'File Completed' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } - - public Integer getFileStatus12Id() { - try { - String query = "SELECT id FROM file_status_master WHERE file_status = 'Retirement File Closed' AND isactive = 1 AND isdelete = 0 LIMIT 1"; - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - System.out.println("No matching file_status found, returning default value (0)."); - return 0; // Default value in case no record is found - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/NewEntryService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/NewEntryService.java deleted file mode 100644 index 4502abb2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/NewEntryService.java +++ /dev/null @@ -1,949 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.text.ParseException; - -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -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 javax.sql.DataSource; - -import java.util.Comparator; -import java.util.Date; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class NewEntryService { - - - @Autowired - private JdbcTemplate jdbcTemplate; - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public NewEntryService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - -// old retiment list getting method - -// public Map fetchEmplyeeDetails(String fromDate, String toDate, Integer deptId) { -// Map response = new HashMap<>(); -// -// String apiUrl = appconfig.qaqcurl + "serviceId=common_api" -// + "&jsonResp=Yes" -// + "&subService=getEmpPenDetDuration" -// + "&fromDate=" + fromDate -// + "&toDate=" + toDate -// + "&deptId=" + deptId; -// -// System.out.println("url: " + apiUrl); -// System.out.println("deptId:" + deptId); -// try { -// String rawResponse = restTemplate.getForObject(apiUrl, String.class); -// System.out.println("Raw Response: " + rawResponse); // Debugging step -// -// if (isValidJson(rawResponse)) { -// JsonNode jsonResponse = objectMapper.readTree(rawResponse); -// -// // Extract the "ListResult" array -// JsonNode details = jsonResponse.path("ListResult"); -// -// if (details.isArray() && details.size() > 0) { -// List> list = new ArrayList<>(); -// for (JsonNode detail : details) { -// Map listResult = new HashMap<>(); -// -// listResult.put("RETIREMENT_DATE", getNonNullValue(detail.path("RETIREMENT_DATE"))); -// listResult.put("DEATH_DATE", getNonNullValue(detail.path("DEATH_DATE"))); -// listResult.put("COMMUNITY_NAME", getNonNullValue(detail.path("COMMUNITY_NAME"))); -// listResult.put("GROUP_TYPE", getNonNullValue(detail.path("GROUP_TYPE"))); -// listResult.put("ID_DEPT", getNonNullValue(detail.path("ID_DEPT"))); -// listResult.put("EMPLOYEE_CODE", getNonNullValue(detail.path("EMPLOYEE_CODE"))); -// listResult.put("FUNCTIONARY", getNonNullValue(detail.path("FUNCTIONARY"))); -// listResult.put("IS_HANDICAPPED", getNonNullValue(detail.path("IS_HANDICAPPED"))); -// listResult.put("GENDER", getNonNullValue(detail.path("GENDER"))); -// listResult.put("DATE_OF_BIRTH", getNonNullValue(detail.path("DATE_OF_BIRTH"))); -// listResult.put("DATE_OF_APPOINTMENT", getNonNullValue(detail.path("DATE_OF_APPOINTMENT"))); -// listResult.put("DESIGNATION", getNonNullValue(detail.path("DESIGNATION"))); -// listResult.put("EMPLOYEE_NAME", getNonNullValue(detail.path("EMPLOYEE_NAME"))); -// listResult.put("DEPARTMENT", getNonNullValue(detail.path("DEPARTMENT"))); -// list.add(listResult); -// } -// // Sort the list by RETIREMENT_DATE in ascending order -// list.sort(Comparator.comparing(map -> parseDate(((Map) map).get("RETIREMENT_DATE")))); -// -// response.put("list", list); -// -// } else { -// response.put("list", Collections.emptyList()); -// } -// } else { -// System.err.println("Invalid JSON Response: " + rawResponse); -// response.put("list", Collections.emptyList()); -// } -// -// } catch (Exception e) { -// e.printStackTrace(); -// response.put("list", Collections.emptyList()); -// } -// return response; -// } - - - // new retirement list getting method with condition - public Map fetchEmplyeeDetails(String fromDate, String toDate, Integer deptId) { - Map response = new HashMap<>(); - - String apiUrl = appconfig.qaqcurl + "serviceId=common_api" - + "&jsonResp=Yes" - + "&subService=getEmpPenDetDuration" - + "&fromDate=" + fromDate - + "&toDate=" + toDate - + "&deptId=" + deptId; - - System.out.println("url: " + apiUrl); - System.out.println("deptId:" + deptId); - - try { - String rawResponse = restTemplate.getForObject(apiUrl, String.class); - System.out.println("Raw Response: " + rawResponse); // Debugging step - - if (isValidJson(rawResponse)) { - JsonNode jsonResponse = objectMapper.readTree(rawResponse); - JsonNode details = jsonResponse.path("ListResult"); - - if (details.isArray() && details.size() > 0) { - List> list = new ArrayList<>(); - LocalDate currentDate = LocalDate.now(); // Get today's date - - for (JsonNode detail : details) { - String retirementDateStr = getNonNullValue(detail.path("RETIREMENT_DATE")); - LocalDate retirementDate = parseDate(retirementDateStr); - - // Only add to the list if RETIREMENT_DATE is today or in the future - if (retirementDate != null && !retirementDate.isBefore(currentDate)) { - Map listResult = new HashMap<>(); - listResult.put("RETIREMENT_DATE", retirementDateStr); - listResult.put("DEATH_DATE", getNonNullValue(detail.path("DEATH_DATE"))); - listResult.put("COMMUNITY_NAME", getNonNullValue(detail.path("COMMUNITY_NAME"))); - listResult.put("GROUP_TYPE", getNonNullValue(detail.path("GROUP_TYPE"))); - listResult.put("ID_DEPT", getNonNullValue(detail.path("ID_DEPT"))); - listResult.put("EMPLOYEE_CODE", getNonNullValue(detail.path("EMPLOYEE_CODE"))); - listResult.put("FUNCTIONARY", getNonNullValue(detail.path("FUNCTIONARY"))); - listResult.put("IS_HANDICAPPED", getNonNullValue(detail.path("IS_HANDICAPPED"))); - listResult.put("GENDER", getNonNullValue(detail.path("GENDER"))); - listResult.put("DATE_OF_BIRTH", getNonNullValue(detail.path("DATE_OF_BIRTH"))); - listResult.put("DATE_OF_APPOINTMENT", getNonNullValue(detail.path("DATE_OF_APPOINTMENT"))); - listResult.put("DESIGNATION", getNonNullValue(detail.path("DESIGNATION"))); - listResult.put("EMPLOYEE_NAME", getNonNullValue(detail.path("EMPLOYEE_NAME"))); - listResult.put("DEPARTMENT", getNonNullValue(detail.path("DEPARTMENT"))); - list.add(listResult); - } - } - - // Sort the list by RETIREMENT_DATE in ascending order - list.sort(Comparator.comparing(map -> parseDate(map.get("RETIREMENT_DATE")))); - - response.put("list", list); - } else { - response.put("list", Collections.emptyList()); - } - } else { - System.err.println("Invalid JSON Response: " + rawResponse); - response.put("list", Collections.emptyList()); - } - } catch (Exception e) { - e.printStackTrace(); - response.put("list", Collections.emptyList()); - } - return response; - } - - - - public Map fetchEmplyeeDetailsbyCode(String empCode) { - Map response = new HashMap<>(); - - String apiUrl = appconfig.qaqcurl + "serviceId=common_api" - + "&jsonResp=Yes" - + "&subService=getEmpWorkDet" - + "&empCode=" + empCode; - - System.out.println("url: " + apiUrl); - System.out.println("empCode:" + empCode); - try { - String rawResponse = restTemplate.getForObject(apiUrl, String.class); - System.out.println("Raw Response: " + rawResponse); // Debugging step - - if (isValidJson(rawResponse)) { - JsonNode jsonResponse = objectMapper.readTree(rawResponse); - - // Extract the "ListResult" array - JsonNode details = jsonResponse.path("ListResult"); - - if (details.isArray() && details.size() > 0) { - List> list = new ArrayList<>(); - for (JsonNode detail : details) { - Map listResult = new HashMap<>(); - listResult.put("RETIREMENT_DATE", formatToISODate(getNonNullValue(detail.path("RETIREMENT_DATE")))); - listResult.put("TO_DATE", parseDate(getNonNullValue(detail.path("TO_DATE"))).toString()); - listResult.put("DEATH_DATE", getNonNullValue(detail.path("DEATH_DATE"))); - listResult.put("COMMUNITY_NAME", getNonNullValue(detail.path("COMMUNITY_NAME"))); - listResult.put("GROUP_TYPE", getNonNullValue(detail.path("GROUP_TYPE"))); - listResult.put("ID_DEPT", getNonNullValue(detail.path("ID_DEPT"))); - listResult.put("EMPLOYEE_CODE", getNonNullValue(detail.path("EMPLOYEE_CODE"))); - listResult.put("FUNCTIONARY", getNonNullValue(detail.path("FUNCTIONARY"))); - listResult.put("IS_HANDICAPPED", getNonNullValue(detail.path("IS_HANDICAPPED"))); - listResult.put("GENDER", getNonNullValue(detail.path("GENDER"))); - listResult.put("DATE_OF_BIRTH", getNonNullValue(detail.path("DATE_OF_BIRTH"))); - listResult.put("DATE_OF_APPOINTMENT", getNonNullValue(detail.path("DATE_OF_APPOINTMENT"))); - listResult.put("DESIGNATION", getNonNullValue(detail.path("DESIGNATION"))); - listResult.put("EMPLOYEE_NAME", getNonNullValue(detail.path("EMPLOYEE_NAME"))); - listResult.put("DEPARTMENT", getNonNullValue(detail.path("DEPARTMENT"))); - list.add(listResult); - } - // Sort the list by RETIREMENT_DATE in ascending order - list.sort(Comparator.comparing(map -> parseDate(((Map) map).get("RETIREMENT_DATE")))); - response.put("list", list); - System.out.println("listresult: "+list); - - } else { - response.put("list", Collections.emptyList()); - } - } else { - System.err.println("Invalid JSON Response: " + rawResponse); - response.put("list", Collections.emptyList()); - } - - } catch (Exception e) { - e.printStackTrace(); - response.put("list", Collections.emptyList()); - } - return response; - } - - - // Utility method to convert DD-MM-YYYY to YYYY-MM-DD - private String formatToISODate(String date) { - if (date == null || date.isEmpty()) { - return ""; - } - try { - SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MM-yyyy"); - SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date parsedDate = inputFormat.parse(date); - return outputFormat.format(parsedDate); - } catch (ParseException e) { - System.err.println("Date parsing error: " + e.getMessage()); - return date; // Return original date if parsing fails - } - } - - - //getting deptId from login - public Integer getloginuserDeptId(int userId) { - String query = "select emp_dept_id from login_details where gcc_login_id = ?"; - try { - // Use queryForObject to return a single value - return jdbcTemplate.queryForObject(query, Integer.class, userId); - } catch (EmptyResultDataAccessException e) { - // Log the issue and handle the case when no result is found - System.out.println("No department found for user ID: " + userId); - return null; // Or return a default value if required - } - } - - - private LocalDate parseDate(String date) { - if (date == null || date.isEmpty()) { - return LocalDate.MIN; // Use a minimum value for invalid or empty dates - } - try { - // Remove time part if present - if (date.contains(" ")) { - date = date.split(" ")[0]; // Extract only the date part before space - } - - DateTimeFormatter formatter; - if (date.matches("\\d{4}-\\d{2}-\\d{2}")) { // yyyy-MM-dd - formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - } else if (date.matches("\\d{2}-\\d{2}-\\d{4}")) { // dd-MM-yyyy - formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - } else { - System.err.println("Unknown date format: " + date); - return LocalDate.MIN; - } - return LocalDate.parse(date, formatter); - } catch (DateTimeParseException e) { - e.printStackTrace(); - return LocalDate.MIN; // Fallback for invalid dates - } - } - - -// private LocalDate parseDate(String date) { -// if (date == null || date.isEmpty()) { -// return LocalDate.MIN; // Use a minimum value for invalid or empty dates -// } -// try { -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); // Adjust format as needed -// return LocalDate.parse(date, formatter); -// } catch (DateTimeParseException e) { -// e.printStackTrace(); -// return LocalDate.MIN; // Fallback for invalid dates -// } -// } - - - private boolean isValidJson(String json) { - try { - objectMapper.readTree(json); - return true; - } catch (Exception e) { - return false; - } - } - - - private String getNonNullValue(JsonNode node) { - //String value = node.isMissingNode() || node.isNull() || node.asText().isEmpty() ? "N/A" : node.asText(); - String value = node.isMissingNode() || node.isNull() || node.asText().isEmpty() || node.asText().isBlank() ? "N/A" : node.asText(); - //2024-565EAT - return "null".equals(value) ? "N/A" : value; // Check for string "null" - } - - public String getDeptNameById(Integer deptId) { - String query = "SELECT dept_name FROM department_master WHERE dept_id=? AND isactive=1 AND isdelete=0"; - - try { - // Query execution and returning the department name - //return jdbcTemplate.queryForObject(query, new Object[]{deptId}, String.class); - - return jdbcTemplate.queryForObject(query, String.class,deptId); - } catch (Exception e) { - // Handle exception if deptId is not found or query fails - e.printStackTrace(); - return null; - } - } - - - - @Transactional - public boolean saveRetirementEmployeeDetails(Map requestData) { - try { - - String empNo = (String) requestData.get("empNo"); - String empName = (String) requestData.get("empName"); - String deptName = (String) requestData.get("deptName"); - String designation = (String) requestData.get("designation"); - String typeOfRetirement = (String) requestData.get("typeOfRetirement"); - String retirementdate = (String) requestData.get("retirementdate"); - String retirementclass = (String) requestData.get("retirementclass"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - String file_category = (String) requestData.get("filecategory"); - - // Safely parse integer values - int deptId; - int filecategory; - try { - deptId = Integer.parseInt(dept_Id); - filecategory = Integer.parseInt(file_category); - } catch (NumberFormatException e) { - System.out.println("Invalid number format for deptId or filecategory."); - return false; - } - - int filestatus = getFileStatus.getFileStatus1Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - // Execute a query to fetch the required String based on filecategory - String additionalDataQuery = "SELECT file_name FROM file_category_master WHERE id = ?"; - String fc_name = jdbcTemplate.queryForObject(additionalDataQuery,String.class,filecategory); - System.out.println("fc_name==="+fc_name); - - - String fileentrytype ="NEW"; - - System.out.println("filemovedby====="+filemovedby); - - // Generate the variable (PR + current date + current time) - String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyHHmmss")); - String temp_id = "PR" + currentTimestamp; - - String query = "INSERT INTO pensioner_details (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,retirement_class,file_moved_date, remarks,file_category,file_status,file_entry_type,dept_id,file_category_name,temp_id) VALUES (?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?)"; - int rowsInserted = jdbcTemplate.update(query, empNo, empName, deptName, designation, typeOfRetirement,retirementdate ,retirementclass,dateToAudit, remarks,filecategory,filestatus,fileentrytype,deptId,fc_name,temp_id); - - String query1 = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,retirement_class,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?)"; - int rowsInsertedHistory = jdbcTemplate.update(query1, empNo, empName, deptName, designation, typeOfRetirement,retirementdate ,retirementclass,dateToAudit, remarks,filecategory,filestatus,fileentrytype,filemovedby,deptId,fc_name,temp_id); - - String query2 = "INSERT INTO file_movement_history (emp_no,file_moved_date,file_status,file_moved_by,remarks,temp_id) VALUES (?, ?, ?, ?, ?,?)"; - int rowsInsertedFileMovement = jdbcTemplate.update(query2, empNo,dateToAudit,filestatus,filemovedby,remarks,temp_id); - - - return rowsInserted > 0 && rowsInsertedHistory > 0 && rowsInsertedFileMovement > 0; - - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false if an exception occurs - } - } - - -// public List getRegisteredEmps(Integer deptId) { -// String query = "SELECT DISTINCT emp_no FROM pensioner_details WHERE dept_id=? AND file_category <> 5 " + -// "UNION ALL " + -// "SELECT DISTINCT emp_no FROM cps_pensioner_details WHERE dept_id=?"; -// -// List emps = jdbcTemplate.queryForList(query, String.class, deptId, deptId); -// System.out.println("emps====" + emps); -// -// return emps; -// } - - - public List getRegisteredEmps(Integer deptId) { - String query = "SELECT DISTINCT emp_no FROM pensioner_details " + - "WHERE dept_id=? AND (file_category <> 5 OR (file_category = 5 AND file_status != 11)) " + - "UNION ALL " + - "SELECT DISTINCT emp_no FROM cps_pensioner_details WHERE dept_id=?"; - - List emps = jdbcTemplate.queryForList(query, String.class, deptId, deptId); - System.out.println("emps====" + emps); - - return emps; - } - - - public Integer getRetirementFileCategoryId() { - String query = "SELECT id FROM file_category_master WHERE file_name = 'Retirement'"; - try { - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - } - - public Integer getFamilyPensionFileCategoryId() { - String query = "SELECT id FROM file_category_master WHERE file_name = 'Family Pension'"; - try { - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - } - - public Integer getPendencyFileCategoryId() { - String query = "SELECT id FROM file_category_master WHERE file_name = 'Pendency'"; - try { - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - } - - public Integer getGISFileCategoryId() { - String query = "SELECT id FROM file_category_master WHERE file_name = 'GIS'"; - try { - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - } - - public Integer getPRFileCategoryId() { - String query = "SELECT id FROM file_category_master WHERE file_name = 'Provisional Pension'"; - try { - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - } - - public Integer getCPSFileCategoryId() { - String query = "SELECT id FROM file_category_master WHERE file_name = 'Contributory Pension Scheme'"; - try { - return jdbcTemplate.queryForObject(query, Integer.class); - } catch (EmptyResultDataAccessException e) { - return null; // or handle as needed - } - } - - - @Transactional - public boolean saveFamilyPensionDetails(Map requestData) { - try { - - // Extract data from the request body - String empNo = (String) requestData.get("empNo"); - String empName = (String) requestData.get("empName"); - String deptName = (String) requestData.get("deptName"); - String designation = (String) requestData.get("designation"); - String sanctionedgis = (String) requestData.get("sanctionedgis"); - String serviceDeath =(String) requestData.get("serviceDeath"); - String deceased =(String) requestData.get("deceased"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String remarks = (String) requestData.get("remarks"); - String filemovedby =(String)requestData.get("filemovedby"); - - String pendingDuration = (String) requestData.get("pendingDuration"); - String reasonPending = (("yes".equals(pendingDuration) || "no".equals(pendingDuration)) - && requestData.get("reasonPending") != null) ? requestData.get("reasonPending").toString() : null; - - String dept_Id = (String) requestData.get("deptId"); - int deptId = Integer.parseInt(dept_Id); - - String file_category = (String) requestData.get("filecategory"); - int filecategory = Integer.parseInt(file_category); - - // Execute a query to fetch the required String based on filecategory - String additionalDataQuery = "SELECT file_name FROM file_category_master WHERE id = ?"; - String fc_name = jdbcTemplate.queryForObject(additionalDataQuery, String.class,filecategory); - System.out.println("fc_name==="+fc_name); - - - int filestatus = getFileStatus.getFileStatus1Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String fileentrytype ="NEW"; - int rowsInserted=0; - - // Generate the variable (PR + current date + current time) - String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyHHmmss")); - String temp_id = "PF" + currentTimestamp; - - String query = "INSERT INTO pensioner_details (emp_no, emp_name, dept_name, designation, sanctioned_gis_amount,service_death,relationship_deceased,file_moved_date, remarks,dept_id,file_category,file_status,file_entry_type,file_category_name,temp_id,pending_duration,reason_for_pending) VALUES (?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - rowsInserted = jdbcTemplate.update(query, empNo, empName, deptName, designation, sanctionedgis,serviceDeath ,deceased,dateToAudit, remarks,deptId,filecategory,filestatus,fileentrytype,fc_name,temp_id, pendingDuration,reasonPending); - - String query1 = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, sanctioned_gis_amount,service_death,relationship_deceased,file_moved_date, remarks,dept_id,file_category,file_status,file_entry_type,file_moved_by,file_category_name,temp_id,pending_duration,reason_for_pending) VALUES (?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?)"; - rowsInserted = jdbcTemplate.update(query1, empNo, empName, deptName, designation, sanctionedgis,serviceDeath ,deceased,dateToAudit, remarks,deptId,filecategory,filestatus,fileentrytype,filemovedby,fc_name,temp_id, pendingDuration,reasonPending); - - String query2 = "INSERT INTO file_movement_history (emp_no,file_moved_date,file_status,file_moved_by,remarks,temp_id) VALUES (?, ?, ?, ?, ?,?)"; - rowsInserted = jdbcTemplate.update(query2, empNo,dateToAudit,filestatus,filemovedby,remarks,temp_id); - - - return rowsInserted > 0; - - - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false if an exception occurs - } - } - - - ///gis saving method service - @Transactional - public boolean savenewEntryDetailsGis(Map requestData) { - try { - - - String empNo = (String) requestData.get("empNo"); - String empName = (String) requestData.get("empName"); - String deptName = (String) requestData.get("deptName"); - String designation = (String) requestData.get("designation"); - String dateToPension = (String) requestData.get("dateToPension"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String serviceDeath =(String) requestData.get("serviceDeath"); - String deceased =(String) requestData.get("deceased"); - String gisentry = requestData.get("gisentry") != null ?(String) requestData.get("gisentry") : null; - String gisAdvanceamount =requestData.get("gisAdvanceamount") != null ?(String) requestData.get("gisAdvanceamount") : null; - String gisAdvance = requestData.get("gisAdvance") != null ? (String) requestData.get("gisAdvance") : null; - String dept_Id = (String) requestData.get("deptId"); - int deptId = Integer.parseInt(dept_Id); - - String file_category = (String) requestData.get("filecategory"); - int filecategory = Integer.parseInt(file_category); - // Execute a query to fetch the required String based on filecategory - String additionalDataQuery = "SELECT file_name FROM file_category_master WHERE id = ?"; - String fc_name = jdbcTemplate.queryForObject(additionalDataQuery, String.class,filecategory); - System.out.println("fc_name==="+fc_name); - - int filestatus = getFileStatus.getFileStatus7Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String fileentrytype ="NEW"; - - System.out.println("filemovedby====="+filemovedby); - - // Generate the variable (PR + current date + current time) - String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyHHmmss")); - String temp_id = "PG" + currentTimestamp; - - String query = "INSERT INTO pensioner_details (emp_no, emp_name, dept_name, designation,file_moved_date, remarks,service_death,relationship_deceased,gis_entry,gis_advance_amount,gis_advance ,file_category,file_status,file_entry_type,dept_id,file_category_name,temp_id) VALUES (?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - int rowsInserted = jdbcTemplate.update(query, empNo, empName, deptName, designation, dateToPension, remarks,serviceDeath,deceased,gisentry,gisAdvanceamount,gisAdvance,filecategory,filestatus,fileentrytype,deptId,fc_name,temp_id); - - String query1 = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,file_moved_date, remarks,service_death,relationship_deceased,gis_entry,gis_advance_amount,gis_advance ,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?)"; - int rowsInsertedHistory = jdbcTemplate.update(query1, empNo, empName, deptName, designation,dateToPension, remarks,serviceDeath,deceased,gisentry,gisAdvanceamount,gisAdvance,filecategory,filestatus,fileentrytype,filemovedby,deptId,fc_name,temp_id); - - String query2 = "INSERT INTO file_movement_history (emp_no,file_moved_date,file_status,file_moved_by,remarks,temp_id) VALUES (?, ?, ?, ?, ?,?)"; - int rowsInsertedFileMovement = jdbcTemplate.update(query2, empNo,dateToPension,filestatus,filemovedby,remarks,temp_id); -// - - return rowsInserted > 0 && rowsInsertedHistory > 0 && rowsInsertedFileMovement > 0; - - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false if an exception occurs - } - } - - - - //provisional retirement method service - @Transactional - public boolean savenewEntryDetailsProvisionalretirement(Map requestData) { - try { - - String empNo = (String) requestData.get("empNo"); - String empName = (String) requestData.get("empName"); - String deptName = (String) requestData.get("deptName"); - String designation = (String) requestData.get("designation"); - String typeOfRetirement = (String) requestData.get("typeOfRetirement"); - - String ReasonofPension = (String) requestData.get("ReasonofPension"); - String retirementClass = (String) requestData.get("retirementClass"); - String retirementDate = (String) requestData.get("retirementDate"); - String pendingDuration = (String) requestData.get("pendingDuration"); - String reasonofPending = (String) requestData.get("reasonofPending"); - String dp = (String) requestData.get("dp"); - String otherReason = (String) requestData.get("otherReason"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - int deptId = Integer.parseInt(dept_Id); - - String file_category = (String) requestData.get("filecategory"); - int filecategory = Integer.parseInt(file_category); - // Execute a query to fetch the required String based on filecategory - String additionalDataQuery = "SELECT file_name FROM file_category_master WHERE id = ?"; - String fc_name = jdbcTemplate.queryForObject(additionalDataQuery, String.class,filecategory); - System.out.println("fc_name==="+fc_name); - - int filestatus = getFileStatus.getFileStatus7Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String fileentrytype ="NEW"; - - System.out.println("filemovedby====="+filemovedby); - - // Generate the variable (PR + current date + current time) - String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyHHmmss")); - String temp_id = "PPR" + currentTimestamp; - - String query = "INSERT INTO pensioner_details (emp_no, emp_name, dept_name, designation,type_of_retirement,retirement_class,retirement_date , reason_for_provisional_pension,file_moved_date, pending_duration,reason_for_pending,dp,remarks,file_category,file_status,file_entry_type,dept_id,file_category_name,others_provisional_pension,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,?)"; - int rowsInserted = jdbcTemplate.update(query, empNo, empName, deptName, designation, typeOfRetirement,retirementClass ,retirementDate , ReasonofPension,dateToAudit,pendingDuration,reasonofPending,dp,remarks,filecategory,filestatus,fileentrytype,deptId,fc_name,otherReason,temp_id); - - String query1 = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement,retirement_class, retirement_date,reason_for_provisional_pension ,file_moved_date, remarks,pending_duration,reason_for_pending,dp ,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,others_provisional_pension,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?)"; - int rowsInsertedHistory = jdbcTemplate.update(query1, empNo, empName, deptName, designation,typeOfRetirement,retirementClass,retirementDate ,ReasonofPension,dateToAudit,remarks,pendingDuration,reasonofPending,dp,filecategory,filestatus,fileentrytype,filemovedby,deptId,fc_name,otherReason,temp_id); - - String query2 = "INSERT INTO file_movement_history (emp_no,file_moved_date,file_status,file_moved_by,remarks,temp_id) VALUES (?, ?, ?, ?, ?,?)"; - int rowsInsertedFileMovement = jdbcTemplate.update(query2, empNo,dateToAudit,filestatus,filemovedby,remarks,temp_id); -// - - return rowsInserted > 0 && rowsInsertedHistory > 0 && rowsInsertedFileMovement > 0; - - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false if an exception occurs - } - } - - //cps saving method: - @Transactional - public boolean savenewEntryDetailspensionscheme(Map requestData) { - try { - - // Safely extract input values from requestData - String empNo = requestData.get("empNo") != null ? requestData.get("empNo").toString() : null; - String empName = requestData.get("empName") != null ? requestData.get("empName").toString() : null; - String deptName = requestData.get("deptName") != null ? requestData.get("deptName").toString() : null; - String designation = requestData.get("designation") != null ? requestData.get("designation").toString() : null; - String classes = requestData.get("classes") != null ? requestData.get("classes").toString() : null; - String fileMovedBy = requestData.get("fileMovedBy") != null ? requestData.get("fileMovedBy").toString() : null; - String remarks = requestData.get("remarks") != null ? requestData.get("remarks").toString() : null; - String retirementType = requestData.get("retirementType") != null ? requestData.get("retirementType").toString() : null; - String retirementdate = requestData.get("retirementdate") !=null ? requestData.get("retirementdate").toString() : null; - - String uac = (String) requestData.get("uac"); - String uacDate = "yes".equals(uac) && requestData.get("uacDate") != null ? requestData.get("uacDate").toString() : null; - - String pendingDuration = (String) requestData.get("pendingDuration"); - String reasonPending = "Yes".equals(pendingDuration) && requestData.get("reasonPending") != null ? requestData.get("reasonPending").toString() : null; - - String cps =(String) requestData.get("cps"); - String cpsAmount = "yes".equals(cps) && requestData.get("cpsAmount") != null ? requestData.get("cpsAmount").toString() : null; - - String elOrLpa = (String)requestData.get("elOrLpa"); - String elOrLpaAmount = "yes".equals(elOrLpa) && requestData.get("elOrLpaAmount") != null ? requestData.get("elOrLpaAmount").toString() : null; - - String spfgs = (String) requestData.get("spfgs"); - String spfgsAmount = "yes".equals(spfgs) && requestData.get("spfgsAmount") != null ? requestData.get("spfgsAmount").toString() : null; - - int deptId = requestData.get("deptId") != null ? Integer.parseInt(requestData.get("deptId").toString()) : 0; - - // Default static values - String file_category = (String) requestData.get("filecategory"); - int filecategory = Integer.parseInt(file_category); - int fileStatus = getFileStatus.getFileStatus11Id(); - if (fileStatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String fileEntryType = "FILE_COMPLETED"; - - // Fetch file_category_name dynamically - String fileCategoryQuery = "SELECT file_name FROM file_category_master WHERE id = ?"; - String fileCategoryName = jdbcTemplate.queryForObject(fileCategoryQuery, String.class,filecategory); - - // Generate the variable (PR + current date + current time) - String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyHHmmss")); - String temp_id = "PC" + currentTimestamp; - - // Insert into cps_pensioner_details - String queryDetails = "INSERT INTO cps_pensioner_details " + - "(emp_no, emp_name, dept_name, designation, file_category, retirement_class, retirement_date,type_of_retirement, uac, uac_date, " + - "pending_duration,reason_for_pending ,cps, cps_amount, el_or_lpa, el_or_lpa_amount, spfgs, spfgs_amount, remarks, " + - "file_status, file_entry_type, dept_id, file_category_name,temp_id) " + - "VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - int rowsInsertedDetails = jdbcTemplate.update(queryDetails, - empNo, empName, deptName, designation, filecategory, classes, retirementdate,retirementType, uac, uacDate, - pendingDuration,reasonPending ,cps, cpsAmount, elOrLpa, elOrLpaAmount, spfgs, spfgsAmount, remarks, - fileStatus, fileEntryType, deptId, fileCategoryName,temp_id); - - // Insert into cps_pensioner_details_history - String queryHistory = "INSERT INTO cps_pensioner_details_history " + - "(emp_no, emp_name, dept_name, designation, file_category, retirement_class, retirement_date,type_of_retirement, uac, uac_date, " + - "pending_duration,reason_for_pending ,cps, cps_amount, el_or_lpa, el_or_lpa_amount, spfgs, spfgs_amount, remarks, " + - "file_status, file_entry_type, file_moved_by, dept_id, file_category_name,temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?)"; - int rowsInsertedHistory = jdbcTemplate.update(queryHistory, - empNo, empName, deptName, designation, filecategory, classes, retirementdate,retirementType, uac, uacDate, - pendingDuration, reasonPending,cps, cpsAmount, elOrLpa, elOrLpaAmount, spfgs, spfgsAmount, remarks, - fileStatus, fileEntryType, fileMovedBy, deptId, fileCategoryName,temp_id); - - // Current date and time - LocalDateTime fileMovedDate = LocalDateTime.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - String formattedFileMovedDate = fileMovedDate.format(formatter); - - // Insert into file_movement_history - String queryFileMovement = "INSERT INTO file_movement_history (emp_no, file_status,file_moved_date, file_moved_by, remarks,temp_id) " + - "VALUES (?, ?, ?, ?, ?,?)"; - int rowsInsertedFileMovement = jdbcTemplate.update(queryFileMovement, empNo, fileStatus, formattedFileMovedDate, fileMovedBy, remarks,temp_id); - - // Return true if all inserts were successful - return rowsInsertedDetails > 0 && rowsInsertedHistory > 0 && rowsInsertedFileMovement > 0; - - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false if an exception occurs - } - } - - - //pendency saving method - @Transactional - public boolean savePendencyDetails(Map requestData) { - try { - - String empNo = (String) requestData.get("empNo"); - String empName = (String) requestData.get("empName"); - String deptName = (String) requestData.get("deptName"); - String designation = (String) requestData.get("designation"); - String retirementclass = (String) requestData.get("retirementclass"); - String typeOfRetirement = (String) requestData.get("typeOfRetirement"); - String retirementDate = (String) requestData.get("retirementDate"); - //String pendencyCategory=(String)requestData.get("pendencyCategory"); - String pendencyCategory="Retirement"; - - String dateToAudit = (String) requestData.get("dateToAudit"); - String remarks = (String) requestData.get("remarks"); - String filemovedby =(String)requestData.get("filemovedby"); - - String pendingDuration = (String) requestData.get("pendingDuration"); - - String reasonPending =requestData.get("reasonPending") != null ? requestData.get("reasonPending").toString() : null; - - String dept_Id = (String) requestData.get("deptId"); - System.out.println("dept_Id = "+dept_Id); - int deptId = Integer.parseInt(dept_Id); - - String file_category = (String) requestData.get("filecategory"); - int filecategory = Integer.parseInt(file_category); - int filestatus = getFileStatus.getFileStatus1Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String fileentrytype ="NEW"; - int rowsInserted = 0; - - // Generate the variable (PR + current date + current time) - String currentTimestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyHHmmss")); - String temp_id = "PP" + currentTimestamp; - - - String query = "INSERT INTO pensioner_details (emp_no, emp_name, dept_name, designation, retirement_class,retirement_date,pending_duration,reason_for_pending,file_moved_date,dept_id,remarks,file_category,file_status,file_entry_type,file_category_name,type_of_retirement,temp_id) VALUES (?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - rowsInserted = jdbcTemplate.update(query, empNo, empName, deptName, designation, retirementclass,retirementDate,pendingDuration,reasonPending,dateToAudit, deptId,remarks,filecategory,filestatus,fileentrytype,pendencyCategory,typeOfRetirement,temp_id); - - String query1 = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, retirement_class,retirement_date,pending_duration,reason_for_pending,file_moved_date,dept_id,remarks,file_category,file_status,file_entry_type,file_category_name,type_of_retirement,file_moved_by,temp_id) VALUES (?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?)"; - rowsInserted = jdbcTemplate.update(query1, empNo, empName, deptName, designation, retirementclass,retirementDate,pendingDuration,reasonPending,dateToAudit, deptId,remarks,filecategory,filestatus,fileentrytype,pendencyCategory,typeOfRetirement,filemovedby,temp_id); - - String query2 = "INSERT INTO file_movement_history (emp_no,file_moved_date,file_status,file_moved_by,remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - rowsInserted = jdbcTemplate.update(query2, empNo,dateToAudit,filestatus,filemovedby,remarks,temp_id); - - - return rowsInserted > 0; - - - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false if an exception occurs - } - } - - public boolean doesEmployeeExistRPR(String empCode) { - String sql = "SELECT COUNT(*) FROM ( " + - " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1,2,3,4,5) " + - " UNION ALL " + - " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + - ") AS combined"; - // Note: Pass empCode twice since there are two placeholders. - Integer count = jdbcTemplate.queryForObject(sql, Integer.class,empCode,empCode); - return count != null && count > 0; - } - - -// public boolean doesEmployeeExist(String empCode) { -// -// String sql = "SELECT COUNT(*) FROM ( " + -// " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1,3,5) "+ -// " UNION ALL " + -// " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + -// ") AS combined"; -// // Note: Pass empCode twice since there are two placeholders. -// Integer count = jdbcTemplate.queryForObject(sql,Integer.class,empCode,empCode); -// System.out.println("count<<<<<<<<<<<"+count); -// return count != null && count > 0; -// } -// -// -// public boolean doesEmployeeExistgis(String empCode) { -// String sql = "SELECT COUNT(*) FROM ( " + -// " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1,2,3,5,6) " + -// " UNION ALL " + -// " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + -// ") AS combined"; -// // Note: Pass empCode twice since there are two placeholders. -// Integer count = jdbcTemplate.queryForObject(sql, Integer.class,empCode,empCode); -// return count != null && count > 0; -// } -// -// -// public boolean doesEmployeeExistfp(String empCode) { -// -// String sql = "SELECT COUNT(*) FROM ( " + -// -// " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1,2,3,5) AND is_closed IN (0)" + -// " UNION ALL " + -// -// " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + -// ") AS combined"; -// -// // Note: Pass empCode twice since there are two placeholders. -// Integer count = jdbcTemplate.queryForObject(sql, Integer.class,empCode,empCode); -// return count != null && count > 0; -// } - - - public boolean doesEmployeeExist(String empCode) { - - String sql = "SELECT COUNT(*) FROM ( " + - " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (3,4,5) "+ - " UNION ALL " + - " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1) AND is_closed=0 "+ - " UNION ALL " + - " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + - ") AS combined"; - // Note: Pass empCode twice since there are two placeholders. - Integer count = jdbcTemplate.queryForObject(sql,Integer.class,empCode,empCode,empCode); - System.out.println("count<<<<<<<<<<<"+count); - return count != null && count > 0; - } - - - public boolean doesEmployeeExistgis(String empCode) { - String sql = "SELECT COUNT(*) FROM ( " + - " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1,2,3,5) " + - " UNION ALL " + - " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + - ") AS combined"; - // Note: Pass empCode twice since there are two placeholders. - Integer count = jdbcTemplate.queryForObject(sql, Integer.class,empCode,empCode); - return count != null && count > 0; - } - - - public boolean doesEmployeeExistfp(String empCode) { - - String sql = "SELECT COUNT(*) FROM ( " + - - " SELECT emp_no FROM pensioner_details WHERE emp_no = ? AND file_category IN (1,2,3,5) AND is_closed IN (0)" + - " UNION ALL " + - - " SELECT emp_no FROM cps_pensioner_details WHERE emp_no = ? AND file_category IN (6) " + - ") AS combined"; - - // Note: Pass empCode twice since there are two placeholders. - Integer count = jdbcTemplate.queryForObject(sql, Integer.class,empCode,empCode); - return count != null && count > 0; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PendencyAutoConversionService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PendencyAutoConversionService.java deleted file mode 100644 index 04900d05..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PendencyAutoConversionService.java +++ /dev/null @@ -1,280 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.time.LocalDate; -import java.time.Period; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -@Transactional -public class PendencyAutoConversionService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private AppConfig appConfig; - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - /** - * Main method to process auto-conversion logic. - * - Fetch records where retirement date has crossed. - * - Update pensioner details. - * - Fetch employee details. - * - Save data into pensioner_details_history and file_movement_history. - */ - @Transactional - public boolean processAutoConversion() { - try { - // Step 1: Fetch temp IDs that need processing - List> tempList = getConvertingTempIds(); - if (tempList.isEmpty()) { - System.out.println("No records found for auto-conversion."); - return false; - } - - for (Map tempIdMap : tempList) { - String tempId = tempIdMap.get("temp_id") != null ? String.valueOf(tempIdMap.get("temp_id")) : null; - if (tempId == null || tempId.trim().isEmpty()) { - System.out.println("Skipping null/empty temp_id."); - continue; - } - - System.out.println("Processing tempId: " + tempId); - - // Step 2: Get file_moved_by value - String fileMovedBy = getFileMovedByTempId(tempId); - if (fileMovedBy == null) { - System.out.println("Skipping tempId " + tempId + " as fileMovedBy is NULL."); - continue; - } - - // Step 3: Update pensioner_details table - boolean updated = updateEntryDetails(tempId); - if (!updated) { - System.out.println("Failed to update pensioner_details for tempId: " + tempId); - continue; - } - - // Step 4: Fetch employee details - List> empDetails = fetchEmployeeDetails(tempId); - if (empDetails.isEmpty()) { - System.out.println("No employee details found for tempId: " + tempId); - continue; - } - - // Step 5: Save history data - boolean historySaved = saveHistory(empDetails, fileMovedBy); - if (!historySaved) { - System.out.println("Failed to save history for tempId: " + tempId); - } - } - - System.out.println("Auto-conversion process completed."); - return true; - } catch (Exception e) { - System.err.println("Exception in processAutoConversion: " + e.getMessage()); - e.printStackTrace(); - return false; - } - } - - public List> getConvertingTempIds() { - String sql = "SELECT temp_id FROM pensioner_details WHERE file_category=1 AND file_status <=8 AND retirement_date <= CURDATE() - 1"; - return jdbcTemplate.queryForList(sql); - } - - private boolean updateEntryDetails(String tempId) { - try { - LocalDate datefield = LocalDate.now(); - String formattedDate = datefield.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); - String remarks = "Auto_Conversion"; - int fileCategory = 3; - String pendingDuration = "yes"; - String reasonForPending = "Retirement Date Crossed while file in Processing"; - - String updateQuery = "UPDATE pensioner_details SET reason_for_pending=?, pending_duration=?, file_category=?, file_moved_date=?, remarks=?, updated_date=CURRENT_TIMESTAMP WHERE temp_id=?"; - int rowsUpdated = jdbcTemplate.update(updateQuery, reasonForPending, pendingDuration, fileCategory, formattedDate, remarks, tempId); - - System.out.println("Updated pensioner_details for tempId: " + tempId + " - Rows affected: " + rowsUpdated); - return rowsUpdated > 0; - } catch (Exception e) { - System.err.println("Exception in updateEntryDetails: " + e.getMessage()); - return false; - } - } - - public List> fetchEmployeeDetails(String tempId) { - String sql = "SELECT * FROM pensioner_details WHERE temp_id=?"; - return jdbcTemplate.queryForList(sql, tempId); - } - - - @Transactional - public boolean saveHistory(List> empDetails, String fileMovedBy) { - try { - String empInsertQuery = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id, pending_duration, reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy != null ? fileMovedBy : ""); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration") != null ? emp.get("pending_duration").toString() : null); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks, temp_id) VALUES (?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(historyQuery, empDetails, empDetails.size(), (ps, his) -> { - ps.setString(1, his.get("emp_no").toString()); - ps.setString(2, his.get("file_moved_date").toString()); - ps.setString(3, his.get("file_status").toString()); - ps.setString(4, fileMovedBy != null ? fileMovedBy : ""); - ps.setString(5, his.get("remarks").toString()); - ps.setString(6, his.get("temp_id").toString()); - }); - - System.out.println("Successfully saved history for " + empDetails.size() + " records."); - return true; - } catch (Exception e) { - System.err.println("Exception in saveHistory: " + e.getMessage()); - return false; - } - } - - public String getFileMovedByTempId(String tempId) { - String sql = "SELECT file_moved_by FROM pensioner_details_history WHERE temp_id=? ORDER BY created_date DESC LIMIT 1"; - return jdbcTemplate.queryForObject(sql, String.class, tempId); - } - - - public boolean processAutoConversionForTempId(String tempId) { - try { - System.out.println("Running auto-conversion for tempId: " + tempId); - - // Step 1: Get fileMovedBy - String fileMovedBy = getFileMovedByTempId(tempId); - if (fileMovedBy == null) { - System.out.println("Skipping tempId " + tempId + " as fileMovedBy is NULL."); - return false; - } - - // Step 2: Update pensioner details - boolean updated = updateEntryDetails(tempId); - if (!updated) { - System.out.println("Failed to update pensioner_details for tempId: " + tempId); - return false; - } - - // Step 3: Fetch employee details - List> empDetails = fetchEmployeeDetails(tempId); - if (empDetails.isEmpty()) { - System.out.println("No employee details found for tempId: " + tempId); - return false; - } - - // Step 4: Save history - boolean historySaved = saveHistory(empDetails, fileMovedBy); - if (!historySaved) { - System.out.println("Failed to save history for tempId: " + tempId); - return false; - } - - System.out.println("Successfully processed tempId: " + tempId); - return true; - } catch (Exception e) { - System.err.println("Error processing tempId: " + tempId + " - " + e.getMessage()); - e.printStackTrace(); - return false; - } - } - - public List> getPendencyUpdatingDuration(){ - - String sqlQuery = "SELECT * FROM pensioner_details WHERE file_category IN (2,3,5) AND (pending_duration = 'yes' OR pending_duration = 'Yes') AND file_status < 11"; - List> details = jdbcTemplate.queryForList(sqlQuery); - - return details; - - } - - public List> getProvisionalNoPendingDuration(){ - - String sqlQuery = "SELECT * FROM pensioner_details WHERE file_category IN (5) AND (pending_duration = 'no' OR pending_duration = 'No') AND file_status < 11 AND retirement_date < curdate()"; - List> prdetails = jdbcTemplate.queryForList(sqlQuery); - - return prdetails; - - } - - public String calculatePendingDuration(LocalDate startDate, LocalDate endDate) { - Period period = Period.between(startDate, endDate); - - int years = period.getYears(); - int months = period.getMonths(); - int days = period.getDays(); - - if (years == 0 && months == 0 && days == 0) { - return "0 days"; // or "Same day" - } - - return (years > 0 ? years + " year " : "") + - (months > 0 ? months + " month " : "") + - (days > 0 ? days + " day" : ""); - } - - public boolean updatePendingDuration(String updateDuration, String tempId) { - String sqlQuery = "UPDATE pensioner_details SET reason_for_pending=? WHERE temp_id=?"; - int rowsUpdated = jdbcTemplate.update(sqlQuery, updateDuration, tempId); - System.out.println("Temp ID: " + tempId + " | Rows Updated: " + rowsUpdated); - return rowsUpdated > 0; - } - - public boolean updatePendingDurationforPR(String updateDuration1, String tempId1) { - String sqlQuery = "UPDATE pensioner_details SET pending_duration='Yes',reason_for_pending=? WHERE temp_id=?"; - int rowsUpdated = jdbcTemplate.update(sqlQuery, updateDuration1, tempId1); - System.out.println("Updating for PR No Temp ID: " + tempId1 + " | Rows Updated: " + rowsUpdated); - return rowsUpdated > 0; - } - - // New method to get the count of pending pensioners - public int getPendingPensionersCount() { - String sqlQuery = "SELECT COUNT(*) FROM pensioner_details WHERE file_category=3 AND pending_duration='yes' AND file_status < 11"; - Integer count = jdbcTemplate.queryForObject(sqlQuery, Integer.class); - return count != null ? count : 0; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionAuditService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionAuditService.java deleted file mode 100644 index 3dee2eb6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionAuditService.java +++ /dev/null @@ -1,235 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -@Transactional -public class PensionAuditService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public PensionAuditService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchDetailsForAudit(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND (file_status=1 OR file_status=3) AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,file_cat); - } - - public boolean updateEntryDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus4Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - String file_entry_type="AUDIT_CLEARED"; - - String updateQuery = "UPDATE pensioner_details SET file_status = ?,file_entry_type=?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,file_entry_type,dateToAudit, remarks,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - public boolean savehistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String retirement_date = emp.get("retirement_date").toString(); - String retirement_class = emp.get("retirement_class").toString(); - String type_of_retirement = emp.get("type_of_retirement").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,retirement_class,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,type_of_retirement,retirement_date,retirement_class,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - //gis - public List> fetchDetailsForrecivedGis(Integer file_cat) { - String query = "SELECT * FROM pensioner_details WHERE file_category = ? AND file_status = 7"; - - - return jdbcTemplate.queryForList(query,file_cat); - } - - - - - - public boolean saveFamilyPensionHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - String serviceDeath = emp.get("service_death").toString(); - String relationshipDeceased = emp.get("relationship_deceased").toString(); - String sanctionedGis = emp.get("sanctioned_gis_amount").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death,relationship_deceased ,sanctioned_gis_amount,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,serviceDeath,relationshipDeceased,sanctionedGis,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - - - public boolean savePendencyHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String retirementClass = emp.get("retirement_class").toString(); - String retirementDate=emp.get("retirement_date").toString(); - - //String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - - String typeOfCategory=emp.get("file_category_name").toString(); - String typeOfRetirement=emp.get("type_of_retirement").toString(); - - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,retirement_class,retirement_date,file_category_name,type_of_retirement,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,retirementClass,retirementDate, typeOfCategory,typeOfRetirement,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionPartiallyCompService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionPartiallyCompService.java deleted file mode 100644 index 2405aa24..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionPartiallyCompService.java +++ /dev/null @@ -1,335 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -@Transactional -public class PensionPartiallyCompService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public PensionPartiallyCompService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchPensionPartialEmpfiles(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_status=10 AND file_category=? AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,file_cat); - } - - public boolean updateEntryCompletedDetails(Map requestData) { - try { - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby = (String) requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - - String gpf = (String) requestData.get("gpf"); - String private_affairs = (String) requestData.get("private_affairs"); - String spfgs = (String) requestData.get("spfgs"); - String recovery_emp = requestData.get("recovery_emp") != null ? requestData.get("recovery_emp").toString() : null; - String dcrg = (String) requestData.get("dcrg"); - - String gpfAmount = requestData.get("gpfAmount") != null ? requestData.get("gpfAmount").toString() : null; - String private_affairs_amount = requestData.get("private_affairs_amount") != null ? requestData.get("private_affairs_amount").toString() : null; - String spfgs_amount = requestData.get("spfgs_amount") != null ? requestData.get("spfgs_amount").toString() : null; - - - String pension_number = (String) requestData.get("pension_number"); - String ledger_number = (String) requestData.get("ledger_number"); - String benefit_pension = (String) requestData.get("benefit_pension"); - String benefit_dcrg = (String) requestData.get("benefit_dcrg"); - String benefit_commutation = (String) requestData.get("benefit_commutation"); - - String benefit_pension_amount = requestData.get("benefit_pension_amount")!= null ? requestData.get("benefit_pension_amount").toString() : null; - String benefit_dcrg_amount = requestData.get("benefit_dcrg_amount") != null ? requestData.get("benefit_dcrg_amount").toString() : null; - String benefit_commutation_amount = requestData.get("benefit_commutation_amount") != null ? requestData.get("benefit_commutation_amount").toString() : null; - - - int deptId = Integer.parseInt(dept_Id); - int filestatus; - String file_entry_type=""; - - - -// String updateQuery1 = "UPDATE zone_benefits SET gpf = ?, gpf_amount = ?, spfgs = ?, spfgs_amount = ?, dcrg = ?, private_affairs = ?, private_affairs_amount = ?, recovery_emp = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; -// int rowsUpdated3 = jdbcTemplate.update(updateQuery1, gpf, gpfAmount, spfgs, spfgs_amount, dcrg, private_affairs, private_affairs_amount, recovery_emp, tempId); -// System.out.println("Rows updated in zb: " + rowsUpdated3); - - - - String updateQuery2 = "UPDATE pension_benefits SET pension_number = ?, ledger_number = ?, benefit_pension = ?, benefit_pension_amount = ?, benefit_dcrg = ?, benefit_dcrg_amount = ?, benefit_commutation = ?, benefit_commutation_amount = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; - int rowsUpdated2 = jdbcTemplate.update(updateQuery2, pension_number, ledger_number, benefit_pension, benefit_pension_amount, benefit_dcrg, benefit_dcrg_amount, benefit_commutation, benefit_commutation_amount, tempId); - System.out.println("Rows updated in pb: " + rowsUpdated2); - - filestatus = CheckFieldsforPension(tempId) ? getFileStatus.getFileStatus11Id() : getFileStatus.getFileStatus10Id(); - System.out.println("filestatus inside service="+filestatus); - - if(filestatus==11) - { - file_entry_type="FILE_COMPLETED"; - } - if(filestatus==10) { - file_entry_type="PENSION_PARTIAL"; - } - - - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - if (rowsUpdated2 > 0) { - - String updateQuery = "UPDATE pensioner_details SET file_entry_type=?,file_status = ?, file_moved_date = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,file_entry_type, filestatus, dateToAudit, remarks, tempId); - System.out.println("Rows updated in fpd: " + rowsUpdated); - - if (rowsUpdated > 0) { - - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks, temp_id) VALUES (?, ?, ?, ?, ?, ?)"; - int rowsUpdated1 = jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks, tempId); - System.out.println("Rows updated in fmh: " + rowsUpdated1); - - return true; - } - } - - return false; - } catch (NumberFormatException e) { - System.err.println("Error parsing department ID: " + e.getMessage()); - return false; - } catch (DataAccessException e) { - System.err.println("Database operation failed: " + e.getMessage()); - return false; - } catch (Exception e) { - System.err.println("Unexpected error: " + e.getMessage()); - return false; - } - } - - - public boolean saveHistory(List> empDetails, List> zoneBenefits, List> pension_details, String fileMovedBy) { - try { - int file_Cat=0; - - if (!empDetails.isEmpty()) { - Map firstEmployeeDetails = empDetails.get(0); - Object fileCatObj = firstEmployeeDetails.get("file_category"); - - if (fileCatObj != null) { - try { - file_Cat = Integer.parseInt(fileCatObj.toString()); - System.out.println("Parsed file_category: " + file_Cat); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_category: " + fileCatObj); - } - } else { - System.out.println("file_category is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - // Batch update for employee details - if(file_Cat==1) { - String empInsertQuery = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - }); - } - - if(file_Cat==2) - { - String empInsertQuery1 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death, " + - "relationship_deceased, sanctioned_gis_amount, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery1, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("service_death").toString()); - ps.setString(6, emp.get("relationship_deceased").toString()); - ps.setString(7, emp.get("sanctioned_gis_amount").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration").toString()); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for family Pension"); - } - - if(file_Cat==3) - { - String empInsertQuery2 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement, " + - "file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending,retirement_class,retirement_date) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery2, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("file_moved_date").toString()); - ps.setString(7, emp.get("remarks").toString()); - ps.setInt(8, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(9, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(10, emp.get("file_entry_type").toString()); - ps.setString(11, fileMovedBy); - ps.setInt(12, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(13, emp.get("file_category_name").toString()); - ps.setString(14, emp.get("temp_id").toString()); - ps.setString(15, emp.get("pending_duration").toString()); - ps.setString(16, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - ps.setString(17, emp.get("retirement_class").toString()); - ps.setString(18, emp.get("retirement_date").toString()); - - }); - - System.out.println("rows inserted in pd history for pendency"); - } - - // Batch update for zone benefits -// String zoneInsertQuery = -// "INSERT INTO zone_benefits_history (emp_no, temp_id, gpf, gpf_amount, spfgs, spfgs_amount, dcrg, " + -// "private_affairs, private_affairs_amount, recovery_emp, file_moved_by) " + -// "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; -// -// jdbcTemplate.batchUpdate(zoneInsertQuery, zoneBenefits, zoneBenefits.size(), (ps, zone) -> { -// ps.setString(1, zone.get("emp_no").toString()); -// ps.setString(2, zone.get("temp_id").toString()); -// ps.setString(3, zone.get("gpf").toString()); -// ps.setString(4, zone.get("gpf_amount") != null ? zone.get("gpf_amount").toString() : null); -// ps.setString(5, zone.get("spfgs").toString()); -// ps.setString(6, zone.get("spfgs_amount") != null ? zone.get("spfgs_amount").toString() : null); -// ps.setString(7, zone.get("dcrg").toString()); -// ps.setString(8, zone.get("private_affairs").toString()); -// ps.setString(9, zone.get("private_affairs_amount") != null ? zone.get("private_affairs_amount").toString() : null); -// ps.setString(10, zone.get("recovery_emp") != null ? zone.get("recovery_emp").toString() : null); -// ps.setString(11, fileMovedBy); -// }); - - // Batch update for pension benefits - String pensionInsertQuery = - "INSERT INTO pension_benefits_history (emp_no,temp_id,file_pending,pension_number,ledger_number,benefit_pension,benefit_pension_amount,benefit_dcrg,benefit_dcrg_amount,benefit_commutation,benefit_commutation_amount,file_moved_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; - - jdbcTemplate.batchUpdate(pensionInsertQuery, pension_details, pension_details.size(), (ps, pension) -> { - ps.setString(1, pension.get("emp_no").toString()); - ps.setString(2, pension.get("temp_id").toString()); - ps.setString(3, pension.get("file_pending").toString()); - ps.setString(4, pension.get("pension_number").toString()); - ps.setString(5, pension.get("ledger_number").toString()); - ps.setString(6, pension.get("benefit_pension").toString()); - ps.setString(7, pension.get("benefit_pension_amount") != null ? pension.get("benefit_pension_amount").toString() : null); - ps.setString(8, pension.get("benefit_dcrg").toString()); - ps.setString(9, pension.get("benefit_dcrg_amount") != null ? pension.get("benefit_dcrg_amount").toString() : null); - ps.setString(10, pension.get("benefit_commutation").toString()); - ps.setString(11, pension.get("benefit_commutation_amount") != null ? pension.get("benefit_commutation_amount").toString() : null); - ps.setString(12, fileMovedBy); - - }); - - return true; // All insertions succeeded - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - private boolean CheckFieldsforPension(String tempId) { - - // Define the SQL query - String sql = "SELECT " + - "CASE " + - "WHEN pb.benefit_pension = 'yes' AND pb.benefit_dcrg = 'yes' " + - "THEN 1 ELSE 0 " + - "END AS allYes " + - "FROM pension_benefits AS pb " + - "WHERE pb.temp_id = ? "; - - - try { - // Use queryForObject to get a single boolean result - Boolean result = jdbcTemplate.queryForObject(sql, Boolean.class, tempId); - - return result != null && result; // Return the result if not null - } catch (Exception e) { - e.printStackTrace(); // Log the exception if needed - } - - return false; // Return false if an exception occurs - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionReceivedService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionReceivedService.java deleted file mode 100644 index 71ee4c74..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionReceivedService.java +++ /dev/null @@ -1,388 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -@Transactional -public class PensionReceivedService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public PensionReceivedService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchReceivedDepartmentEmpfiles(Integer deptId,Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE dept_id=? AND file_category=? AND (file_status=5 OR file_status=6) AND is_closed=0"; - - return jdbcTemplate.queryForList(query,deptId,file_cat); - } - - - public List> fetchZonebenefitsById(String tempId) { - String query = "SELECT * " + - "FROM zone_benefits " + - "WHERE temp_id=?"; - - - return jdbcTemplate.queryForList(query,tempId); - } - - public List> fetchPensionbenefitsById(String tempId) { - String query = "SELECT * " + - "FROM pension_benefits " + - "WHERE temp_id=?"; - - - return jdbcTemplate.queryForList(query,tempId); - } - - public boolean updateEntryDetails(Map requestData) { - try { - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - - String dateToAudit = (String) requestData.get("file_moved_date"); - String filemovedby = (String) requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - int deptId = (dept_Id != null && !dept_Id.isEmpty()) ? Integer.parseInt(dept_Id) : 0; - int filestatus = getFileStatus.getFileStatus7Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - String gpf = (String) requestData.get("gpf"); - String private_affairs = (String) requestData.get("private_affairs"); - String spfgs = (String) requestData.get("spfgs"); - String recovery_emp = (String) requestData.get("recovery_emp"); - String dcrg = (String) requestData.get("dcrg"); - - String gpfAmount = requestData.get("gpfAmount") != null ? requestData.get("gpfAmount").toString() : null; - String private_affairs_amount = requestData.get("private_affairs_amount") != null ? requestData.get("private_affairs_amount").toString() : null; - String spfgs_amount = requestData.get("spfgs_amount") != null ? requestData.get("spfgs_amount").toString() : null; - - boolean check = checkTempIdInZoneBenefits(tempId); - - // Update file_status in pensioner_details - String updateQuery = "UPDATE pensioner_details SET file_status = ?, file_moved_date = ?, remarks = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; - int rowsUpdated = jdbcTemplate.update(updateQuery, filestatus, dateToAudit, remarks, tempId); - System.out.println("Rows updated in pensioner_details: " + rowsUpdated); - - if (rowsUpdated > 0) { - // Insert into file movement history - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks, temp_id) VALUES (?, ?, ?, ?, ?, ?)"; - int rowsUpdated1 = jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks, tempId); - System.out.println("Rows inserted in file_movement_history: " + rowsUpdated1); - - if (rowsUpdated1 > 0) { - if (check) { - // Update zone benefits - String updateQuery1 = "UPDATE zone_benefits SET gpf = ?, gpf_amount = ?, spfgs = ?, spfgs_amount = ?, dcrg = ?, private_affairs = ?, private_affairs_amount = ?, recovery_emp = ?, updated_date = CURRENT_TIMESTAMP WHERE temp_id = ?"; - int rowsUpdated3 = jdbcTemplate.update(updateQuery1, gpf, gpfAmount, spfgs, spfgs_amount, dcrg, private_affairs, private_affairs_amount, recovery_emp, tempId); - System.out.println("Rows updated in zone_benefits: " + rowsUpdated3); - } else { - // Insert into zone benefits - String benefitQuery = "INSERT INTO zone_benefits (emp_no, temp_id, gpf, gpf_amount, spfgs, spfgs_amount, dcrg, private_affairs, private_affairs_amount, recovery_emp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - int rowsUpdated2 = jdbcTemplate.update(benefitQuery, empNo, tempId, gpf, gpfAmount, spfgs, spfgs_amount, dcrg, private_affairs, private_affairs_amount, recovery_emp); - System.out.println("Rows inserted in zone_benefits: " + rowsUpdated2); - } - return true; - } else { - System.out.println("Failed to insert into file_movement_history"); - return false; - } - } else { - System.out.println("Failed to update pensioner_details"); - return false; - } - } catch (Exception e) { - System.err.println("Exception in updateEntryDetails: " + e.getMessage()); - return false; - } - } - - - - public boolean saveHistory(List> empDetails, List> zoneBenefits, String fileMovedBy) { - try { - // Batch update for employee details - int file_Cat=0; - - if (!empDetails.isEmpty()) { - Map firstEmployeeDetails = empDetails.get(0); - Object fileCatObj = firstEmployeeDetails.get("file_category"); - - if (fileCatObj != null) { - try { - file_Cat = Integer.parseInt(fileCatObj.toString()); - System.out.println("Parsed file_category: " + file_Cat); - } catch (NumberFormatException e) { - System.err.println("Failed to parse file_category: " + fileCatObj); - } - } else { - System.out.println("file_category is null in emp_details."); - } - } else { - System.out.println("emp_details is empty."); - } - - - if(file_Cat==1) { - String empInsertQuery = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement, " + - "retirement_date, retirement_class, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(empInsertQuery, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("retirement_date").toString()); - ps.setString(7, emp.get("retirement_class").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - }); - - System.out.println("rows inserted in pd history for retirement"); - - } - - if(file_Cat==2) - { - String empInsertQuery1 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death, " + - "relationship_deceased, sanctioned_gis_amount, file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery1, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("service_death").toString()); - ps.setString(6, emp.get("relationship_deceased").toString()); - ps.setString(7, emp.get("sanctioned_gis_amount").toString()); - ps.setString(8, emp.get("file_moved_date").toString()); - ps.setString(9, emp.get("remarks").toString()); - ps.setInt(10, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(11, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(12, emp.get("file_entry_type").toString()); - ps.setString(13, fileMovedBy); - ps.setInt(14, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(15, emp.get("file_category_name").toString()); - ps.setString(16, emp.get("temp_id").toString()); - ps.setString(17, emp.get("pending_duration").toString()); - ps.setString(18, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - }); - - System.out.println("rows inserted in pd history for family Pension"); - } - - if(file_Cat==3) - { - String empInsertQuery2 = - "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,type_of_retirement, " + - "file_moved_date, remarks, file_category, file_status, " + - "file_entry_type, file_moved_by, dept_id, file_category_name, temp_id,pending_duration,reason_for_pending,retirement_class,retirement_date) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - - jdbcTemplate.batchUpdate(empInsertQuery2, empDetails, empDetails.size(), (ps, emp) -> { - ps.setString(1, emp.get("emp_no").toString()); - ps.setString(2, emp.get("emp_name").toString()); - ps.setString(3, emp.get("dept_name").toString()); - ps.setString(4, emp.get("designation").toString()); - ps.setString(5, emp.get("type_of_retirement").toString()); - ps.setString(6, emp.get("file_moved_date").toString()); - ps.setString(7, emp.get("remarks").toString()); - ps.setInt(8, Integer.parseInt(emp.get("file_category").toString())); - ps.setInt(9, Integer.parseInt(emp.get("file_status").toString())); - ps.setString(10, emp.get("file_entry_type").toString()); - ps.setString(11, fileMovedBy); - ps.setInt(12, Integer.parseInt(emp.get("dept_id").toString())); - ps.setString(13, emp.get("file_category_name").toString()); - ps.setString(14, emp.get("temp_id").toString()); - ps.setString(15, emp.get("pending_duration").toString()); - ps.setString(16, emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null); - ps.setString(17, emp.get("retirement_class").toString()); - ps.setString(18, emp.get("retirement_date").toString()); - }); - - System.out.println("rows inserted in pd history for pendency"); - } - - // Batch update for zone benefits - String zoneInsertQuery = - "INSERT INTO zone_benefits_history (emp_no, temp_id, gpf, gpf_amount, spfgs, spfgs_amount, dcrg, " + - "private_affairs, private_affairs_amount, recovery_emp, file_moved_by) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.batchUpdate(zoneInsertQuery, zoneBenefits, zoneBenefits.size(), (ps, zone) -> { - ps.setString(1, zone.get("emp_no").toString()); - ps.setString(2, zone.get("temp_id").toString()); - ps.setString(3, zone.get("gpf").toString()); - ps.setString(4, zone.get("gpf_amount") != null ? zone.get("gpf_amount").toString() : null); - ps.setString(5, zone.get("spfgs").toString()); - ps.setString(6, zone.get("spfgs_amount") != null ? zone.get("spfgs_amount").toString() : null); - ps.setString(7, zone.get("dcrg").toString()); - ps.setString(8, zone.get("private_affairs").toString()); - ps.setString(9, zone.get("private_affairs_amount") != null ? zone.get("private_affairs_amount").toString() : null); - ps.setString(10, zone.get("recovery_emp") != null ? zone.get("recovery_emp").toString() : null); - ps.setString(11, fileMovedBy); - }); - - System.out.println("rows inserted in zone history for family Pension"); - - return true; // All insertions succeeded - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - /* - */ - - -public boolean checkTempIdInZoneBenefits(String tempId) { - String query = "SELECT EXISTS (SELECT 1 FROM zone_benefits WHERE temp_id = ?)"; - - return Boolean.TRUE.equals(jdbcTemplate.queryForObject(query, Boolean.class, tempId)); - } - - - - //gis - - public boolean updateEntryGisDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - String sanctional_gis_date = (String) requestData.get("sanctional_gis_date"); - String sanctional_gis_amount = (String) requestData.get("sanctional_gis_amount"); - String lic_date = (String) requestData.get("lic_date"); - - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus11Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - String fileentrytype = "FILE_COMPLETED"; - - String updateQuery = "UPDATE pensioner_details SET file_status = ?, file_moved_date = ?, remarks = ?, sanctional_gis_date = ?, sanctional_gis_amount = ?, lic_date = ?,file_entry_type=? ,updated_date = CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery, filestatus, dateToAudit, remarks, sanctional_gis_date, sanctional_gis_amount, lic_date,fileentrytype ,tempId); - - //int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,dateToAudit, remarks,sanctional_gis_date,sanctional_gis_amount,lic_date,tempId); - System.out.println(dateToAudit); - System.out.println(sanctional_gis_date); - System.out.println(sanctional_gis_amount); - System.out.println(lic_date); - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - public boolean savehistoryGis(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String sanctional_gis_date=emp.get("sanctional_gis_date").toString(); - String sanctional_gis_amount=emp.get("sanctional_gis_amount").toString(); - String lic_date=emp.get("lic_date").toString(); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, file_moved_date, remarks, file_category, file_status, file_entry_type, file_moved_by, dept_id, file_category_name, temp_id, sanctional_gis_date, sanctional_gis_amount, lic_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id,sanctional_gis_date,sanctional_gis_amount,lic_date); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReceivedDeptProvisionalService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReceivedDeptProvisionalService.java deleted file mode 100644 index 9140ac45..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReceivedDeptProvisionalService.java +++ /dev/null @@ -1,241 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; - -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Service -@Transactional -public class ReceivedDeptProvisionalService { - - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - - public ReceivedDeptProvisionalService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - - - public List> fetchDetailsProvisionalPension(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND file_status=7"; - return jdbcTemplate.queryForList(query,file_cat); - } - - public List> fetchDetailsProvisionalDepartment(Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_category=? AND file_status=6"; - return jdbcTemplate.queryForList(query,file_cat); - } - - - - - //updated entry details - public boolean updateEntryDetailsCompleted(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - String pramount = (String) requestData.get("pramount"); - String prpercentage = (String) requestData.get("prpercentage"); - - - int deptId = Integer.parseInt(dept_Id); - int filestatus = 11; - String file_entry_type="FILE_COMPLETED"; - - // Update file_status in pensioner_details - String updateQuery = "UPDATE pensioner_details SET file_status = ?,file_moved_date=?,remarks=?,pr_amount=?,pr_percentage=?,file_entry_type=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,dateToAudit, remarks,pramount,prpercentage,file_entry_type,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - - - - // return to department - public boolean updateEntryDetailsReturntoDepartment(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); -// String pramount = (String) requestData.get("pramount"); -// String prpercentage = (String) requestData.get("prpercentage"); - - - int deptId = Integer.parseInt(dept_Id); - int filestatus = 6; - String file_entry_type="FILE_RETURNED"; - - // Update file_status in pensioner_details - String updateQuery = "UPDATE pensioner_details SET file_status = ?, file_entry_type =?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,file_entry_type,dateToAudit,remarks,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - - - - // sent to pension - public boolean updateEntryDetailsSenttoPension(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - String ReasonofPension = (String) requestData.get("ReasonofPension"); - String pendingDuration = (String) requestData.get("pendingDuration"); - String reasonofPending = (String) requestData.get("reasonofPending"); - String Dp = (String) requestData.get("Dp"); - String otherReason = (String) requestData.get("otherReason"); - -// String pramount = (String) requestData.get("pramount"); -// String prpercentage = (String) requestData.get("prpercentage"); - - - int deptId = Integer.parseInt(dept_Id); - int filestatus = 7; - String file_entry_type="FILE_RETURNED"; - - // Update file_status in pensioner_details - String updateQuery = "UPDATE pensioner_details SET file_status = ?, file_entry_type =?,file_moved_date=?,remarks=?,reason_for_provisional_pension=?,pending_duration=?,reason_for_pending=?,dp=?,others_provisional_pension=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,file_entry_type,dateToAudit,remarks,ReasonofPension,pendingDuration,reasonofPending,Dp,otherReason ,tempId); - - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - - - - - - - public boolean savehistory(List> emp_details, String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Safely extract individual fields from the map with default values - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String retirement_class = emp.get("retirement_class").toString(); - String type_of_retirement = emp.get("type_of_retirement").toString(); - String retirementDate = emp.get("retirement_date").toString(); - String ReasonofPension = emp.get("reason_for_provisional_pension").toString(); - String pendingDuration = emp.get("pending_duration").toString(); - String reasonofPending = emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - //String Dp = emp.get("dp").toString(); - String Dp = emp.get("dp") != null ? emp.get("dp").toString() : "hello"; - String otherReason = emp.get("others_provisional_pension") != null ? emp.get("others_provisional_pension").toString() : null; - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - String pramount = emp.get("pr_amount") != null && !emp.get("pr_amount").toString().trim().isEmpty() ? emp.get("pr_amount").toString() : null; - String prpercentage = emp.get("pr_percentage") != null && !emp.get("pr_percentage").toString().trim().isEmpty() ? emp.get("pr_percentage").toString() : null; - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); // Default to 0 - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); // Default to 0 - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); // Default to 0 - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery = "INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,reason_for_provisional_pension, pending_duration, dp, others_provisional_pension, reason_for_pending, retirement_class, file_moved_date, remarks, pr_amount, pr_percentage, file_category, file_status, file_entry_type, file_moved_by, dept_id, file_category_name, temp_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName, designation, type_of_retirement,retirementDate ,ReasonofPension, pendingDuration, Dp, otherReason, reasonofPending, retirement_class, fileMovedDate, remarks, pramount, prpercentage, file_category, fileStatus, fileEntryType, filemovedby, dept_id, fileCategoryName, temp_id); - System.out.println("Rows inserted in pdh: " + rowsInserted); - - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReportApiService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReportApiService.java deleted file mode 100644 index 51598d06..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReportApiService.java +++ /dev/null @@ -1,579 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -public class ReportApiService { - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public ReportApiService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> getFileCategories() { - String sql = "SELECT id,file_name FROM file_category_master"; - return jdbcTemplate.queryForList(sql); - } - -// String sql = "SELECT fm.file_name, " + -// "COALESCE(SUM(CASE WHEN pd.file_status IN (1,3) THEN 1 ELSE 0 END), 0) AS audit_pending, " + -// "COALESCE(SUM(CASE WHEN pd.file_status IN (2,5,6,9) THEN 1 ELSE 0 END), 0) AS department_pending, " + -// "COALESCE(SUM(CASE WHEN pd.file_status IN (4,7,8,10) THEN 1 ELSE 0 END), 0) AS pension_pending, " + -// "COALESCE(SUM(CASE WHEN pd.file_status = 11 THEN 1 ELSE 0 END), 0) AS completed " + -// "FROM gcc_pensioner.file_category_master fm " + -// "LEFT JOIN gcc_pensioner.pensioner_details pd " + -// "ON pd.file_category = fm.id " + -// "AND pd.created_date BETWEEN ? AND ? " + -// "AND pd.dept_id = ? " + -// "AND pd.is_closed = 0 " + // Ensure only active records are considered -// "GROUP BY fm.file_name"; - - - public List> getReportData(String startDate, String endDate, String deptId) { - String sql = "SELECT fm.id, " + - " fm.file_name AS file_name, " + - - // Audit Pending Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status IN (1,3) AND pd.dept_id = ? " + - " AND pd.file_category=fm.id "+ - " AND pd.is_closed = 0 " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS audit_pending, " + - - // Department Pending Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status IN (2,5,6,9) AND pd.dept_id = ? " + - " AND pd.file_category=fm.id "+ - " AND pd.is_closed = 0 " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS department_pending, " + - - // Pension Pending Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status IN (4,7,8,10) AND pd.dept_id = ? " + - " AND pd.file_category=fm.id "+ - " AND pd.is_closed = 0 " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS pension_pending, " + - - // Completed Count (SUM of two tables) - " (COALESCE((SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status = 11 AND pd.dept_id = ? " + - " AND pd.file_category=fm.id "+ - " AND pd.is_closed = 0 " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)), 0) " + - " + " + - " COALESCE((SELECT COUNT(*) FROM cps_pensioner_details cps " + - " WHERE cps.file_status = 11 AND cps.dept_id = ? " + - " AND cps.file_category=fm.id "+ - " AND DATE(cps.created_date) BETWEEN DATE(?) AND DATE(?)), 0)) AS completed, " + - - // Total Files Count (SUM of two tables) - " (COALESCE((SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.dept_id = ? " + - " AND pd.file_category=fm.id "+ - " AND pd.is_closed = 0 " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)), 0) " + - " + " + - " COALESCE((SELECT COUNT(*) FROM cps_pensioner_details cps " + - " WHERE cps.dept_id = ? " + - " AND cps.file_category=fm.id "+ - " AND DATE(cps.created_date) BETWEEN DATE(?) AND DATE(?)), 0)) AS total_files " + - - "FROM file_category_master fm " + - "GROUP BY fm.id, fm.file_name " + // Correct placement of GROUP BY - "ORDER BY fm.id"; // ORDER BY after GROUP BY - - List params = new ArrayList<>(); - - // Adding parameters in the correct order for each subquery - for (int i = 0; i < 7; i++) { // 6 subqueries that use deptId, startDate, endDate - params.add(deptId); - params.add(startDate); - params.add(endDate); - } - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - - - - public List> getReportDetails(String startDate, String endDate, Integer deptId, Integer fileCatId, List fileStatus) { - String sql = ""; - List params = new ArrayList<>(); - - // Construct fileStatus condition - String fileStatusCondition = (fileStatus != null && !fileStatus.isEmpty()) - ? " AND pd.file_status IN (" + String.join(",", Collections.nCopies(fileStatus.size(), "?")) + ")" - : ""; // Skip condition if fileStatus is empty or null - - if (fileCatId == 6) { - sql = "SELECT pd.emp_no, pd.emp_name, pd.designation, pd.type_of_retirement, pd.reason_for_pending, pd.retirement_date, " + - "fm.file_status AS fst, pd.file_category_name, pd.remarks, DATE(pd.created_date) AS created_date " + - "FROM cps_pensioner_details pd " + - "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + - "WHERE DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?) " + // First date filter - "AND pd.dept_id = ? " + // Next deptId - "AND pd.file_category = ? " + // Next fileCatId - fileStatusCondition; // Last fileStatus condition - - } else { - sql = "SELECT pd.*, fm.file_status AS fst " + - "FROM pensioner_details pd " + - "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + - "WHERE DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?) " + // First date filter - "AND pd.dept_id = ? " + // Next deptId - "AND pd.file_category = ? " + // Next fileCatId - fileStatusCondition; // Last fileStatus condition - } - - // Add date range parameters first - params.add(startDate); - params.add(endDate); - - // Add deptId and fileCatId parameters - params.add(deptId); - params.add(fileCatId); - - // Add fileStatus parameters if present - if (fileStatus != null && !fileStatus.isEmpty()) { - params.addAll(fileStatus); - } - - System.out.println("Executing SQL Query: " + sql); - System.out.println("Query Parameters: " + params); - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - - - - - - //pensioner side reorts methods - - public List> getstatus() { - String sql = "select id , file_status from file_status_master"; - return jdbcTemplate.queryForList(sql); - } - - public List> getdepartment() { - String sql = "select dept_id ,dept_name from department_master WHERE dept_id <> 2000"; - return jdbcTemplate.queryForList(sql); - } - - -// public List> getReportDatapension(String startDate, String endDate, String fileCategoryId) { -// String sql = "SELECT fm.file_name, " + -// "fm.id AS file_category_id, " + -// "COALESCE(dm.dept_name, 'All Departments') AS dept_name, " + -// "COALESCE(SUM(CASE WHEN pd.file_status IN (1,3) OR cps.file_status IN (1,3) THEN 1 ELSE 0 END), 0) AS audit_pending, " + -// "COALESCE(SUM(CASE WHEN pd.file_status IN (2,5,6,9) OR cps.file_status IN (2,5,6,9) THEN 1 ELSE 0 END), 0) AS department_pending, " + -// "COALESCE(SUM(CASE WHEN pd.file_status IN (4,7,8,10) OR cps.file_status IN (4,7,8,10) THEN 1 ELSE 0 END), 0) AS pension_pending, " + -// "COALESCE(SUM(CASE WHEN pd.file_status = 11 OR cps.file_status = 11 THEN 1 ELSE 0 END), 0) AS completed, " + -// "COALESCE(COUNT(pd.id) + COUNT(cps.id), 0) AS total_files " + -// "FROM gcc_pensioner.file_category_master fm " + -// "LEFT JOIN gcc_pensioner.cps_pensioner_details cps ON cps.file_category = fm.id " + -// "LEFT JOIN gcc_pensioner.pensioner_details pd ON pd.file_category = fm.id " + -// "LEFT JOIN gcc_pensioner.department_master dm ON dm.dept_id = COALESCE(pd.dept_id, cps.dept_id) " + -// "WHERE (pd.created_date BETWEEN ? AND ? OR cps.created_date BETWEEN ? AND ?) " + -// (fileCategoryId != null && !fileCategoryId.isEmpty() ? "AND fm.id = ? " : "") + -// "GROUP BY fm.id, fm.file_name, dm.dept_name " + -// "ORDER BY fm.id, dm.dept_name, fm.file_name"; -// -// System.out.println("Executing SQL: " + sql); -// -// List params = new ArrayList<>(); -// params.add(startDate); -// params.add(endDate); -// params.add(startDate); // Date filter applies to both `pd` and `cps` -// params.add(endDate); -// -// if (fileCategoryId != null && !fileCategoryId.isEmpty()) { -// params.add(fileCategoryId); -// } -// -// return jdbcTemplate.queryForList(sql, params.toArray()); -// } - - - - -// public List> getReportDatapension(String startDate, String endDate, String fileCategoryId) { -// String sql = "SELECT dm.dept_id, " + -// " dm.dept_name AS dept_name, " + -// -// // Audit Pending Count -// " (SELECT COUNT(*) FROM pensioner_details pd " + -// " WHERE pd.file_status IN (1,3) AND pd.dept_id = dm.dept_id " + -// " AND pd.is_closed = 0 " + // Added condition -// " AND ( ? IS NULL OR pd.file_category = ? ) " + -// " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS audit_pending, " + -// -// // Department Pending Count -// " (SELECT COUNT(*) FROM pensioner_details pd " + -// " WHERE pd.file_status IN (2,5,6,9) AND pd.dept_id = dm.dept_id " + -// " AND pd.is_closed = 0 " + // Added condition -// " AND ( ? IS NULL OR pd.file_category = ? ) " + -// " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS department_pending, " + -// -// // Pension Pending Count -// " (SELECT COUNT(*) FROM pensioner_details pd " + -// " WHERE pd.file_status IN (4,7,8,10) AND pd.dept_id = dm.dept_id " + -// " AND pd.is_closed = 0 " + // Added condition -// " AND ( ? IS NULL OR pd.file_category = ? ) " + -// " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS pension_pending, " + -// -// // Completed Count -// " (SELECT COUNT(*) FROM pensioner_details pd " + -// " WHERE pd.file_status = 11 AND pd.dept_id = dm.dept_id " + -// " AND pd.is_closed = 0 " + // Added condition -// " AND ( ? IS NULL OR pd.file_category = ? ) " + -// " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) " + -// " + " + -// " (SELECT COUNT(*) FROM cps_pensioner_details cps " + -// " WHERE cps.file_status = 11 AND cps.dept_id = dm.dept_id " + -// " AND ( ? IS NULL OR cps.file_category = ? ) " + -// " AND DATE(cps.created_date) BETWEEN DATE(?) AND DATE(?)) AS completed, " + -// -// // Total Files Count -// " (SELECT COUNT(*) pensioner_details pd " + -// " WHERE pd.dept_id = dm.dept_id " + -// " AND pd.is_closed = 0 " + // Added condition -// " AND ( ? IS NULL OR pd.file_category = ? ) " + -// " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) " + -// " + " + -// " (SELECT COUNT(*) FROM cps_pensioner_details cps " + -// " WHERE cps.dept_id = dm.dept_id " + -// " AND ( ? IS NULL OR cps.file_category = ? ) " + -// " AND DATE(cps.created_date) BETWEEN DATE(?) AND DATE(?)) AS total_files " + -// -// "FROM department_master dm " + -// "ORDER BY dm.dept_id"; -// -// System.out.println("Executing SQL: " + sql); -// -// List params = new ArrayList<>(); -// -// // Adding parameters explicitly without a loop -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); -// params.add(fileCategoryId); -// params.add(startDate); -// params.add(endDate); -// -// return jdbcTemplate.queryForList(sql, params.toArray()); -// } - - - public List> getReportDatapension(String startDate, String endDate, String fileCategoryId) { - String sql = "SELECT dm.dept_id, " + - " dm.dept_name AS dept_name, " + - - // Audit Pending Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status IN (1,3) AND pd.dept_id = dm.dept_id " + - " AND pd.is_closed = 0 " + - " AND ( ? IS NULL OR pd.file_category = ? ) " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS audit_pending, " + - - // Department Pending Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status IN (2,5,6,9) AND pd.dept_id = dm.dept_id " + - " AND pd.is_closed = 0 " + - " AND ( ? IS NULL OR pd.file_category = ? ) " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS department_pending, " + - - // Pension Pending Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status IN (4,7,8,10) AND pd.dept_id = dm.dept_id " + - " AND pd.is_closed = 0 " + - " AND ( ? IS NULL OR pd.file_category = ? ) " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) AS pension_pending, " + - - // Completed Count - " (SELECT COUNT(*) FROM pensioner_details pd " + - " WHERE pd.file_status = 11 AND pd.dept_id = dm.dept_id " + - " AND pd.is_closed = 0 " + - " AND ( ? IS NULL OR pd.file_category = ? ) " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) " + - " + " + - " (SELECT COUNT(*) FROM cps_pensioner_details cps " + - " WHERE cps.file_status = 11 AND cps.dept_id = dm.dept_id " + - " AND ( ? IS NULL OR cps.file_category = ? ) " + - " AND DATE(cps.created_date) BETWEEN DATE(?) AND DATE(?)) AS completed, " + - - // Total Files Count - " (SELECT COUNT(*) FROM pensioner_details pd " + // Fixed Syntax - " WHERE pd.dept_id = dm.dept_id " + - " AND pd.is_closed = 0 " + - " AND ( ? IS NULL OR pd.file_category = ? ) " + - " AND DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?)) " + - " + " + - " (SELECT COUNT(*) FROM cps_pensioner_details cps " + - " WHERE cps.dept_id = dm.dept_id " + - " AND ( ? IS NULL OR cps.file_category = ? ) " + - " AND DATE(cps.created_date) BETWEEN DATE(?) AND DATE(?)) AS total_files " + - - "FROM department_master dm " + - "ORDER BY dm.dept_id"; - - System.out.println("Executing SQL: " + sql); - - List params = new ArrayList<>(); - - for (int i = 0; i < 7; i++) { - params.add(fileCategoryId != null && !fileCategoryId.isEmpty() ? fileCategoryId : null); - params.add(fileCategoryId); - params.add(startDate); - params.add(endDate); - } - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - - -// public List> getReportDetailspension(String startDate, String endDate, List deptIds, Integer fileCatId, List fileStatus) { -// String sql = ""; -// List params = new ArrayList<>(); -// -// boolean selectAll = deptIds.contains("ALL"); -// -// // ✅ If "ALL" is selected, remove department filtering -// String deptCondition = selectAll ? "1=1" : "pd.dept_id IN (" + String.join(",", Collections.nCopies(deptIds.size(), "?")) + ")"; -// -// // ✅ Handle fileStatus as multiple values in IN clause -// String fileStatusCondition = (fileStatus != null && !fileStatus.isEmpty()) -// ? " AND pd.file_status IN (" + String.join(",", Collections.nCopies(fileStatus.size(), "?")) + ")" -// : ""; // Skip condition if fileStatus is empty or null -// -// if (fileCatId == 6) { -// sql = "SELECT pd.emp_no, pd.emp_name, pd.designation, pd.type_of_retirement, pd.reason_for_pending, " + -// "fm.file_status AS fst, pd.file_category_name, pd.remarks, DATE(pd.created_date) AS created_date " + -// "FROM cps_pensioner_details pd " + -// "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + -// "WHERE " + deptCondition + " AND pd.file_category = ?" + fileStatusCondition; -// -// if (!selectAll) { -// params.addAll(deptIds); -// } -// params.add(fileCatId); -// if (fileStatus != null && !fileStatus.isEmpty()) { -// params.addAll(fileStatus); -// } -// } -// else { -// sql = "SELECT pd.*, fm.file_status as fst FROM pensioner_details pd " + -// "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + -// "WHERE " + deptCondition + " AND pd.file_category = ?" + fileStatusCondition; -// -// if (!selectAll) { -// params.addAll(deptIds); -// } -// params.add(fileCatId); -// if (fileStatus != null && !fileStatus.isEmpty()) { -// params.addAll(fileStatus); -// } -// } -// -// System.out.println("Executing SQL Query: " + sql); -// System.out.println("Query Parameters: " + params); -// -// return jdbcTemplate.queryForList(sql, params.toArray()); -// } - - - -// public List> getReportDetailspension(String startDate, String endDate, List deptIds, Integer fileCatId, List fileStatus) { -// String sql = ""; -// List params = new ArrayList<>(); -// -// boolean selectAll = deptIds.contains("ALL"); -// -// // ✅ If "ALL" is selected, remove department filtering -// String deptCondition = selectAll ? "1=1" : "pd.dept_id IN (" + String.join(",", Collections.nCopies(deptIds.size(), "?")) + ")"; -// -// // ✅ Handle fileStatus as multiple values in IN clause -// String fileStatusCondition = (fileStatus != null && !fileStatus.isEmpty()) -// ? " AND pd.file_status IN (" + String.join(",", Collections.nCopies(fileStatus.size(), "?")) + ")" -// : ""; // Skip condition if fileStatus is empty or null -// -// if (fileCatId == 6) { -// sql = "SELECT pd.emp_no, pd.emp_name, pd.designation, pd.type_of_retirement, pd.reason_for_pending,pd.retirement_date, " + -// "fm.file_status AS fst, pd.file_category_name, pd.remarks, DATE(pd.created_date) AS created_date " + -// "FROM cps_pensioner_details pd " + -// "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + -// "WHERE DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?) " + // First: Date filter -// "AND pd.file_category = ? " + // Second: File category filter -// "AND " + deptCondition + // Third: Department condition -// fileStatusCondition; // Last: File status condition -// -// } else { -// sql = "SELECT pd.*, fm.file_status as fst " + -// "FROM pensioner_details pd " + -// "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + -// "WHERE DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?) " + // First: Date filter -// "AND pd.file_category = ? " + // Second: File category filter -// "AND " + deptCondition + // Third: Department condition -// fileStatusCondition; // Last: File status condition -// } -// -// // Add date range parameters first -// params.add(startDate); -// params.add(endDate); -// -// // Add file category next -// params.add(fileCatId); -// -// // Add department filter parameters if not "ALL" -// if (!selectAll) { -// params.addAll(deptIds); -// } -// -// // Add fileStatus parameters if present -// if (fileStatus != null && !fileStatus.isEmpty()) { -// params.addAll(fileStatus); -// } -// -// System.out.println("Executing SQL Query: " + sql); -// System.out.println("Query Parameters: " + params); -// -// return jdbcTemplate.queryForList(sql, params.toArray()); -// } - - - - public List> getReportDetailspension(String startDate, String endDate, List deptIds, Integer fileCatId, List fileStatus) { - String sql = ""; - List params = new ArrayList<>(); - - // ✅ Ensure deptIds is never empty, otherwise fetch nothing - if (deptIds == null || deptIds.isEmpty()) { - return new ArrayList<>(); - } - - // ✅ Construct IN clause for department filtering - String deptCondition = "pd.dept_id IN (" + String.join(",", Collections.nCopies(deptIds.size(), "?")) + ")"; - - // ✅ Handle fileStatus as multiple values in IN clause - String fileStatusCondition = (fileStatus != null && !fileStatus.isEmpty()) - ? " AND pd.file_status IN (" + String.join(",", Collections.nCopies(fileStatus.size(), "?")) + ")" - : ""; // Skip condition if fileStatus is empty or null - - if (fileCatId == 6) { - sql = "SELECT pd.emp_no, pd.emp_name, pd.designation, pd.type_of_retirement, pd.reason_for_pending, pd.retirement_date, " + - "fm.file_status AS fst, pd.file_category_name, pd.remarks, DATE(pd.created_date) AS created_date " + - "FROM cps_pensioner_details pd " + - "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + - "WHERE DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?) " + - "AND pd.file_category = ? " + - "AND " + deptCondition + - fileStatusCondition; - - } else { - sql = "SELECT pd.*, fm.file_status as fst " + - "FROM pensioner_details pd " + - "INNER JOIN file_status_master fm ON pd.file_status = fm.id " + - "WHERE DATE(pd.created_date) BETWEEN DATE(?) AND DATE(?) " + - "AND pd.file_category = ? " + - "AND " + deptCondition + - fileStatusCondition; - } - - // Add date range parameters first - params.add(startDate); - params.add(endDate); - - // Add file category next - params.add(fileCatId); - - // Add department filter parameters - params.addAll(deptIds); - - // Add fileStatus parameters if present - if (fileStatus != null && !fileStatus.isEmpty()) { - params.addAll(fileStatus); - } - - System.out.println("Executing SQL Query: " + sql); - System.out.println("Query Parameters: " + params); - - return jdbcTemplate.queryForList(sql, params.toArray()); - } - - - - public List> getDepartmentpending(int file_category) { - - String sql = "SELECT dept_name, emp_name, emp_no, file_category_name, file_status, file_moved_date, remarks " + - "FROM pensioner_details WHERE file_status IN (2, 5, 6, 9) AND file_category=?"; - - List> results = jdbcTemplate.queryForList(sql, file_category); - - return jdbcTemplate.queryForList(sql, file_category); - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReturnFromAuditService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReturnFromAuditService.java deleted file mode 100644 index 9c2fee87..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReturnFromAuditService.java +++ /dev/null @@ -1,220 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pensioner.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@Service -@Transactional -public class ReturnFromAuditService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - private RestTemplate restTemplate; - private ObjectMapper objectMapper; - @Autowired - private AppConfig appconfig; - - public ReturnFromAuditService(RestTemplate restTemplate, ObjectMapper objectMapper) { - this.restTemplate = restTemplate; - this.objectMapper = objectMapper; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlPensionerDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public GetFileStatusService getFileStatus; - - public List> fetchReturnEmpfiles(Integer deptId,Integer file_cat) { - String query = "SELECT * " + - "FROM pensioner_details " + - "WHERE file_status=2 AND dept_id=? AND file_category=? AND is_closed=0"; - - - return jdbcTemplate.queryForList(query,deptId,file_cat); - } - - public boolean updateEntryDetails(Map requestData) { - // TODO Auto-generated method stub - String empNo = (String) requestData.get("empNo"); - String tempId = (String) requestData.get("tempId"); - String dateToAudit = (String) requestData.get("dateToAudit"); - String filemovedby =(String)requestData.get("filemovedby"); - String remarks = (String) requestData.get("remarks"); - String dept_Id = (String) requestData.get("deptId"); - - int deptId = Integer.parseInt(dept_Id); - int filestatus = getFileStatus.getFileStatus3Id(); - if (filestatus == 0) { - System.out.println("File status not found. Aborting insertion."); - return false; - } - - // Update file_status in pensioner_details - String updateQuery = "UPDATE pensioner_details SET file_status = ?,file_moved_date=?,remarks=?,updated_date= CURRENT_TIMESTAMP WHERE temp_id = ? LIMIT 1"; - int rowsUpdated = jdbcTemplate.update(updateQuery,filestatus,dateToAudit, remarks,tempId); - System.out.println("Rows inserted in pd:"+rowsUpdated); - if(rowsUpdated>0) - { - // Optional: Insert into file movement history for auditing - String historyQuery = "INSERT INTO file_movement_history (emp_no, file_moved_date, file_status, file_moved_by, remarks,temp_id) VALUES (?,?, ?, ?, ?, ?)"; - int rowsUpdated1=jdbcTemplate.update(historyQuery, empNo, dateToAudit, filestatus, filemovedby, remarks,tempId); - System.out.println("Rows inserted in fmh:"+rowsUpdated1); - - return true; - } - else { - return false; - } - - } - - public boolean savehistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String retirement_date = emp.get("retirement_date").toString(); - String retirement_class = emp.get("retirement_class").toString(); - String type_of_retirement = emp.get("type_of_retirement").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, type_of_retirement,retirement_date ,retirement_class,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,type_of_retirement,retirement_date,retirement_class,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - - - //save the updatedfamilypensionReturn - - public boolean saveFamilyPensionReturnHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - String sericeDeath = emp.get("service_death").toString(); - String relationshipDeceased = emp.get("relationship_deceased").toString(); - String sanctionedGis = emp.get("sanctioned_gis_amount").toString(); - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation, service_death,relationship_deceased ,sanctioned_gis_amount,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,file_category_name,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,sericeDeath,relationshipDeceased,sanctionedGis,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,fileCategoryName,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } - - //update save pendency history - public boolean savePendencyHistory(List> emp_details,String filemovedby) { - try { - // Loop through the list of employee details - for (Map emp : emp_details) { - // Extract individual fields from the map - String empNo = emp.get("emp_no").toString(); - String empName = emp.get("emp_name").toString(); - String deptName = emp.get("dept_name").toString(); - String designation = emp.get("designation").toString(); - String retirementClass = emp.get("retirement_class").toString(); - String retirementDate=emp.get("retirement_date").toString(); - //String fileCategoryName = emp.get("file_category_name").toString(); - String pendingDuration=emp.get("pending_duration").toString(); - String pendingReason=emp.get("reason_for_pending") != null ? emp.get("reason_for_pending").toString() : null; - - String typeOfCategory=emp.get("file_category_name").toString(); - String typeOfRetirement=emp.get("type_of_retirement").toString(); - - String fileMovedDate = emp.get("file_moved_date").toString(); - String remarks = emp.get("remarks").toString(); - int fileStatus = Integer.parseInt(emp.get("file_status").toString()); - String fileEntryType = emp.get("file_entry_type").toString(); - int file_category = Integer.parseInt(emp.get("file_category").toString()); - int dept_id = Integer.parseInt(emp.get("dept_id").toString()); - String temp_id = emp.get("temp_id").toString(); - - // Prepare the insert query - String insertQuery ="INSERT INTO pensioner_details_history (emp_no, emp_name, dept_name, designation,retirement_class,retirement_date,file_category_name,type_of_retirement,file_moved_date, remarks,file_category,file_status,file_entry_type,file_moved_by,dept_id,temp_id,pending_duration,reason_for_pending) VALUES (?,?,?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?)"; - - // Execute the query - int rowsInserted = jdbcTemplate.update(insertQuery, empNo, empName, deptName,designation,retirementClass,retirementDate,typeOfCategory,typeOfRetirement,fileMovedDate,remarks,file_category,fileStatus,fileEntryType,filemovedby,dept_id,temp_id,pendingDuration,pendingReason); - System.out.println("Rows inserted in pdh:"+rowsInserted); - // Check if the insertion was successful - if (rowsInserted <= 0) { - return false; // Return false if any insertion fails - } - } - - return true; // Return true if all insertions succeed - } catch (Exception e) { - e.printStackTrace(); - return false; // Return false in case of any exception - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/controller/APIController.java deleted file mode 100644 index 205f4c6f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/controller/APIController.java +++ /dev/null @@ -1,82 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("/gcc/api/petregistration") -@RestController("petRegistrationRest") -public class APIController { - private final RestTemplate restTemplate; - private final AppConfig appConfig; - String bodyMessage = ""; - - @Autowired - public APIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @GetMapping(value = "/getpetimg") - public String getPetImage(@RequestParam String mobno,@RequestParam String uniqueid) { - String baseURL = appConfig.petRegistration+"/api/getpetimg"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("mobno", mobno) - .queryParam("uniqueid", uniqueid ); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping(value = "/getvaccineimg") - public String getVaccineImage(@RequestParam String mobno,@RequestParam String uniqueid) { - String baseURL = appConfig.petRegistration+"/api/getvacimg"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("mobno", mobno) - .queryParam("uniqueid", uniqueid ); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping(value = "/getapplicantimg") - public String getApplicantImage(@RequestParam String mobno,@RequestParam String uniqueid) { - String baseURL = appConfig.petRegistration+"/api/getapplicantimg"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("mobno", mobno) - .queryParam("uniqueid", uniqueid ); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping(value = "/getaddressproofimg") - public String getAddressProofImage(@RequestParam String mobno,@RequestParam String uniqueid) { - String baseURL = appConfig.petRegistration+"/api/getaddproofimg"; - UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseURL) - .queryParam("mobno", mobno) - .queryParam("uniqueid", uniqueid ); - - ResponseEntity response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/controller/MainController.java deleted file mode 100644 index 977df874..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/controller/MainController.java +++ /dev/null @@ -1,168 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.controller; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Lookup; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.petregistration.data.PetCountInfo; -import in.gov.chennaicorporation.gccoffice.petregistration.data.RequestList; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/petregistration") -@Controller("petregistration") -public class MainController { - private final RestTemplate restTemplate; - private final LoginUserInfo loginUserInfo; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate,LoginUserInfo loginUserInfo, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.loginUserInfo = loginUserInfo; - this.appConfig = appConfig; - } - - @Lookup - public static String[] getDates() { - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.MONTH, -1); - - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - - String formattedDate = dateFormat.format(calendar.getTime()); - - String currentDate = dateFormat.format(new Date()); - System.out.println("formattedDate : "+formattedDate); - return new String[] { formattedDate, currentDate }; - } - - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String main(Model model,@RequestParam(required=false) String zone) { - String userId = LoginUserInfo.getLoginUserId(); - String baseUrl = appConfig.petRegistration + "/api/admin/dashboard"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl).queryParam("zone",zone); - PetCountInfo dash = restTemplate.getForObject(builder.toUriString(),PetCountInfo.class); - if (userId != null && !userId.isEmpty()) { - System.out.println("String UserID: " + userId); - } - model.addAttribute("dash",dash); - return "modules/petregistration/index"; - } - - @GetMapping("/requestlist") - public String viewRequest(Model model, - @RequestParam(required=false) String fromDate, - @RequestParam(required =false) String toDate, - @RequestParam(required=false) String zone) { - - if(fromDate==null && toDate==null) { - String[] dates = getDates(); - fromDate=dates[0]; - toDate=dates[1]; - model.addAttribute(fromDate); - model.addAttribute(toDate); - } - - String baseUrl = appConfig.petRegistration + "/api/admin/licenserequest"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("zone",zone) - .queryParam("fromDate",fromDate) - .queryParam("toDate",toDate); - - RequestList[] requestList = restTemplate.getForObject(builder.toUriString(), RequestList[].class); - model.addAttribute("petlist",requestList); - - return "modules/petregistration/request-list"; - } - - @GetMapping("/acceptedlist") - public String viewAccepted(Model model, - @RequestParam(required=false) String fromDate, - @RequestParam(required =false) String toDate, - @RequestParam(required=false) String zone) { - - if(fromDate==null && toDate==null) { - String[] dates = getDates(); - fromDate=dates[0]; - toDate=dates[1]; - model.addAttribute(fromDate); - model.addAttribute(toDate); - } - - String baseUrl = appConfig.petRegistration + "/api/admin/acceptedlist"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("zone",zone) - .queryParam("fromDate",fromDate) - .queryParam("toDate",toDate); - - RequestList[] requestList = restTemplate.getForObject(builder.toUriString(), RequestList[].class); - model.addAttribute("petlist",requestList); - - return "modules/petregistration/accepted-list"; - } - - @GetMapping("/rejectedlist") - public String viewRejected(Model model, - @RequestParam(required=false) String fromDate, - @RequestParam(required =false) String toDate, - @RequestParam(required=false) String zone) { - - if(fromDate==null && toDate==null) { - String[] dates = getDates(); - fromDate=dates[0]; - toDate=dates[1]; - model.addAttribute(fromDate); - model.addAttribute(toDate); - } - - String baseUrl = appConfig.petRegistration + "/api/admin/rejectedlist"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("zone",zone) - .queryParam("fromDate",fromDate) - .queryParam("toDate",toDate); - - RequestList[] requestList = restTemplate.getForObject(builder.toUriString(), RequestList[].class); - model.addAttribute("petlist",requestList); - - return "modules/petregistration/accepted-list"; - } - - @GetMapping("/licenseissued") - public String viewLicenseIssued(Model model, - @RequestParam(required=false) String fromDate, - @RequestParam(required =false) String toDate, - @RequestParam(required=false) String zone) { - - if(fromDate==null && toDate==null) { - String[] dates = getDates(); - fromDate=dates[0]; - toDate=dates[1]; - model.addAttribute(fromDate); - model.addAttribute(toDate); - } - - String baseUrl = appConfig.petRegistration + "/api/admin/licenseIssued"; - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) - .queryParam("zone",zone) - .queryParam("fromDate",fromDate) - .queryParam("toDate",toDate); - - RequestList[] requestList = restTemplate.getForObject(builder.toUriString(), RequestList[].class); - model.addAttribute("petlist",requestList); - - return "modules/petregistration/accepted-list"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/PetCountInfo.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/PetCountInfo.java deleted file mode 100644 index 0714a0d2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/PetCountInfo.java +++ /dev/null @@ -1,46 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.data; - -import java.util.Map; - -public class PetCountInfo { - - private Map dog; - private Map cat; - private int userCount; - private int licCount; - - // Getters and setters - - public Map getDog() { - return dog; - } - - public void setDog(Map dog) { - this.dog = dog; - } - - public Map getCat() { - return cat; - } - - public void setCat(Map cat) { - this.cat = cat; - } - - public int getUserCount() { - return userCount; - } - - public void setUserCount(int userCount) { - this.userCount = userCount; - } - - public int getLicCount() { - return licCount; - } - - public void setLicCount(int licCount) { - this.licCount = licCount; - } -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/RequestList.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/RequestList.java deleted file mode 100644 index 09cf9ce1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/RequestList.java +++ /dev/null @@ -1,150 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class RequestList { - private int uniqueid; - private long mobilenum; - private String petname; - private String species; - private String breed; - private String gender; - private String registerdate; - private int status; - private String rejectreason; - private String zone; - private String statusdate; - private String updatedby; - - - // Constructor - public RequestList() { - - } - - @JsonCreator - public RequestList(@JsonProperty("uniqueid") int uniqueid, - @JsonProperty("mobilenum") long mobilenum, - @JsonProperty("petname") String petname, - @JsonProperty("species") String species, - @JsonProperty("breed") String breed, - @JsonProperty("gender") String gender, - @JsonProperty("registerdate") String registerdate, - @JsonProperty("status") int status, - @JsonProperty("rejectreason") String rejectreason, - @JsonProperty("zone") String zone, - @JsonProperty("statusdate") String statusdate, - @JsonProperty("updatedby") String updatedby) { - - this.uniqueid = uniqueid; - this.mobilenum = mobilenum; - this.petname = petname; - this.species = species; - this.breed = breed; - this.gender = gender; - this.registerdate = registerdate; - this.status = status; - this.rejectreason = rejectreason; - this.zone = zone; - this.statusdate = statusdate; - this.updatedby = updatedby; - } - - // Getters and setters for each field - public int getUniqueid() { - return uniqueid; - } - - public void setUniqueid(int uniqueid) { - this.uniqueid = uniqueid; - } - - public long getMobilenum() { - return mobilenum; - } - - public void setMobilenum(long mobilenum) { - this.mobilenum = mobilenum; - } - - public String getPetname() { - return petname; - } - - public void setPetname(String petname) { - this.petname = petname; - } - - public String getSpecies() { - return species; - } - - public void setSpecies(String species) { - this.species = species; - } - - public String getBreed() { - return breed; - } - - public void setBreed(String breed) { - this.breed = breed; - } - - public String getGender() { - return gender; - } - - public void setGender(String gender) { - this.gender = gender; - } - - public String getRegisterdate() { - return registerdate; - } - - public void setRegisterdate(String registerdate) { - this.registerdate = registerdate; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getRejectreason() { - return rejectreason; - } - - public void setRejectreason(String rejectreason) { - this.rejectreason = rejectreason; - } - - public String getZone() { - return zone; - } - - public void setZone(String zone) { - this.zone = zone; - } - - public String getStatusdate() { - return statusdate; - } - - public void setStatusdate(String statusdate) { - this.statusdate = statusdate; - } - - public String getUpdatedby() { - return updatedby; - } - - public void setUpdatedby(String updatedby) { - this.updatedby = updatedby; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/ResponseWrapper.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/ResponseWrapper.java deleted file mode 100644 index 35e697e1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/ResponseWrapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.data; - -import java.util.List; - -public class ResponseWrapper { - private List data; - - public List getData() { - return data; - } - - public void setData(List data) { - this.data = data; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/package-info.java deleted file mode 100644 index 71394d68..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/package-info.java deleted file mode 100644 index 02b3ead6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/service/API.java b/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/service/API.java deleted file mode 100644 index 7b0e8739..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/petregistration/service/API.java +++ /dev/null @@ -1,5 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.petregistration.service; - -public class API { - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/APIController.java deleted file mode 100644 index 47c561dc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/APIController.java +++ /dev/null @@ -1,139 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.controller; - -import java.net.URLDecoder; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.pgr.service.DataSyncService; -import in.gov.chennaicorporation.gccoffice.pgr.service.PGRCommon; -import in.gov.chennaicorporation.gccoffice.repository.UserActivityLogRepository; - -@RequestMapping("/gcc/api/pgr") -@RestController("pgrRest") -public class APIController { - - private PGRCommon pgrCommon; - - @Autowired - public APIController(PGRCommon pgrCommon) { - - this.pgrCommon = pgrCommon; - } - - @Autowired - private DataSyncService dataSyncService; - - @GetMapping(value="/getDepartments") - public List getDepartmentList() { - return pgrCommon.getDeaprtmentList(); - } - - @GetMapping(value="/getPendingComplaintCount") - public List getPendingComplaintCount() { - return pgrCommon.getPendingComplanitCount(); - } - - @GetMapping(value="/getZoneWisePendingComplaintCount") - public List getZoneWisePendingComplaintCount() { - return pgrCommon.getZoneWisePendingComplanitCount(); - } - - @GetMapping(value="/getZoneWiseReopenComplaintCount") - public List getZoneWiseReopenComplaintCount() { - return pgrCommon.getZoneWiseReopenComplanitCount(); - } - - @GetMapping(value="/getComplaintsList") - public List getComplaintsList() { - return pgrCommon.getComplaintsList(); - } - - @GetMapping(value="/getQaQcList") - public List getQaQcList() { - return pgrCommon.getQaQcList(); - } - - @GetMapping(value="/getZoneWiseComplaintCountList") - public List getZoneWiseComplaintList() { - return pgrCommon.getZoneWiseComplaintCountList(); - } - - @GetMapping(value="/getZoneWiseWithoutReopenComplaintList") - public List getZoneWiseWithoutReopenComplaintList() { - return pgrCommon.getZoneWiseWithoutReopenComplaintCountList(); - } - - @GetMapping(value="/getComplaintDetails") - public List getComplaintDetails(@RequestParam("complaintNumber") String complaintNumber) { - return pgrCommon.getComplaintDetails(complaintNumber); - } - - // For Sub Pages - @GetMapping(value="/getZoneWiseOfficerComplaintCountList") - public List getZoneWiseOfficerComplaintCountList(@RequestParam("deptid") String deptid, @RequestParam("complainttype") String complainttype) { - return pgrCommon.getZoneWiseOfficerComplaintCountList(deptid, complainttype); - } - - @GetMapping(value="/getZoneWiseOfficerComplaintList") - public List getZoneWiseOfficerComplaintList(@RequestParam("deptid") String deptid, @RequestParam("complainttype") String complainttype, @RequestParam("iduser") String iduser) { - return pgrCommon.getZoneWiseOfficerComplaintList(deptid, complainttype,iduser); - } - - @GetMapping(value="/getZoneWiseOfficerWithoutReopenComplaintCountList") - public List getZoneWiseOfficerWithoutReopenComplaintCountList(@RequestParam("deptid") String deptid, @RequestParam("complainttype") String complainttype) { - return pgrCommon.getZoneWiseOfficerWithoutReopenComplaintCountList(deptid, complainttype); - } - - @GetMapping(value="/getZoneWiseOfficerWithoutReopenComplaintList") - public List getZoneWiseOfficerWithoutReopenComplaintList(@RequestParam("deptid") String deptid, @RequestParam("complainttype") String complainttype, @RequestParam("iduser") String iduser) { - return pgrCommon.getZoneWiseOfficerWithoutReopenComplaintList(deptid, complainttype,iduser); - } - - @GetMapping(value="/syncERPtoLocal") - public String syncERPtoLocal() { - return syncData(); - } - - public String syncData() { - System.out.println("Starting Syning EG_USER Table Data.\n"); - dataSyncService.syncEgUserData(); - System.out.println("EG_USER Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EG_DEPARTMENT Table Data.\n"); - dataSyncService.syncEgDepartmentData(); - System.out.println("EG_DEPARTMENT Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EG_BOUNDARY Table Data.\n"); - dataSyncService.syncEgBoundaryData(); - System.out.println("EG_BOUNDARY Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EGGR_COMPLAINTSTATUS Table Data.\n"); - dataSyncService.syncEggrComplaintStatusData(); - System.out.println("EGGR_COMPLAINTSTATUS Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EGGR_COMPLAINTTYPES Table Data.\n"); - dataSyncService.syncEggrComplaintTypesData(); - System.out.println("EGGR_COMPLAINTTYPES Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EGGR_COMPLAINTGROUP Table Data.\n"); - dataSyncService.syncEggrComplaintGroupData(); - System.out.println("EGGR_COMPLAINTGROUP Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EGGR_COMPLAINTDETAILS Table Data.\n"); - dataSyncService.syncEggrComplaintDetailsData(); - System.out.println("EGGR_COMPLAINTDETAILS Table Data synchronization completed.\n"); - - System.out.println("Starting Syning EGGR_REDRESSALDETAILS Table Data.\n"); - dataSyncService.syncEggrComplaintDetailsData(); - System.out.println("EGGR_REDRESSALDETAILS Table Data synchronization completed.\n"); - - return "ERP -> All PGR Data synchronization completed!"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/MainController.java deleted file mode 100644 index 16c8cb1c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/MainController.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.pgr.service.PGRCommon; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/pgr") -@Controller("pgrController") -public class MainController { - private final LoginUserInfo loginUserInfo; - private final PGRCommon dashboards; - - @Autowired - public MainController(LoginUserInfo loginUserInfo, - PGRCommon dashboards) { - this.loginUserInfo = loginUserInfo; - this.dashboards = dashboards; - } - - @GetMapping({"", "/", "/index"}) - public String main(Model model) { - String userId = LoginUserInfo.getLoginUserId(); - if (userId != null && !userId.isEmpty()) { - System.out.println("String UserID: " + userId); - } - return "modules/pgr/index"; - } - - @GetMapping("/all-list") - public String allList(Model model) { - return "modules/pgr/all-list"; - } - - @GetMapping("/qa-qc-list") - public String qaqcList(Model model) { - return "modules/pgr/qa-qc-list"; - } - - @GetMapping("/zone-wise-reports/zone-wise-with-reopen") - public String zoneWiseWithReopnList(Model model) { - return "modules/pgr/zone-wise-with-reopen"; - } - - @GetMapping("/zone-wise-reports/zone-wise-without-reopen") - public String zoneWiseWithoutReopnList(Model model) { - return "modules/pgr/zone-wise-without-reopen"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/package-info.java deleted file mode 100644 index da165f3a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/data/Departments.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/data/Departments.java deleted file mode 100644 index 8500d92f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/data/Departments.java +++ /dev/null @@ -1,35 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Departments { - - private String id; - private String name; - - @JsonCreator - public Departments( - @JsonProperty("id") String id, - @JsonProperty("name") String name - ) { - this.id = id; - this.name = name; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/data/package-info.java deleted file mode 100644 index d18fe0dd..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/package-info.java deleted file mode 100644 index 4ade4f9b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/DataSyncService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/DataSyncService.java deleted file mode 100644 index 922b0e7d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/DataSyncService.java +++ /dev/null @@ -1,1448 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -import javax.sql.DataSource; - -import java.math.BigDecimal; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -@Service -public class DataSyncService { - - private JdbcTemplate oracleJdbcTemplate; - private JdbcTemplate mysqlJdbcTemplate; - - @Autowired - @Qualifier("oracleDataSource") - private DataSource oracleDataSource; - - @Autowired - public void setDataSource(@Qualifier("oracleDataSource") DataSource oracleDataSource, - @Qualifier("mysqlPGRMasterDataSource") DataSource mysqlDataSource) { - this.oracleJdbcTemplate = new JdbcTemplate(oracleDataSource); - this.mysqlJdbcTemplate = new JdbcTemplate(mysqlDataSource); - } - - private int getTotalRecordCount(String tablename) { - String countQuery = "SELECT COUNT(*) FROM "+tablename; - if(tablename.equals("EGGR_COMPLAINTDETAILS@erp")) { - countQuery = "SELECT COUNT(*) FROM "+tablename+" WHERE YEAR(`COMPLAINTDATE`) = '2023'"; - } - if(tablename.equals("EGGR_REDRESSALDETAILS@erp")) { - countQuery = "SELECT COUNT(*) FROM "+tablename+" WHERE YEAR(`RESPONSEDATE`) = '2023'"; - } - return oracleJdbcTemplate.queryForObject(countQuery, Integer.class); - } - - private List> fetchBatch(int startRow, int endRow, String tablename) { - String fetchQuery = ""; - fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+") a " + - "WHERE ROWNUM <= ?) WHERE rnum > ?"; - if(tablename.equals("EGGR_COMPLAINTDETAILS@erp")) { - fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+") a " + - "WHERE ROWNUM <= ?) WHERE rnum > ? AND YEAR(`COMPLAINTDATE`) = '2023'"; - } - if(tablename.equals("EGGR_REDRESSALDETAILS@erp")) { - fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+") a " + - "WHERE ROWNUM <= ?) WHERE rnum > ? AND YEAR(`RESPONSEDATE`) = '2023'"; - } - return oracleJdbcTemplate.queryForList(fetchQuery, endRow, startRow); - } - /* - private List> fetchExistingData(List ids, String tablename, String primaryKeyColumn) { - String idList = ids.stream().map(Objects::toString).collect(Collectors.joining(", ")); - String fetchQuery = "SELECT * FROM "+tablename+" WHERE "+primaryKeyColumn+" IN (" + idList + ")"; - System.out.println(fetchQuery); - return mysqlJdbcTemplate.queryForList(fetchQuery); - } - */ - private List> fetchExistingData( - List ids, - String tablename, - String primaryKeyColumn - ) { - - if (ids == null || ids.isEmpty()) { - return Collections.emptyList(); - } - - StringBuilder idListBuilder = new StringBuilder(); - - for (Object id : ids) { - if (id != null) { - if (idListBuilder.length() > 0) { - idListBuilder.append(", "); - } - idListBuilder.append(id.toString()); - } - } - - String fetchQuery = - "SELECT * FROM " + tablename + - " WHERE " + primaryKeyColumn + - " IN (" + idListBuilder.toString() + ")"; - - System.out.println(fetchQuery); - - return mysqlJdbcTemplate.queryForList(fetchQuery); - } - - private boolean compareAndPrint(Object existingPrimaryKeyValue, Object primaryKeyValue) { - Integer existingKey = (existingPrimaryKeyValue instanceof Integer) ? (Integer) existingPrimaryKeyValue : null; - Integer keyToCompare = (primaryKeyValue instanceof BigDecimal) ? ((BigDecimal) primaryKeyValue).intValue() : null; - - //System.out.println("Comparing existingPrimaryKeyValue: " + existingKey + " (" + (existingKey != null ? existingKey.getClass().getName() : "null") + ") with primaryKeyValue: " + keyToCompare + " (" + (keyToCompare != null ? keyToCompare.getClass().getName() : "null") + ")"); - - return Objects.equals(existingKey, keyToCompare); - } - - public void syncEgUserData() { - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EG_USER@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "id_user"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EG_USER@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); -*/ - List ids = new ArrayList(); - - for (Map row : rows) { - if (row.containsKey(primaryKeyColumn)) { - Object value = row.get(primaryKeyColumn); - if (value != null) { - ids.add(value); - } - } - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EG_USER",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EG_USER ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); -*/ - Map existingRow = null; - - for (Map eRow : existingRows) { - Object keyValue = eRow.get(primaryKeyColumn); - if (compareAndPrint(keyValue, primaryKeyValue)) { - existingRow = eRow; - break; // stop at first match - } - } - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - /* - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - */ - if (hasChanges) { - - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !"RNUM".equalsIgnoreCase(key)) { - - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(new Object[valueList.size()]); - - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - /*/ - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - */ - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !"RNUM".equalsIgnoreCase(key)) { - - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(new Object[valueList.size()]); - - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - - public void syncEgDepartmentData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EG_DEPARTMENT@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "ID_DEPT"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EG_DEPARTMENT@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - List ids = new ArrayList(); - - for (Map row : rows) { - Object id = row.get(primaryKeyColumn); - if (id != null) { - ids.add(id); - } - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EG_DEPARTMENT",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EG_DEPARTMENT ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - Map existingRow = null; - - // Find matching row - for (Map eRow : existingRows) { - if (compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) { - existingRow = eRow; - break; - } - } - - if (existingRow != null) { - System.out.println( - "Match found: primaryKeyValue: " + primaryKeyValue + - " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn) - ); - - boolean hasChanges = !row.equals(existingRow); - - if (hasChanges) { - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - - public void syncEgBoundaryData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EG_BOUNDARY@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "ID_BNDRY"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EG_BOUNDARY@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - List ids = new ArrayList(); - - for (Map row : rows) { - Object id = row.get(primaryKeyColumn); - if (id != null) { - ids.add(id); - } - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EG_BOUNDARY",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EG_BOUNDARY ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - - Map existingRow = null; - - /* -------- Find existing row (replace stream + filter + findFirst) -------- */ - for (Map eRow : existingRows) { - Object existingPk = eRow.get(primaryKeyColumn); - if (compareAndPrint(existingPk, primaryKeyValue)) { - existingRow = eRow; - break; - } - } - - if (existingRow != null) { - - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + - " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - - boolean hasChanges = !row.equals(existingRow); - - if (hasChanges) { - - /* -------- Build values array (replace stream + filter + map + toArray) -------- */ - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(); - - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - - } else { - - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - /* -------- Insert logic (same extraction) -------- */ - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(); - - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - - public void syncEggrComplaintStatusData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EGGR_COMPLAINTSTATUS@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "COMPLAINTSTATUSID"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTSTATUS@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - - List ids = new ArrayList(); - - for (Map row : rows) { - ids.add(row.get(primaryKeyColumn)); - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTSTATUS",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTSTATUS ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - - Map existingRow = null; - - // ---- findFirst() replacement ---- - for (Map eRow : existingRows) { - if (compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) { - existingRow = eRow; - break; // same as findFirst() - } - } - - if (existingRow != null) { - - System.out.println( - "Match found: primaryKeyValue: " + primaryKeyValue + - " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn) - ); - - boolean hasChanges = !row.equals(existingRow); - - if (hasChanges) { - - List valuesList = new ArrayList(); - - // ---- filter + map + toArray replacement ---- - for (Map.Entry entry : row.entrySet()) { - - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - - valuesList.add(entry.getValue()); - } - } - - Object[] values = valuesList.toArray(); - - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - - } else { - - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - List valuesList = new ArrayList(); - - // ---- filter + map + toArray replacement ---- - for (Map.Entry entry : row.entrySet()) { - - String key = entry.getKey(); - - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - - valuesList.add(entry.getValue()); - } - } - - Object[] values = valuesList.toArray(); - - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - - public void syncEggrComplaintTypesData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EGGR_COMPLAINTTYPES@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "COMPLAINTTYPEID"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTTYPES@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - - List ids = new ArrayList(); - - for (Map row : rows) { - if (row.containsKey(primaryKeyColumn)) { - ids.add(row.get(primaryKeyColumn)); - } - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTTYPES",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTTYPES ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - - Map existingRow = null; - - // Find matching row manually - for (Map eRow : existingRows) { - Object existingPk = eRow.get(primaryKeyColumn); - if (compareAndPrint(existingPk, primaryKeyValue)) { - existingRow = eRow; - break; - } - } - - if (existingRow != null) { - System.out.println( - "Match found: primaryKeyValue: " + primaryKeyValue + - " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn) - ); - - boolean hasChanges = !row.equals(existingRow); - - if (hasChanges) { - List valuesList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - valuesList.add(entry.getValue()); - } - } - - Object[] values = valuesList.toArray(new Object[valuesList.size()]); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - - System.out.println("Updated: " + primaryKeyValue); - } - - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - List valuesList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) - && !key.equalsIgnoreCase("RNUM")) { - valuesList.add(entry.getValue()); - } - } - - Object[] values = valuesList.toArray(new Object[valuesList.size()]); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - - System.out.println("Inserted: " + primaryKeyValue); - } - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - - public void syncEggrComplaintGroupData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EGGR_COMPLAINTGROUP@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "ID_COMPLAINTGROUP"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTGROUP@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - - List ids = new ArrayList(); - - for (Map row : rows) { - ids.add(row.get(primaryKeyColumn)); - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTGROUP",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTGROUP ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - - Map existingRow = null; - - for (Map eRow : existingRows) { - if (compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) { - existingRow = eRow; - break; - } - } - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + - " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - - boolean hasChanges = !row.equals(existingRow); - - if (hasChanges) { - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) && - !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - List valueList = new ArrayList(); - - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) && - !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - - Object[] values = valueList.toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - - public void syncEggrComplaintDetailsData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EGGR_COMPLAINTDETAILS@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "COMPLAINTID"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTDETAILS@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - List ids = new ArrayList(); - for (Map row : rows) { - ids.add(row.get(primaryKeyColumn)); - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTDETAILS",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTDETAILS ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - - // Find existing row - Map existingRow = null; - for (Map eRow : existingRows) { - if (compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) { - existingRow = eRow; - break; - } - } - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue - + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - // Prepare values excluding autoIncrementColumn and "RNUM" - List valuesList = new ArrayList(); - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) && !key.equalsIgnoreCase("RNUM")) { - valuesList.add(entry.getValue()); - } - } - Object[] values = valuesList.toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - // Prepare values excluding autoIncrementColumn and "RNUM" - List valuesList = new ArrayList(); - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) && !key.equalsIgnoreCase("RNUM")) { - valuesList.add(entry.getValue()); - } - } - Object[] values = valuesList.toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } - -public void syncEggrRedressalDetailsData() { - - int batchSize = 10000; - int totalRecords = getTotalRecordCount("EGGR_REDRESSALDETAILS@erp"); - int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up - - System.out.println("totalRecords : " + totalRecords + "\n" - + "totalBatches : " + totalBatches); - - String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different - String primaryKeyColumn = "REDRESSALID"; // Replace 'id_user' with the actual primary key column name if different - - for (int batch = 0; batch < totalBatches; batch++) { - int startRow = batch * batchSize; - int endRow = startRow + batchSize; - - long startTime = System.currentTimeMillis(); - List> rows = fetchBatch(startRow, endRow,"EGGR_REDRESSALDETAILS@erp"); - long endTime = System.currentTimeMillis(); - long queryTime = endTime - startTime; - System.out.println("Fetch Batch Time Taken: " + queryTime + " ms"); - - if (!rows.isEmpty()) { - // Extract primary keys from the fetched rows - /* - List ids = rows.stream() - .map(row -> row.get(primaryKeyColumn)) - .collect(Collectors.toList()); - */ - List ids = new ArrayList(); - for (Map row : rows) { - ids.add(row.get(primaryKeyColumn)); - } - - // Fetch existing data from MySQL - startTime = System.currentTimeMillis(); - List> existingRows = fetchExistingData(ids,"EGGR_REDRESSALDETAILS",primaryKeyColumn); - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms"); - - StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_REDRESSALDETAILS ("); - StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE "); - boolean first = true; - - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - updateQuery.append(", "); - } - first = false; - insertQuery.append(key); - updateQuery.append(key).append("=VALUES(").append(key).append(")"); - } - insertQuery.append(") VALUES ("); - first = true; - for (String key : rows.get(0).keySet()) { - if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) { - continue; // Skip the auto-increment column and RNUM - } - if (!first) { - insertQuery.append(", "); - } - first = false; - insertQuery.append("?"); - } - insertQuery.append(")").append(updateQuery.toString()); - - startTime = System.currentTimeMillis(); - for (Map row : rows) { - Object primaryKeyValue = row.get(primaryKeyColumn); - - // Filter to find if there is any existing row with the same primary key value - /* - Map existingRow = existingRows.stream() - .filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) - .findFirst() - .orElse(null); - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - if (hasChanges) { - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - Object[] values = row.entrySet().stream() - .filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM")) - .map(Map.Entry::getValue) - .toArray(); - mysqlJdbcTemplate.update(insertQuery.toString(), values); - System.out.println("Inserted: " + primaryKeyValue); - } - */ - Map existingRow = null; - for (Map eRow : existingRows) { - if (compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue)) { - existingRow = eRow; - break; - } - } - - if (existingRow != null) { - System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + - " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn)); - boolean hasChanges = !row.equals(existingRow); - - if (hasChanges) { - List valueList = new ArrayList(); - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) && !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - mysqlJdbcTemplate.update(insertQuery.toString(), valueList.toArray()); - System.out.println("Updated: " + primaryKeyValue); - } - } else { - System.out.println("No match found: primaryKeyValue: " + primaryKeyValue); - - List valueList = new ArrayList(); - for (Map.Entry entry : row.entrySet()) { - String key = entry.getKey(); - if (!key.equalsIgnoreCase(autoIncrementColumn) && !key.equalsIgnoreCase("RNUM")) { - valueList.add(entry.getValue()); - } - } - mysqlJdbcTemplate.update(insertQuery.toString(), valueList.toArray()); - System.out.println("Inserted: " + primaryKeyValue); - } - } - endTime = System.currentTimeMillis(); - queryTime = endTime - startTime; - System.out.println("Insert/Update Time Taken: " + queryTime + " ms"); - - System.out.println("Batch " + (batch+1) + " Completed\n"); - } - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/PGRCommon.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/PGRCommon.java deleted file mode 100644 index d1154f8e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/PGRCommon.java +++ /dev/null @@ -1,486 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class PGRCommon { - private JdbcTemplate jdbcTemplate; - private JdbcTemplate jdbcPGRTemplate; - - @Autowired - public void setDataSource(@Qualifier("oracleDataSource") DataSource dataSource,@Qualifier("mysqlPGRMasterDataSource") DataSource pgrDataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.jdbcPGRTemplate = new JdbcTemplate(pgrDataSource); - } - - @Transactional - public List> getDeaprtmentList() { - - String SqlQuery = ""; - - SqlQuery="SELECT Distinct id_dept,dept_name " - + "FROM EG_DEPARTMENT@ERP " - + "WHERE NVL(dept_name, '0') NOT LIKE 'F%' AND dept_name IS NOT NULL " - + "ORDER BY id_dept"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneList() { - - String SqlQuery = ""; - - SqlQuery="SELECT Distinct id_dept,dept_name " - + "FROM EG_DEPARTMENT@ERP " - + "WHERE NVL(dept_name, '0') NOT LIKE 'F%' AND dept_name IS NOT NULL AND (id_dept >= 32 AND id_dept <= 46)" - + "ORDER BY id_dept"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getPendingComplanitCount() { - - String SqlQuery = ""; - - SqlQuery = "SELECT c.dept_name, a.deptid, a.days_90, a.days_90_pen, a.days_90_reopen, " - + "a.days_61_90, a.days_61_90_pen, a.days_61_90_reopen, " - + "a.days_31_60, a.days_31_60_pen, a.days_31_60_reopen, " - + "a.days_16_30, a.days_16_30_pen, a.days_16_30_reopen, " - + "a.days_0_15, a.days_0_15_pen, a.days_0_15_reopen, " - + "a.Total, a.Total_pen, a.Total_reopen " - + "FROM ( " - + "SELECT " - + "a.deptid, " - + "nvl(sum(case when sysdate - a.complaintdate > 90 then 1 end), '0') AS days_90, " - + "nvl(sum(case when sysdate - a.complaintdate > 90 AND b.COMPLAINTSTATUSID IN (2, 3, 4) then 1 end), '0') AS days_90_pen, " - + "nvl(sum(case when sysdate - a.complaintdate > 90 AND b.COMPLAINTSTATUSID IN (9) then 1 end), '0') AS days_90_reopen, " - + "nvl(sum(case when sysdate - a.complaintdate > 60 AND sysdate - a.complaintdate <= 90 then 1 end), '0') AS days_61_90, " - + "nvl(sum(case when sysdate - a.complaintdate > 60 AND sysdate - a.complaintdate <= 90 AND b.COMPLAINTSTATUSID IN (2, 3, 4) then 1 end), '0') AS days_61_90_pen, " - + "nvl(sum(case when sysdate - a.complaintdate > 60 AND sysdate - a.complaintdate <= 90 AND b.COMPLAINTSTATUSID IN (9) then 1 end), '0') AS days_61_90_reopen, " - + "nvl(sum(case when sysdate - a.complaintdate > 30 AND sysdate - a.complaintdate <= 60 then 1 end), '0') AS days_31_60, " - + "nvl(sum(case when sysdate - a.complaintdate > 30 AND sysdate - a.complaintdate <= 60 AND b.COMPLAINTSTATUSID IN (2, 3, 4) then 1 end), '0') AS days_31_60_pen, " - + "nvl(sum(case when sysdate - a.complaintdate > 30 AND sysdate - a.complaintdate <= 60 AND b.COMPLAINTSTATUSID IN (9) then 1 end), '0') AS days_31_60_reopen, " - + "nvl(sum(case when sysdate - a.complaintdate > 15 AND sysdate - a.complaintdate <= 30 then 1 end), '0') AS days_16_30, " - + "nvl(sum(case when sysdate - a.complaintdate > 15 AND sysdate - a.complaintdate <= 30 AND b.COMPLAINTSTATUSID IN (2, 3, 4) then 1 end), '0') AS days_16_30_pen, " - + "nvl(sum(case when sysdate - a.complaintdate > 15 AND sysdate - a.complaintdate <= 30 AND b.COMPLAINTSTATUSID IN (9) then 1 end), '0') AS days_16_30_reopen, " - + "nvl(sum(case when sysdate - a.complaintdate > 0 AND sysdate - a.complaintdate <= 15 then 1 end), '0') AS days_0_15, " - + "nvl(sum(case when sysdate - a.complaintdate > 0 AND sysdate - a.complaintdate <= 15 AND b.COMPLAINTSTATUSID IN (2, 3, 4) then 1 end), '0') AS days_0_15_pen, " - + "nvl(sum(case when sysdate - a.complaintdate > 0 AND sysdate - a.complaintdate <= 15 AND b.COMPLAINTSTATUSID IN (9) then 1 end), '0') AS days_0_15_reopen, " - + "nvl(count(*), '0') AS Total, " - + "nvl(count(case when b.COMPLAINTSTATUSID IN (2, 3, 4) then 1 end), '0') AS Total_pen, " - + "nvl(count(case when b.COMPLAINTSTATUSID IN (9) then 1 end), '0') AS Total_reopen " - + "FROM eggr_complaintdetails@erp a, eggr_redressaldetails@erp b " - + "WHERE a.complaintid = b.complaintid "; - //25-oct-2010 - SqlQuery += " AND (a.complaintdate >= '01-apr-2009' AND a.complaintdate < '01-apr-2009') GROUP BY a.deptid) a, EG_DEPARTMENT@ERP c " - + "WHERE a.deptid = c.id_dept AND (NVL(DEPT_NAME, 0) NOT LIKE 'F%' AND DEPT_NAME IS NOT NULL)"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWisePendingComplanitCount() { - - String SqlQuery = ""; - - SqlQuery = "SELECT deptid, DEPT_NAME" - + ", NVL(SUM(CASE WHEN complainttype IN (52,146) THEN 1 END), 0) AS NonBURSTLT" - + ", NVL(SUM(CASE WHEN complainttype IN (1,97) THEN 1 END), 0) AS REOFGAR" - + ", NVL(SUM(CASE WHEN complainttype IN (22,32,57,59,70,113,114,130,145) THEN 1 END), 0) AS ROAD" - + ", NVL(SUM(CASE WHEN complainttype IN (18,118) THEN 1 END), 0) AS MOSQUITE" - + ", NVL(SUM(CASE WHEN complainttype IN (69,138) THEN 1 END), 0) AS WATER" - + ", NVL(SUM(CASE WHEN complainttype IN (7,99) THEN 1 END), 0) AS REOFDEB" - + ", NVL(SUM(CASE WHEN complainttype IN (71,152) THEN 1 END), 0) AS TREE" - + ", NVL(SUM(CASE WHEN complainttype IN (19,119) THEN 1 END), 0) AS DOGS" - + ", NVL(SUM(CASE WHEN complainttype IN (75,181) THEN 1 END), 0) AS ENCMTN" - + ", NVL(SUM(CASE WHEN complainttype IN (58,112) THEN 1 END), 0) AS POT" - + ", NVL(SUM(CASE WHEN complainttype IN (43,166) THEN 1 END), 0) AS PTAX" - + ", NVL(SUM(CASE WHEN complainttype NOT IN (52,146,1,97,22,32,57,59,70,113,114,130,145,18,118,69,138,7,99,71,152,19,119,75,181,58,112,43,166) THEN 1 END), 0) AS OTHERS" - + ", COUNT(*) AS Total FROM " - + " eggr_complaintdetails@erp a " - + ", eggr_redressaldetails@erp b " - + ", EG_DEPARTMENT@ERP c " - + "WHERE a.complaintdate >= '01-apr-2009' " - + "AND a.complaintid = b.complaintid " - + "AND b.COMPLAINTSTATUSID IN (2,3,4,9) " - + "AND a.deptid = c.id_dept " - + "AND (NVL(DEPT_NAME, 0) NOT LIKE 'F%' " - + "AND DEPT_NAME IS NOT NULL) " - + "GROUP BY a.deptid,c.DEPT_NAME ORDER BY a.deptid"; - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWiseReopenComplanitCount() { - - String SqlQuery = ""; - - SqlQuery = "SELECT deptid, DEPT_NAME" - + ", NVL(SUM(CASE WHEN complainttype IN (52,146) THEN 1 END), 0) AS NonBURSTLT" - + ", NVL(SUM(CASE WHEN complainttype IN (1,97) THEN 1 END), 0) AS REOFGAR" - + ", NVL(SUM(CASE WHEN complainttype IN (22,32,57,59,70,113,114,130,145) THEN 1 END), 0) AS ROAD" - + ", NVL(SUM(CASE WHEN complainttype IN (18,118) THEN 1 END), 0) AS MOSQUITE" - + ", NVL(SUM(CASE WHEN complainttype IN (69,138) THEN 1 END), 0) AS WATER" - + ", NVL(SUM(CASE WHEN complainttype IN (7,99) THEN 1 END), 0) AS REOFDEB" - + ", NVL(SUM(CASE WHEN complainttype IN (71,152) THEN 1 END), 0) AS TREE" - + ", NVL(SUM(CASE WHEN complainttype IN (19,119) THEN 1 END), 0) AS DOGS" - + ", NVL(SUM(CASE WHEN complainttype IN (75,181) THEN 1 END), 0) AS ENCMTN" - + ", NVL(SUM(CASE WHEN complainttype IN (58,112) THEN 1 END), 0) AS POT" - + ", NVL(SUM(CASE WHEN complainttype IN (43,166) THEN 1 END), 0) AS PTAX" - + ", NVL(SUM(CASE WHEN complainttype NOT IN (52,146,1,97,22,32,57,59,70,113,114,130,145,18,118,69,138,7,99,71,152,19,119,75,181,58,112,43,166) THEN 1 END), 0) AS OTHERS" - + ", COUNT(*) AS Total FROM " - + "eggr_complaintdetails@erp a" - + ", eggr_redressaldetails@erp b" - + ", EG_DEPARTMENT@ERP c " - + "WHERE a.complaintdate >= '01-apr-2009' " - + "AND a.complaintid = b.complaintid " - + "AND b.COMPLAINTSTATUSID IN (9) " - + "AND a.deptid = c.id_dept " - + "AND (NVL(DEPT_NAME, 0) NOT LIKE 'F%' " - + "AND DEPT_NAME IS NOT NULL) " - + "GROUP BY a.deptid,c.DEPT_NAME ORDER BY a.deptid"; - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getComplaintsList() { - - String SqlQuery = ""; - - SqlQuery ="SELECT z.name AS zone_name, " - + " dn.name AS division_name, " - + " location.name AS location, " - + " d.dept_name, " - + " TO_CHAR(cd.complaintdate, 'dd-mm-yyyy') AS COMPDATE, " - + " TO_CHAR(cd.complaintdate, 'HH24:MI:SS') AS Time, " - + " cs.statusname AS status, " - + " usr.user_name, " - + " cd.complaintnumber, " - + " cd.ID_MODE AS \"MODE\", " - + " COALESCE(ct.complainttypename, 'Unspecified') AS complainttypename, " - + " cg.complaintgroupname " - + "FROM eggr_complaintdetails@erp cd " - + "INNER JOIN eggr_redressaldetails@erp rd ON cd.complaintid = rd.complaintid " - + "INNER JOIN eggr_complaintstatus@erp cs ON rd.complaintstatusid = cs.complaintstatusid " - + "INNER JOIN eggr_complainttypes@erp ct ON TRIM(cd.complainttype) = ct.complainttypeid " - + "INNER JOIN eg_user@erp usr ON rd.redressalofficerid = usr.id_user " - + "INNER JOIN eg_department@erp d ON cd.deptid = d.id_dept " - + "INNER JOIN eggr_complaintgroup@erp cg ON cg.id_complaintgroup = ct.complaintgroup_id " - + "INNER JOIN eg_boundary@erp dn ON dn.id_bndry = cd.bndry " - + "INNER JOIN eg_boundary@erp z ON dn.parent = z.id_bndry " - + "INNER JOIN eg_boundary@ERP location ON location.id_bndry = cd.locbndryid " - + "WHERE (cd.deptid IS NULL OR (cd.deptid < 21 OR cd.deptid > 30)) " - + " AND cd.complaintdate >= TO_DATE('2024-02-23', 'yyyy-MM-dd') " - + " AND cd.complaintdate < (TO_DATE('2024-02-23', 'yyyy-MM-dd') + 1) " - + "ORDER BY zone_name, division_name, cd.complaintdate" - + ""; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getQaQcList() { - - String SqlQuery = ""; - - SqlQuery ="select cd.COMPLAINTNUMBER, " - + "dep.DEPT_NAME,ct.COMPLAINTTYPENAME, " - + "TO_CHAR(cd.COMPLAINTDATE,'DD-MM-RRRR') COMPLAINTDATE, " - + "TO_CHAR(cd.COMPLAINTDATE,'HH:MI:SS AM') COMPLAINTTIME, " - + "cd.COMPLAINTDETAILS,cd.COMPLAINANTFIRSTNAME, " - + "cd.MOBILENUMBER AS COMPLAINANTMOBILENUMBER, usr.USER_NAME, usr.extrafield2 as Mobile_number, " - + "TO_CHAR(c.compl_date,'DD-MM-RRRR HH:MI:SS AM') as COMPLAINTCOMPLETIONDATE, DECODE ( qa.STATUS,null,'Not Attended','Attended') STATUS " - + "from EGGR_COMPLAINTDETAILS@erp cd , " - + "eg_department@erp dep, " - + "EGGR_COMPLAINTTYPES@erp ct, " - + "eg_user@erp usr, " - + "eggr_qams_store@erp qa, " - + "EGGR_REDRESSALDETAILS@erp rd, " - + "(SELECT c.redressalid, MAX(c.TIMESTAMP) compl_date " - + "FROM eggr_status_tracker@erp c,eggr_redressaldetails@ERP d " - + "WHERE c.statusid in(5,10) " - + "AND TRUNC(c.TIMESTAMP) between TO_DATE('2024-02-23', 'yyyy-MM-dd') and TO_DATE('2024-02-24', 'yyyy-MM-dd') " - + "AND d.COMPLAINTSTATUSID in(5,10) " - + "AND d.REDRESSALID=c.redressalid " - + "GROUP BY c.redressalid) c " - + "where cd.DEPTID=dep.ID_DEPT " - + "and cd.COMPLAINTTYPE=ct.COMPLAINTTYPEID " - + "AND rd.COMPLAINTID =cd.COMPLAINTID " - + "AND rd.REDRESSALOFFICERID =usr.id_user " - + "and qa.FDBK_OBJ_REF =cd.COMPLAINTID(+) " - + "and rd.COMPLAINTSTATUSID not in(2,3,4,9) and rd.redressalid=c.redressalid(+) and " - + "TRUNC(cd.COMPLAINTDATE) between TO_DATE('2024-02-23', 'yyyy-MM-dd') and TO_DATE('2024-02-24', 'yyyy-MM-dd') " - + "order by dept_name"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWiseComplaintCountList() { - - String SqlQuery = ""; - - SqlQuery ="select * from (SELECT deptid , " - + "nvl(sum( case when complainttype in (52,146) then 1 end),0) as \"NonBURSTLT\" , " - + "nvl(sum( case when complainttype in (1,97) then 1 end),0) as \"REOFGAR\" ," - + "nvl(sum( case when complainttype in (22,32,57,59,70,113,114,130,145) then 1 end),0) as \"ROAD\" ," - + "nvl(sum( case when complainttype in (18,118) then 1 end),0) as \"MOSQUITE\" , " - + "nvl(sum( case when complainttype in (69,138) then 1 end),0) as \"WATER\" , " - + "nvl(sum( case when complainttype in (7,99) then 1 end),0) as \"REOFDEB\" ," - + "nvl(sum( case when complainttype in (71,152) then 1 end),0) as \"TREE\" , " - + "nvl(sum( case when complainttype in (19,119) then 1 end),0) as \"DOGS\" , " - + "nvl(sum( case when complainttype in (75,181) then 1 end),0) as \"ENCMTN\" ," - + "nvl(sum( case when complainttype in (58,112) then 1 end),0) as \"POT\" , " - + "nvl(sum( case when complainttype in (43,166) then 1 end),0) as \"PTAX\" , " - + "nvl(sum( case when complainttype not in (52,1,22,32,57,59,70,18,69,7,71,19,75,58,43,146,97,113,114,130,145,118,138,99,152,119,181,112,166) then 1 end),0) as \"OTHERS\" , " - + "COUNT(*) Total FROM eggr_complaintdetails@erp a, eggr_redressaldetails@erp b " - + "WHERE a.complaintid=b.complaintid " - + "and b.COMPLAINTSTATUSID IN(2,3,4,9) " - + "group by a.deptid ) a " - + "inner join EG_DEPARTMENT@ERP c on a.deptid=c.id_dept " - + "left outer join ( SELECT deptid , " - + "nvl(sum( case when sysdate-complaintdate>90 and b.COMPLAINTSTATUSID IN(2,3,4,9) then 1 end),'0') as days_90_pen , " - + "nvl(sum( case when sysdate-complaintdate>60 and sysdate-complaintdate<=90 and b.COMPLAINTSTATUSID IN(2,3,4,9) then 1 end),'0') as days_61_90_pen ," - + "nvl(sum( case when sysdate-complaintdate>30 and sysdate-complaintdate<=60 and b.COMPLAINTSTATUSID IN(2,3,4,9) then 1 end),'0') as days_31_60_pen , " - + "nvl(sum( case when sysdate-complaintdate>15 and sysdate-complaintdate<=30 and b.COMPLAINTSTATUSID IN(2,3,4,9) then 1 end),'0') as days_16_30_pen , " - + "nvl(sum( case when sysdate-complaintdate<=15 and b.COMPLAINTSTATUSID IN(2,3,4,9) then 1 end),'0') as days_0_15_pen , " - + "nvl(count(case when b.COMPLAINTSTATUSID IN(2,3,4,9) then 1 end),'0') as Total_pen " - + "FROM eggr_complaintdetails@erp a, eggr_redressaldetails@erp b " - + " WHERE a.complaintid=b.complaintid " - + "AND EXISTS (SELECT 1 FROM EG_DEPARTMENT@ERP c " - + "WHERE a.deptid = c.id_dept " - + "AND (NVL(c.id_dept, 0) NOT LIKE 'F%' " - + "AND c.id_dept IS NOT NULL)) group by a.deptid ) d on d.deptid=c.id_dept " - + "where (NVL(DEPT_NAME,0) NOT LIKE 'F%' AND DEPT_NAME IS NOT NULL) AND (a.deptid>=32 AND a.deptid<=46)" - + "order by a.deptid"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWiseOfficerComplaintCountList(String deptid, String complainttype) { - - String SqlQuery = ""; - String where_1=""; - if(!complainttype.equals("all")) { - where_1 = "and cd.complainttype in ("+complainttype+") "; - } - - SqlQuery ="Select c.dept_name,a.iduser,a.user_name,nvl(b.extrafield2,' ') MOBILENO,a.nos,a.deptid from " - + "(SELECT cd.deptid, u.user_name, COUNT (cd.complaintid) nos, max(u.id_user) iduser " - + "FROM eggr_complaintdetails@erp cd, eggr_redressaldetails@erp rd, eg_user@erp u " - + "WHERE cd.complaintid = rd.complaintid " - + "AND rd.redressalofficerid = u.id_user and complaintdate >= '25-oct-2010' " - + "and rd.COMPLAINTSTATUSID IN(2,3,4,9) " - + where_1 +"" - + "AND cd.deptid = "+deptid+" " - + "GROUP BY cd.deptid, u.user_name " - + "ORDER BY cd.deptid,u.user_name) a , eg_user@erp b,eg_department@erp c " - + "where a.deptid="+deptid+" AND(a.deptid=c.id_dept(+) and a.user_name=b.user_name ) " - + "order by c.dept_name,a.user_name"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWiseOfficerComplaintList(String deptid, String complainttype, String redressalofficerid) { - - String SqlQuery = ""; - String where_1=""; - if(!complainttype.equals("all")) { - where_1 = "and a.complainttype in ("+complainttype+") "; - } - - SqlQuery ="SELECT a.*, NVL(TO_CHAR(a.complaintdate, 'dd-mm-rrrr'), ' ') compdate,c.DEPT_NAME, u.user_name, ct.COMPLAINTTYPEName " - + "FROM eggr_complaintdetails@erp a, " - + "EG_DEPARTMENT@ERP c, " - + "eggr_redressaldetails@erp b, " - + "eg_user@erp u, " - + "EGGR_COMPLAINTTYPES@erp ct " - + "WHERE a.deptid = c.id_dept " - + "AND a.complainttype = ct.COMPLAINTTYPEID " - + "AND (NVL(DEPT_NAME, '0') NOT LIKE 'F%' AND DEPT_NAME IS NOT NULL) AND a.complaintid = b.complaintid " - + "AND complaintdate >= TO_DATE('25-Oct-2010', 'DD-Mon-YYYY') " - + "AND u.id_user = b.redressalofficerid " - + "AND b.COMPLAINTSTATUSID IN (2, 3, 4, 9) " - + where_1 +"" - + "AND a.deptid = "+deptid+" " - + "AND b.redressalofficerid = "+redressalofficerid+" " - + "ORDER BY user_name, a.complaintdate"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - - @Transactional - public List> getZoneWiseWithoutReopenComplaintCountList() { - - String SqlQuery = ""; - - SqlQuery ="select * from (SELECT deptid , " - + "nvl(sum( case when complainttype in (52,146) then 1 end),0) as \"NonBURSTLT\" , " - + "nvl(sum( case when complainttype in (1,97) then 1 end),0) as \"REOFGAR\" ," - + "nvl(sum( case when complainttype in (22,32,57,59,70,113,114,130,145) then 1 end),0) as \"ROAD\" ," - + "nvl(sum( case when complainttype in (18,118) then 1 end),0) as \"MOSQUITE\" , " - + "nvl(sum( case when complainttype in (69,138) then 1 end),0) as \"WATER\" , " - + "nvl(sum( case when complainttype in (7,99) then 1 end),0) as \"REOFDEB\" ," - + "nvl(sum( case when complainttype in (71,152) then 1 end),0) as \"TREE\" , " - + "nvl(sum( case when complainttype in (19,119) then 1 end),0) as \"DOGS\" , " - + "nvl(sum( case when complainttype in (75,181) then 1 end),0) as \"ENCMTN\" ," - + "nvl(sum( case when complainttype in (58,112) then 1 end),0) as \"POT\" , " - + "nvl(sum( case when complainttype in (43,166) then 1 end),0) as \"PTAX\" , " - + "nvl(sum( case when complainttype not in (52,1,22,32,57,59,70,18,69,7,71,19,75,58,43,146,97,113,114,130,145,118,138,99,152,119,181,112,166) then 1 end),0) as \"OTHERS\" , " - + "COUNT(*) Total FROM eggr_complaintdetails@erp a, eggr_redressaldetails@erp b " - + "WHERE a.complaintid=b.complaintid " - + "and b.COMPLAINTSTATUSID IN(2,3,4) " - + "group by a.deptid ) a " - + "inner join EG_DEPARTMENT@ERP c on a.deptid=c.id_dept " - + "left outer join ( SELECT deptid , " - + "nvl(sum( case when sysdate-complaintdate>90 and b.COMPLAINTSTATUSID IN(2,3,4) then 1 end),'0') as days_90_pen , " - + "nvl(sum( case when sysdate-complaintdate>60 and sysdate-complaintdate<=90 and b.COMPLAINTSTATUSID IN(2,3,4) then 1 end),'0') as days_61_90_pen ," - + "nvl(sum( case when sysdate-complaintdate>30 and sysdate-complaintdate<=60 and b.COMPLAINTSTATUSID IN(2,3,4) then 1 end),'0') as days_31_60_pen , " - + "nvl(sum( case when sysdate-complaintdate>15 and sysdate-complaintdate<=30 and b.COMPLAINTSTATUSID IN(2,3,4) then 1 end),'0') as days_16_30_pen , " - + "nvl(sum( case when sysdate-complaintdate<=15 and b.COMPLAINTSTATUSID IN(2,3,4) then 1 end),'0') as days_0_15_pen , " - + "nvl(count(case when b.COMPLAINTSTATUSID IN(2,3,4) then 1 end),'0') as Total_pen " - + "FROM eggr_complaintdetails@erp a, eggr_redressaldetails@erp b " - + " WHERE a.complaintid=b.complaintid " - + "AND EXISTS (SELECT 1 FROM EG_DEPARTMENT@ERP c " - + "WHERE a.deptid = c.id_dept " - + "AND (NVL(c.id_dept, 0) NOT LIKE 'F%' " - + "AND c.id_dept IS NOT NULL)) group by a.deptid ) d on d.deptid=c.id_dept " - + "where (NVL(DEPT_NAME,0) NOT LIKE 'F%' AND DEPT_NAME IS NOT NULL) AND (a.deptid>=32 AND a.deptid<=46)" - + "order by a.deptid"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWiseOfficerWithoutReopenComplaintCountList(String deptid, String complainttype) { - - String SqlQuery = ""; - String where_1=""; - if(!complainttype.equals("all")) { - where_1 = "and cd.complainttype in ("+complainttype+") "; - } - - SqlQuery ="Select c.dept_name,a.iduser,a.user_name,nvl(b.extrafield2,' ') MOBILENO,a.nos,a.deptid from " - + "(SELECT cd.deptid, u.user_name, COUNT (cd.complaintid) nos, max(u.id_user) iduser " - + "FROM eggr_complaintdetails@erp cd, eggr_redressaldetails@erp rd, eg_user@erp u " - + "WHERE cd.complaintid = rd.complaintid " - + "AND rd.redressalofficerid = u.id_user and complaintdate >= '25-oct-2010' " - + "and rd.COMPLAINTSTATUSID IN(2,3,4) " - + where_1 +"" - + "AND cd.deptid = "+deptid+" " - + "GROUP BY cd.deptid, u.user_name " - + "ORDER BY cd.deptid,u.user_name) a , eg_user@erp b,eg_department@erp c " - + "where a.deptid="+deptid+" AND(a.deptid=c.id_dept(+) and a.user_name=b.user_name ) " - + "order by c.dept_name,a.user_name"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - return result; - } - - @Transactional - public List> getZoneWiseOfficerWithoutReopenComplaintList(String deptid, String complainttype, String redressalofficerid) { - - String SqlQuery = ""; - String where_1=""; - if(!complainttype.equals("all")) { - where_1 = "and a.complainttype in ("+complainttype+") "; - } - - SqlQuery ="SELECT a.*, NVL(TO_CHAR(a.complaintdate, 'dd-mm-rrrr'), ' ') compdate,c.DEPT_NAME, u.user_name, ct.COMPLAINTTYPEName " - + "FROM eggr_complaintdetails@erp a, " - + "EG_DEPARTMENT@ERP c, " - + "eggr_redressaldetails@erp b, " - + "eg_user@erp u, " - + "EGGR_COMPLAINTTYPES@erp ct " - + "WHERE a.deptid = c.id_dept " - + "AND a.complainttype = ct.COMPLAINTTYPEID " - + "AND (NVL(DEPT_NAME, '0') NOT LIKE 'F%' AND DEPT_NAME IS NOT NULL) AND a.complaintid = b.complaintid " - + "AND complaintdate >= TO_DATE('25-Oct-2010', 'DD-Mon-YYYY') " - + "AND u.id_user = b.redressalofficerid " - + "AND b.COMPLAINTSTATUSID IN (2, 3, 4) " - + where_1 +"" - + "AND a.deptid = "+deptid+" " - + "AND b.redressalofficerid = "+redressalofficerid+" " - + "ORDER BY user_name, a.complaintdate"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional - public List> getComplaintDetails(String complaintNumber) { - - String SqlQuery = ""; - - SqlQuery ="SELECT a.*, NVL(TO_CHAR(a.complaintdate, 'dd-mm-rrrr'), ' ') compdate,c.DEPT_NAME, u.user_name, ct.COMPLAINTTYPEName " - + "FROM eggr_complaintdetails@erp a, " - + "EG_DEPARTMENT@ERP c, " - + "eggr_redressaldetails@erp b, " - + "eg_user@erp u, " - + "EGGR_COMPLAINTTYPES@erp ct " - + "WHERE a.deptid = c.id_dept " - + "AND a.complainttype = ct.COMPLAINTTYPEID " - + "AND (NVL(DEPT_NAME, '0') NOT LIKE 'F%' AND DEPT_NAME IS NOT NULL) AND a.complaintid = b.complaintid " - + "AND complaintdate >= TO_DATE('25-Oct-2010', 'DD-Mon-YYYY') " - + "AND u.id_user = b.redressalofficerid " - + "AND a.COMPLAINTNUMBER = '"+complaintNumber+"' " - + "ORDER BY user_name, a.complaintdate"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - // Iterate over the result list - for (Map row : result) { - // Iterate over each key-value pair in the map - for (Map.Entry entry : row.entrySet()) { - // Check if the value is null - if (entry.getValue() == null) { - // If the value is null, replace it with an empty string - entry.setValue(""); - } - } - } - - return result; - } - - - @Transactional - public List> syncERPtoLocal() { - - String SqlQuery = ""; - - SqlQuery ="SELECT count(cd.complaintid) total FROM eggr_complaintdetails@erp cd"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - //List> result = jdbcPGRTemplate.queryForList(SqlQuery); - return result; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/package-info.java deleted file mode 100644 index b928b6f3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/pgr/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.pgr.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/controller/APIController.java deleted file mode 100644 index 6ba44012..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/controller/APIController.java +++ /dev/null @@ -1,209 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; - -@RequestMapping("/gcc/api/qrfeedback") -@RestController("qrassetfeedbackcontroller") -public class APIController { - private final RestTemplate restTemplate; - private final AppConfig appConfig; - String bodyMessage = ""; - - @Autowired - public APIController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - @GetMapping(value = "/getFeedbackAssetdetails") - public String getFeedbackAssetdetails(@RequestParam String fbId) { - String feedbackId = fbId; - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/feedback/{feedbackId}",String.class,feedbackId); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - @GetMapping(value = "/getFeedbackData") - public String getFeedbackData(@RequestParam String fbId) { - String feedbackId = fbId; - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/feedback/data/{feedbackId}",String.class,feedbackId); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - @GetMapping(value = "/dashboard-summary") - public String getDashboardSummary() { - System.out.print("hi dashboard-summary"); - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/dashboard-summary",String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @PostMapping(value = "/category/checkbyname") - public int checkByName(@RequestParam("catName") String catName) { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("catName", catName); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback + "/api/category/checkbyname", request, Integer.class); - - return response.getBody(); - } - - @PostMapping(value = "/category/edit/checkbyname") - public int editCheckByName(@RequestParam("catName") String catName,@RequestParam("cId") String cId) { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("catName", catName); - params.add("cId", cId); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback + "/api/category/edit/checkbyname", request, Integer.class); - - return response.getBody(); - } - - @PostMapping(value = "/category/{id}") - public String getCategoryById(@PathVariable("id") int id) { - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/category/"+id,String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @PostMapping(value = "/saveCategory") - public int saveCategory(@RequestParam("catName") String catName, @RequestParam("isActive") String isActive) { - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("catName", catName); - params.add("isActive", isActive); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback + "/api/category/save", request, Integer.class); - - return response.getBody(); - } - - @PostMapping(value = "/updateCategory") - public int updateCategory(@RequestParam("catName") String catName, @RequestParam("isActive") String isActive, @RequestParam("cId") String cId) { - //System.out.println(cId); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("catName", catName); - params.add("isActive", isActive); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback + "/api/category/"+cId+"/update", request, Integer.class); - - return response.getBody(); - } - - @GetMapping("/category/{id}/delete") - public String deleteCategory(@PathVariable("id") int id) { - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/category/{id}/delete",String.class,id); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - - @PostMapping(value = "/category/question/{id}") - public String getCategoryQuestionById(@PathVariable("id") int id) { - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/category/question/"+id,String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @GetMapping("/category/question/{id}/delete") - public String deleteCategoryQuestion(@PathVariable("id") int id) { - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/category/question/{id}/delete",String.class,id); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - - @PostMapping(value = "/saveCategoryQuestion") - public int saveCategoryQuestion(@RequestParam("assetCategory") String assetCategory,@RequestParam("engQuestion") String engQuestion,@RequestParam("tamilQuestion") String tamilQuestion, @RequestParam("isActive") String isActive) { - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("assetCategory", assetCategory); - params.add("engQuestion", engQuestion); - params.add("tamilQuestion", tamilQuestion); - params.add("isActive", isActive); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback + "/api/category/question/save", request, Integer.class); - - return response.getBody(); - } - - @PostMapping(value = "/updateCategoryQuestion") - public int updateCategoryQuestion(@RequestParam("cmqId") String cmqId,@RequestParam("assetCategory") String assetCategory,@RequestParam("engQuestion") String engQuestion,@RequestParam("tamilQuestion") String tamilQuestion, @RequestParam("isActive") String isActive) { - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("assetCategory", assetCategory); - params.add("engQuestion", engQuestion); - params.add("tamilQuestion", tamilQuestion); - params.add("isActive", isActive); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback + "/api/category/question/"+cmqId+"/update", request, Integer.class); - - return response.getBody(); - } - - @GetMapping(value = "/getComplaintCategory") - public String getComplaintCategory() { - ResponseEntity response = restTemplate.getForEntity(appConfig.qrAssetFeedback+"/api/getComplaintCategory",String.class); - bodyMessage = response.getBody().trim(); - return bodyMessage; - } - @PostMapping(value = "/getComplaintCategoryById") - public String getComplaintCategoryById(@RequestParam String comGroupId) { - - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - - MultiValueMap params = new LinkedMultiValueMap<>(); - params.add("comGroupId", comGroupId); - - HttpEntity> request = new HttpEntity<>(params, headers); - - ResponseEntity response = restTemplate.postForEntity(appConfig.qrAssetFeedback+"/api/getComplaintCategoryById",request,String.class); - bodyMessage = response.getBody().trim(); - - return bodyMessage; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/controller/MainController.java deleted file mode 100644 index 7b2b19e9..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/controller/MainController.java +++ /dev/null @@ -1,127 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.controller; - -import java.util.Arrays; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Asset; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategory; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategoryQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameter; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameterQuestions; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Feedback; - -@RequestMapping("/gcc/qrfeedback") -@Controller("qrAssetFeedbackController") -public class MainController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return "modules/qrfeedback/index"; - } - - @GetMapping("/master/asset-category") - public String category(Model model) { - - String apiUrl = appConfig.qrAssetFeedback + "/api/category"; - AssetCategory[] assetCategoryList = restTemplate.getForObject(apiUrl, AssetCategory[].class); - - model.addAttribute("assetcategorylist",assetCategoryList); - model.addAttribute("qrAssetFeedbackApiUrl",appConfig.qrAssetFeedback); - return "modules/qrfeedback/master/asset-category"; - } - - @GetMapping("/master/asset-category-questions") - public String categoryQuestions(Model model) { - String apiUrl = appConfig.qrAssetFeedback + "/api/category"; - AssetCategory[] assetCategoryList = restTemplate.getForObject(apiUrl, AssetCategory[].class); - - model.addAttribute("assetcategorylist",assetCategoryList); - - apiUrl = appConfig.qrAssetFeedback + "/api/category/question"; - AssetCategoryQuestion[] assetCategoryQuestionList = restTemplate.getForObject(apiUrl, AssetCategoryQuestion[].class); - - model.addAttribute("assetcategoryquestionlist",assetCategoryQuestionList); - return "modules/qrfeedback/master/asset-category-questions"; - } - - @GetMapping("/master/asset-parameter") - public String parameter(Model model) { - String apiUrl = appConfig.qrAssetFeedback + "/api/parameter"; - AssetParameter[] assetParameterList = restTemplate.getForObject(apiUrl, AssetParameter[].class); - - model.addAttribute("assetparameterlist",assetParameterList); - return "modules/qrfeedback/master/asset-parameter"; - } - - @GetMapping("/master/asset-parameter-questions") - public String parameterQuestions(Model model) { - String apiUrl = appConfig.qrAssetFeedback + "/api/parameter/question"; - AssetParameterQuestions[] assetParameterQuestionsList = restTemplate.getForObject(apiUrl, AssetParameterQuestions[].class); - - model.addAttribute("assetparameterquestionslist",assetParameterQuestionsList); - return "modules/qrfeedback/master/asset-parameter-questions"; - } - - // For Asset - @GetMapping("/assets/asset-list") - public String asset(Model model) { - String apiUrl = appConfig.qrAssetFeedback + "/api/asset"; - Asset[] assetList = restTemplate.getForObject(apiUrl, Asset[].class); - - model.addAttribute("assetlist",assetList); - return "modules/qrfeedback/assets/asset-list"; - } - - @GetMapping("/assets/asset-questions") - public String assetQuestions(Model model) { - String apiUrl = appConfig.qrAssetFeedback + "/api/asset/question"; - AssetQuestion[] assetQuestionsList = restTemplate.getForObject(apiUrl, AssetQuestion[].class); - - model.addAttribute("assetquestionslist",assetQuestionsList); - return "modules/qrfeedback/assets/asset-questions"; - } - - @GetMapping("/feedbacks/feedback-list") - public String assetFeedback(Model model) { - String apiUrl = appConfig.qrAssetFeedback + "/api/feedback"; - Feedback[] feedbackList = restTemplate.getForObject(apiUrl, Feedback[].class); - model.addAttribute("feedbacklist",feedbackList); - return "modules/qrfeedback/feedbacks/feedback-list"; - } - @GetMapping("/feedbacks/feedback-list-yes") - public String assetFeedbackByTypeYes(Model model) { - String option = "[yes]"; - String apiUrl = appConfig.qrAssetFeedback + "/api/feedback/data/option/"+option; - Feedback[] feedbackList = restTemplate.getForObject(apiUrl, Feedback[].class); - model.addAttribute("feedbacklist",feedbackList); - return "modules/qrfeedback/feedbacks/feedback-list-yes"; - } - @GetMapping("/feedbacks/feedback-list-no") - public String assetFeedbackByTypeNo(Model model) { - String option = "[no]"; - String apiUrl = appConfig.qrAssetFeedback + "/api/feedback/data/option/"+option; - Feedback[] feedbackList = restTemplate.getForObject(apiUrl, Feedback[].class); - model.addAttribute("feedbacklist",feedbackList); - return "modules/qrfeedback/feedbacks/feedback-list-no"; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/Asset.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/Asset.java deleted file mode 100644 index e2c2a4b2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/Asset.java +++ /dev/null @@ -1,301 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Asset { - private Long assetId; - private AssetCategory assetCategory; - private String paramId; - private Long zoneId; - private Long divId; - private String areaName; - private String locName; - private String streetName; - private String assetName; - private String assetCode; - private String assetAddress; - private String assetOpeningTime; - private String assetClosingTime; - private String assetLatitude; - private String assetLongitude; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructors - // Getters and Setters - // Other methods if needed - - @JsonCreator - public Asset( - @JsonProperty("assetId") Long assetId, - @JsonProperty("assetCategory") AssetCategory assetCategory, - @JsonProperty("paramId") String paramId, - @JsonProperty("zoneId") Long zoneId, - @JsonProperty("divId") Long divId, - @JsonProperty("areaName") String areaName, - @JsonProperty("locName") String locName, - @JsonProperty("streetName") String streetName, - @JsonProperty("assetName") String assetName, - @JsonProperty("assetCode") String assetCode, - @JsonProperty("assetAddress") String assetAddress, - @JsonProperty("assetOpeningTime") String assetOpeningTime, - @JsonProperty("assetClosingTime") String assetClosingTime, - @JsonProperty("assetLatitude") String assetLatitude, - @JsonProperty("assetLongitude") String assetLongitude, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.assetId = assetId; - this.assetCategory = assetCategory; - this.paramId = paramId; - this.zoneId = zoneId; - this.divId = divId; - this.areaName = areaName; - this.locName = locName; - this.streetName = streetName; - this.assetName = assetName; - this.assetCode = assetCode; - this.assetAddress = assetAddress; - this.assetOpeningTime = assetOpeningTime; - this.assetClosingTime = assetClosingTime; - this.assetLatitude = assetLatitude; - this.assetLongitude = assetLongitude; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getAssetId() { - return assetId; - } - - public void setAssetId(Long assetId) { - this.assetId = assetId; - } - - public AssetCategory getAssetCategory() { - return assetCategory; - } - - public void setAssetCategory(AssetCategory assetCategory) { - this.assetCategory = assetCategory; - } - - public String getParamId() { - return paramId; - } - - public void setParamId(String paramId) { - this.paramId = paramId; - } - - public Long getZoneId() { - return zoneId; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - public Long getDivId() { - return divId; - } - - public void setDivId(Long divId) { - this.divId = divId; - } - - public String getAreaName() { - return areaName; - } - - public void setAreaName(String areaName) { - this.areaName = areaName; - } - - public String getLocName() { - return locName; - } - - public void setLocName(String locName) { - this.locName = locName; - } - - public String getStreetName() { - return streetName; - } - - public void setStreetName(String streetName) { - this.streetName = streetName; - } - - public String getAssetName() { - return assetName; - } - - public void setAssetName(String assetName) { - this.assetName = assetName; - } - - public String getAssetCode() { - return assetCode; - } - - public void setAssetCode(String assetCode) { - this.assetCode = assetCode; - } - - public String getAssetAddress() { - return assetAddress; - } - - public void setAssetAddress(String assetAddress) { - this.assetAddress = assetAddress; - } - - public String getAssetOpeningTime() { - return assetOpeningTime; - } - - public void setAssetOpeningTime(String assetOpeningTime) { - this.assetOpeningTime = assetOpeningTime; - } - - public String getAssetClosingTime() { - return assetClosingTime; - } - - public void setAssetClosingTime(String assetClosingTime) { - this.assetClosingTime = assetClosingTime; - } - - public String getAssetLatitude() { - return assetLatitude; - } - - public void setAssetLatitude(String assetLatitude) { - this.assetLatitude = assetLatitude; - } - - public String getAssetLongitude() { - return assetLongitude; - } - - public void setAssetLongitude(String assetLongitude) { - this.assetLongitude = assetLongitude; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public static class AssetCategory { - private Long cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructors (JsonCreator) - @JsonCreator - public AssetCategory( - @JsonProperty("cId") Long cId, - @JsonProperty("catName") String catName, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.cId = cId; - this.catName = catName; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getcId() { - return cId; - } - - public void setcId(Long cId) { - this.cId = cId; - } - - public String getCatName() { - return catName; - } - - public void setCatName(String catName) { - this.catName = catName; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetCategory.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetCategory.java deleted file mode 100644 index b40c4ac3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetCategory.java +++ /dev/null @@ -1,82 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class AssetCategory { - private Long cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructor - public AssetCategory() { - - } - @JsonCreator - public AssetCategory(@JsonProperty("cId") Long cId, - @JsonProperty("catName") String catName, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate) { - this.cId = cId; - this.catName = catName; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getcId() { - return cId; - } - - public void setcId(Long cId) { - this.cId = cId; - } - - public String getCatName() { - return catName; - } - - public void setCatName(String catName) { - this.catName = catName; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetCategoryQuestion.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetCategoryQuestion.java deleted file mode 100644 index 2b7ece4e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetCategoryQuestion.java +++ /dev/null @@ -1,195 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class AssetCategoryQuestion { - private Long cmqId; - private AssetCategoryInfo assetCategory; - private String engQuestion; - private String tamilQuestion; - private Long comGroupId; - private Long comSubGroupId; - private String comSubGroupName; - private String qType; - private boolean isActive; - private boolean isDelete; - private Long createdBy; - private String cDate; - - // Constructors - // Getters and Setters - // Other methods if needed - - @JsonCreator - public AssetCategoryQuestion( - @JsonProperty("cmqId") Long cmqId, - @JsonProperty("assetCategory") AssetCategoryInfo assetCategory, - @JsonProperty("engQuestion") String engQuestion, - @JsonProperty("tamilQuestion") String tamilQuestion, - @JsonProperty("comGroupId") Long comGroupId, - @JsonProperty("comSubGroupId") Long comSubGroupId, - @JsonProperty("comSubGroupName") String comSubGroupName, - @JsonProperty("qType") String qType, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.cmqId = cmqId; - this.assetCategory = assetCategory; - this.engQuestion = engQuestion; - this.tamilQuestion = tamilQuestion; - this.comGroupId = comGroupId; - this.comSubGroupId = comSubGroupId; - this.comSubGroupName = comSubGroupName; - this.qType = qType; - this.isActive = isActive; - this.isDelete = isDelete; - this.createdBy = createdBy; - this.cDate = cDate; - } - - // Define the inner class for assetCategory - public static class AssetCategoryInfo { - private Long cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - public Long getcId() { - return cId; - } - public void setcId(Long cId) { - this.cId = cId; - } - public String getCatName() { - return catName; - } - public void setCatName(String catName) { - this.catName = catName; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public Long getCreatedBy() { - return createdBy; - } - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - } - - public Long getCmqId() { - return cmqId; - } - - public void setCmqId(Long cmqId) { - this.cmqId = cmqId; - } - - public AssetCategoryInfo getAssetCategory() { - return assetCategory; - } - - public void setAssetCategory(AssetCategoryInfo assetCategory) { - this.assetCategory = assetCategory; - } - - public String getEngQuestion() { - return engQuestion; - } - - public void setEngQuestion(String engQuestion) { - this.engQuestion = engQuestion; - } - - public String getTamilQuestion() { - return tamilQuestion; - } - - public void setTamilQuestion(String tamilQuestion) { - this.tamilQuestion = tamilQuestion; - } - - public Long getComGroupId() { - return comGroupId; - } - - public void setComGroupId(Long comGroupId) { - this.comGroupId = comGroupId; - } - - public Long getComSubGroupId() { - return comSubGroupId; - } - - public void setComSubGroupId(Long comSubGroupId) { - this.comSubGroupId = comSubGroupId; - } - - public String getComSubGroupName() { - return comSubGroupName; - } - - public void setComSubGroupName(String comSubGroupName) { - this.comSubGroupName = comSubGroupName; - } - - public String getqType() { - return qType; - } - - public void setqType(String qType) { - this.qType = qType; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetParameter.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetParameter.java deleted file mode 100644 index 9d1f0295..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetParameter.java +++ /dev/null @@ -1,123 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class AssetParameter { - private Long paramId; - private AssetCategoryInfo assetCategory; - private String paramName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructor - public AssetParameter() { - - } - @JsonCreator - public AssetParameter(@JsonProperty("paramId") Long paramId, - @JsonProperty("catName") String catName, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate) { - this.paramId = paramId; - this.paramName = catName; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - // Define the inner class for assetCategory - public static class AssetCategoryInfo { - private Long cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - public Long getcId() { - return cId; - } - public void setcId(Long cId) { - this.cId = cId; - } - public String getCatName() { - return catName; - } - public void setCatName(String catName) { - this.catName = catName; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public Long getCreatedBy() { - return createdBy; - } - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - } - - public Long getParamId() { - return paramId; - } - public void setParamId(Long paramId) { - this.paramId = paramId; - } - public AssetCategoryInfo getAssetCategory() { - return assetCategory; - } - public void setAssetCategory(AssetCategoryInfo assetCategory) { - this.assetCategory = assetCategory; - } - public String getParamName() { - return paramName; - } - public void setParamName(String paramName) { - this.paramName = paramName; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public Long getCreatedBy() { - return createdBy; - } - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetParameterQuestions.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetParameterQuestions.java deleted file mode 100644 index 17a0c505..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetParameterQuestions.java +++ /dev/null @@ -1,276 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class AssetParameterQuestions { - private Long apqId; - private AssetParameter assetParameter; - private String engQuestion; - private String tamilQuestion; - private String qType; - private boolean isActive; - private boolean isDelete; - private Long createdBy; - private String cDate; - - // Constructors (JsonCreator) - @JsonCreator - public AssetParameterQuestions( - @JsonProperty("apqId") Long apqId, - @JsonProperty("assetParameter") AssetParameter assetParameter, - @JsonProperty("engQuestion") String engQuestion, - @JsonProperty("tamilQuestion") String tamilQuestion, - @JsonProperty("qType") String qType, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.apqId = apqId; - this.assetParameter = assetParameter; - this.engQuestion = engQuestion; - this.tamilQuestion = tamilQuestion; - this.qType = qType; - this.isActive = isActive; - this.isDelete = isDelete; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getApqId() { - return apqId; - } - - public void setApqId(Long apqId) { - this.apqId = apqId; - } - - public AssetParameter getAssetParameter() { - return assetParameter; - } - - public void setAssetParameter(AssetParameter assetParameter) { - this.assetParameter = assetParameter; - } - - public String getEngQuestion() { - return engQuestion; - } - - public void setEngQuestion(String engQuestion) { - this.engQuestion = engQuestion; - } - - public String getTamilQuestion() { - return tamilQuestion; - } - - public void setTamilQuestion(String tamilQuestion) { - this.tamilQuestion = tamilQuestion; - } - - public String getqType() { - return qType; - } - - public void setqType(String qType) { - this.qType = qType; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - // Define the nested classes for assetParameter and assetCategory - public static class AssetParameter { - private Long paramId; - private AssetCategory assetCategory; - private String paramName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructors (JsonCreator) - @JsonCreator - public AssetParameter( - @JsonProperty("paramId") Long paramId, - @JsonProperty("assetCategory") AssetCategory assetCategory, - @JsonProperty("paramName") String paramName, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.paramId = paramId; - this.assetCategory = assetCategory; - this.paramName = paramName; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getParamId() { - return paramId; - } - - public void setParamId(Long paramId) { - this.paramId = paramId; - } - - public AssetCategory getAssetCategory() { - return assetCategory; - } - - public void setAssetCategory(AssetCategory assetCategory) { - this.assetCategory = assetCategory; - } - - public String getParamName() { - return paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - } - - public static class AssetCategory { - private Long cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructors (JsonCreator) - @JsonCreator - public AssetCategory( - @JsonProperty("cId") Long cId, - @JsonProperty("catName") String catName, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.cId = cId; - this.catName = catName; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - public Long getcId() { - return cId; - } - - public void setcId(Long cId) { - this.cId = cId; - } - - public String getCatName() { - return catName; - } - - public void setCatName(String catName) { - this.catName = catName; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetQuestion.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetQuestion.java deleted file mode 100644 index a097f981..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/AssetQuestion.java +++ /dev/null @@ -1,357 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class AssetQuestion { - private Long aqId; - private AssetDetails assetDetails; - private String engQuestion; - private String tamilQuestion; - private String qType; - private boolean isActive; - private boolean isDelete; - private Long createdBy; - private String cDate; - - // Constructors, Getters and Setters - - @JsonCreator - public AssetQuestion( - @JsonProperty("aqId") Long aqId, - @JsonProperty("assetDetails") AssetDetails assetDetails, - @JsonProperty("engQuestion") String engQuestion, - @JsonProperty("tamilQuestion") String tamilQuestion, - @JsonProperty("qType") String qType, - @JsonProperty("isActive") boolean isActive, - @JsonProperty("isDelete") boolean isDelete, - @JsonProperty("createdBy") Long createdBy, - @JsonProperty("cDate") String cDate - ) { - this.aqId = aqId; - this.assetDetails = assetDetails; - this.engQuestion = engQuestion; - this.tamilQuestion = tamilQuestion; - this.qType = qType; - this.isActive = isActive; - this.isDelete = isDelete; - this.createdBy = createdBy; - this.cDate = cDate; - } - - - public Long getAqId() { - return aqId; - } - - public void setAqId(Long aqId) { - this.aqId = aqId; - } - - public AssetDetails getAssetDetails() { - return assetDetails; - } - - public void setAssetDetails(AssetDetails assetDetails) { - this.assetDetails = assetDetails; - } - - public String getEngQuestion() { - return engQuestion; - } - - public void setEngQuestion(String engQuestion) { - this.engQuestion = engQuestion; - } - - public String getTamilQuestion() { - return tamilQuestion; - } - - public void setTamilQuestion(String tamilQuestion) { - this.tamilQuestion = tamilQuestion; - } - - public String getqType() { - return qType; - } - - public void setqType(String qType) { - this.qType = qType; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public static class AssetDetails { - private Long assetId; - private AssetCategory assetCategory; - private String paramId; - private Long zoneId; - private Long divId; - private String areaName; - private String locName; - private String streetName; - private String assetName; - private String assetCode; - private String assetAddress; - private String assetOpeningTime; - private String assetClosingTime; - private String assetLatitude; - private String assetLongitude; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructors, Getters and Setters - - public AssetDetails() { - } - - public Long getAssetId() { - return assetId; - } - - public void setAssetId(Long assetId) { - this.assetId = assetId; - } - - public AssetCategory getAssetCategory() { - return assetCategory; - } - - public void setAssetCategory(AssetCategory assetCategory) { - this.assetCategory = assetCategory; - } - - public String getParamId() { - return paramId; - } - - public void setParamId(String paramId) { - this.paramId = paramId; - } - - public Long getZoneId() { - return zoneId; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - public Long getDivId() { - return divId; - } - - public void setDivId(Long divId) { - this.divId = divId; - } - - public String getAreaName() { - return areaName; - } - - public void setAreaName(String areaName) { - this.areaName = areaName; - } - - public String getLocName() { - return locName; - } - - public void setLocName(String locName) { - this.locName = locName; - } - - public String getStreetName() { - return streetName; - } - - public void setStreetName(String streetName) { - this.streetName = streetName; - } - - public String getAssetName() { - return assetName; - } - - public void setAssetName(String assetName) { - this.assetName = assetName; - } - - public String getAssetCode() { - return assetCode; - } - - public void setAssetCode(String assetCode) { - this.assetCode = assetCode; - } - - public String getAssetAddress() { - return assetAddress; - } - - public void setAssetAddress(String assetAddress) { - this.assetAddress = assetAddress; - } - - public String getAssetOpeningTime() { - return assetOpeningTime; - } - - public void setAssetOpeningTime(String assetOpeningTime) { - this.assetOpeningTime = assetOpeningTime; - } - - public String getAssetClosingTime() { - return assetClosingTime; - } - - public void setAssetClosingTime(String assetClosingTime) { - this.assetClosingTime = assetClosingTime; - } - - public String getAssetLatitude() { - return assetLatitude; - } - - public void setAssetLatitude(String assetLatitude) { - this.assetLatitude = assetLatitude; - } - - public String getAssetLongitude() { - return assetLongitude; - } - - public void setAssetLongitude(String assetLongitude) { - this.assetLongitude = assetLongitude; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - - - public static class AssetCategory { - private Long cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private Long createdBy; - private String cDate; - - // Constructors, Getters and Setters - - public AssetCategory() { - } - - public Long getcId() { - return cId; - } - - public void setcId(Long cId) { - this.cId = cId; - } - - public String getCatName() { - return catName; - } - - public void setCatName(String catName) { - this.catName = catName; - } - - public boolean isDelete() { - return isDelete; - } - - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - - public boolean isActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public Long getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Long createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/Feedback.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/Feedback.java deleted file mode 100644 index b945ee6c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/data/Feedback.java +++ /dev/null @@ -1,290 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback.data; - -public class Feedback { - private int fbId; - private AssetDetails assetDetails; - private String paramName; - private String mobileNo; - private int ratingVal; - private Object file; - private int createdBy; - private String cDate; - private boolean delete; - private boolean active; - - public Feedback() { - super(); - } - - public int getFbId() { - return fbId; - } - - public void setFbId(int fbId) { - this.fbId = fbId; - } - - public AssetDetails getAssetDetails() { - return assetDetails; - } - - public void setAssetDetails(AssetDetails assetDetails) { - this.assetDetails = assetDetails; - } - - public String getParamName() { - return paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - - public String getMobileNo() { - return mobileNo; - } - - public void setMobileNo(String mobileNo) { - this.mobileNo = mobileNo; - } - - public int getRatingVal() { - return ratingVal; - } - - public void setRatingVal(int ratingVal) { - this.ratingVal = ratingVal; - } - - public Object getFile() { - return file; - } - - public void setFile(Object file) { - this.file = file; - } - - public int getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(int createdBy) { - this.createdBy = createdBy; - } - - public String getCDate() { - return cDate; - } - - public void setCDate(String cDate) { - this.cDate = cDate; - } - - public boolean isDelete() { - return delete; - } - - public void setDelete(boolean delete) { - this.delete = delete; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - - public class AssetDetails { - private int assetId; - private AssetCategory assetCategory; - private String paramId; - private int zoneId; - private int divId; - private String areaName; - private String locName; - private String streetName; - private String assetName; - private String assetCode; - private String assetAddress; - private String assetOpeningTime; - private String assetClosingTime; - private String assetLatitude; - private String assetLongitude; - private boolean isDelete; - private boolean isActive; - private int createdBy; - private String cDate; - - - public AssetDetails() { - super(); - } - - public int getAssetId() { - return assetId; - } - public void setAssetId(int assetId) { - this.assetId = assetId; - } - public AssetCategory getAssetCategory() { - return assetCategory; - } - public void setAssetCategory(AssetCategory assetCategory) { - this.assetCategory = assetCategory; - } - public String getParamId() { - return paramId; - } - public void setParamId(String paramId) { - this.paramId = paramId; - } - public int getZoneId() { - return zoneId; - } - public void setZoneId(int zoneId) { - this.zoneId = zoneId; - } - public int getDivId() { - return divId; - } - public void setDivId(int divId) { - this.divId = divId; - } - public String getAreaName() { - return areaName; - } - public void setAreaName(String areaName) { - this.areaName = areaName; - } - public String getLocName() { - return locName; - } - public void setLocName(String locName) { - this.locName = locName; - } - public String getStreetName() { - return streetName; - } - public void setStreetName(String streetName) { - this.streetName = streetName; - } - public String getAssetName() { - return assetName; - } - public void setAssetName(String assetName) { - this.assetName = assetName; - } - public String getAssetCode() { - return assetCode; - } - public void setAssetCode(String assetCode) { - this.assetCode = assetCode; - } - public String getAssetAddress() { - return assetAddress; - } - public void setAssetAddress(String assetAddress) { - this.assetAddress = assetAddress; - } - public String getAssetOpeningTime() { - return assetOpeningTime; - } - public void setAssetOpeningTime(String assetOpeningTime) { - this.assetOpeningTime = assetOpeningTime; - } - public String getAssetClosingTime() { - return assetClosingTime; - } - public void setAssetClosingTime(String assetClosingTime) { - this.assetClosingTime = assetClosingTime; - } - public String getAssetLatitude() { - return assetLatitude; - } - public void setAssetLatitude(String assetLatitude) { - this.assetLatitude = assetLatitude; - } - public String getAssetLongitude() { - return assetLongitude; - } - public void setAssetLongitude(String assetLongitude) { - this.assetLongitude = assetLongitude; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public int getCreatedBy() { - return createdBy; - } - public void setCreatedBy(int createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - // Asset Category - public class AssetCategory { - private int cId; - private String catName; - private boolean isDelete; - private boolean isActive; - private int createdBy; - private String cDate; - - - public AssetCategory() { - super(); - } - public int getcId() { - return cId; - } - public void setcId(int cId) { - this.cId = cId; - } - public String getCatName() { - return catName; - } - public void setCatName(String catName) { - this.catName = catName; - } - public boolean isDelete() { - return isDelete; - } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } - public boolean isActive() { - return isActive; - } - public void setActive(boolean isActive) { - this.isActive = isActive; - } - public int getCreatedBy() { - return createdBy; - } - public void setCreatedBy(int createdBy) { - this.createdBy = createdBy; - } - public String getcDate() { - return cDate; - } - public void setcDate(String cDate) { - this.cDate = cDate; - } - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/package-info.java deleted file mode 100644 index 81d46e79..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/qrassetfeedback/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.qrassetfeedback; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppModuleAccessRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppModuleAccessRepository.java deleted file mode 100644 index b86b2ff1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppModuleAccessRepository.java +++ /dev/null @@ -1,40 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; - -@Repository -@Transactional -public interface AppModuleAccessRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `modules_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true) - List findByUserGroupID(@Param("usergroup_id") String usergroup_id); - - @Query(value = "SELECT * FROM `modules_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) - List findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id); - - @Modifying - @Query(value = "INSERT INTO `modules_access`(`module_id`, `usergroup_id`) VALUES (:module_id,:usergroup_id)", nativeQuery = true) - void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); - - @Modifying - @Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id", nativeQuery = true) - void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); - - @Modifying - @Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) - void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppModuleRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppModuleRepository.java deleted file mode 100644 index 66706f25..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppModuleRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; - -@Repository -@Transactional -public interface AppModuleRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `modules` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`", nativeQuery = true) - List showAll(); - - @Query(value = "SELECT * FROM `modules` WHERE `id` IN (:checkModuleid) AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id`", nativeQuery = true) - List showAllById(String[] checkModuleid); - - @Query(value = "SELECT * FROM `modules` WHERE (`module_path` = :module_path) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByModulePath(String module_path); -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppUserGroupRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppUserGroupRepository.java deleted file mode 100644 index f8e1acff..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppUserGroupRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.AppUserEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppUserGroupEntity; - -@Repository -@Transactional -public interface AppUserGroupRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppUserRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppUserRepository.java deleted file mode 100644 index 9a544902..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/AppUserRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.AppUserEntity; -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestEntity; - -@Repository -@Transactional -public interface AppUserRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `appusers`", nativeQuery = true) - List showAll(); - - @Query(value = "SELECT * FROM `appusers` WHERE (userid=:userId AND `isdelete`=0)", nativeQuery = true) - List showById(String userId); - - AppUserEntity findByUsername(String username); -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/MenuItemAccessRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/MenuItemAccessRepository.java deleted file mode 100644 index bc7fa103..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/MenuItemAccessRepository.java +++ /dev/null @@ -1,42 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; - -@Repository -@Transactional -public interface MenuItemAccessRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) - List findByUserGroupID(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); - - @Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id); - - @Modifying - @Query(value = "INSERT INTO `menuitem_access`(`menuitem_id`, `module_id`, `usergroup_id`) VALUES (:menuitem_id,:module_id,:usergroup_id)", nativeQuery = true) - void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id); - - @Modifying - @Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id", nativeQuery = true) - void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id); - - @Modifying - @Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) - void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/MenuItemRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/MenuItemRepository.java deleted file mode 100644 index 6e01da5f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/MenuItemRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; - -@Repository -@Transactional -public interface MenuItemRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true) - List getMenuItemByModuleId(@Param("module_id") int module_id); - - @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`module_id`=:module_id AND `id` IN (:checkMenuid)) ORDER BY `orderby`", nativeQuery = true) - List getMenuItemByModuleIdAccess(@Param("module_id") int module_id, String[] checkMenuid); - - @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`url`=:url) LIMIT 0,1", nativeQuery = true) - List findByUrl(@Param("url") String url); - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/SubMenuItemAccessRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/SubMenuItemAccessRepository.java deleted file mode 100644 index 63a8a320..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/SubMenuItemAccessRepository.java +++ /dev/null @@ -1,45 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.AppModuleAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.AppModuleEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemAccessEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; - -@Repository -@Transactional -public interface SubMenuItemAccessRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `submenuitem_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true) - List findByUserGroupID(@Param("usergroup_id") String usergroup_id); - - @Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) - List findByUserGroupIDAccess(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id); - - @Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id,@Param("submenuitem_id") String submenuitem_id); - - @Modifying - @Query(value = "INSERT INTO `submenuitem_access`(`submenuitem_id`, `menuitem_id`, `module_id`, `usergroup_id`) VALUES (:submenuitem_id, :menuitem_id, :module_id, :usergroup_id)", nativeQuery = true) - void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id); - - @Modifying - @Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id", nativeQuery = true) - void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id); - - @Modifying - @Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) - void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/SubMenuItemRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/SubMenuItemRepository.java deleted file mode 100644 index 68b15ab7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/SubMenuItemRepository.java +++ /dev/null @@ -1,33 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.MenuItemEntity; -import in.gov.chennaicorporation.gccoffice.entity.SubMenuItemEntity; - -@Repository -@Transactional -public interface SubMenuItemRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true) - List getSubMenuItemByModuleId(@Param("module_id") int module_id); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `menuitem_id`=:menuitem_id ORDER BY `orderby`", nativeQuery = true) - List getSubMenuItemByMenuItemId(@Param("menuitem_id") int menuitem_id); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`menuitem_id`=:menuitem_id AND `id` IN (:checkSubMenuid)) ORDER BY `orderby`", nativeQuery = true) - List getSubMenuItemByMenuItemIdAccess(@Param("menuitem_id") int menuitem_id,String[] checkSubMenuid); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`url`=:url) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByUrl(@Param("url") String url); - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/UserActivityLogRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/UserActivityLogRepository.java deleted file mode 100644 index 48406cc7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/UserActivityLogRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.UserActivityLog; - -import java.util.List; - -import javax.transaction.Transactional; - -@Repository -@Transactional -public interface UserActivityLogRepository extends JpaRepository { - List findByUserIdOrderByTimestampDesc(String userId); -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/UserInfoRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/repository/UserInfoRepository.java deleted file mode 100644 index 64f9c410..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/repository/UserInfoRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.repository; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.entity.UserInfoEntity; - -@Repository -@Transactional -public interface UserInfoRepository extends JpaRepository{ - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/controller/Maincontroller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/controller/Maincontroller.java deleted file mode 100644 index a00ecb62..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/controller/Maincontroller.java +++ /dev/null @@ -1,57 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.roadwar.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.roadwar.service.LoginMappingService; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/roadwarweb") -@Controller("RoadWarMainController") -public class Maincontroller { - - @Autowired - private LoginUserInfo loginUserInfo; - - @Autowired - private LoginMappingService loginMappingService; - - @GetMapping("/regform") - public String viewdashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String zone=loginMappingService.getZoneByUserId(LoginUserId); - String ward=loginMappingService.getWardByUserId(LoginUserId); - - model.addAttribute("Loginzone", zone); - model.addAttribute("Loginward", ward); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/roadwar/regform"; - } - - - @GetMapping("/updateform") - public String updateForm(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - String zone=loginMappingService.getZoneByUserId(LoginUserId); - String ward=loginMappingService.getWardByUserId(LoginUserId); - - model.addAttribute("Loginzone", zone); - model.addAttribute("Loginward", ward); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/roadwar/updateform"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/controller/RegisterApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/controller/RegisterApiController.java deleted file mode 100644 index 6ea8d30e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/controller/RegisterApiController.java +++ /dev/null @@ -1,258 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.roadwar.controller; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.roadwar.service.RegisterService; - -@RestController -@RequestMapping("/gcc/api/roadwarweb/register") -public class RegisterApiController { - - - @Autowired - private RegisterService registerService; - - - @GetMapping("/getzones") - public Map ViewZoneDropdown() { - - Map response = new HashMap<>(); - - List> zones = registerService.ViewZoneDropdown(); - - if (!zones.isEmpty()) { - response.put("status", true); - response.put("message", "Zone list fetched successfully"); - response.put("data", zones); - } else { - response.put("status", false); - response.put("message", "No zones found"); - response.put("data", Collections.emptyList()); - } - - return response; - } - - @GetMapping("/getwardbyzone") - public Map ViewWardDropdown(@RequestParam String zone) { - - Map response = new HashMap<>(); - - List> wards = registerService.ViewWardDropdown(zone); - - if (!wards.isEmpty()) { - response.put("status", true); - response.put("message", "Ward list fetched successfully"); - response.put("data", wards); - } else { - response.put("status", false); - response.put("message", "No wards found"); - response.put("data", Collections.emptyList()); - } - - return response; - } - - - - @GetMapping("/getRoadNamesByWard") - public Map getRoadNamesByWard(@RequestParam String ward) { - Map response = new HashMap<>(); - List> roads = registerService.getRoadNamesByWard(ward); - if (!roads.isEmpty()) { - response.put("status", true); - response.put("message", "Road names fetched successfully"); - response.put("data", roads); - } else { - response.put("status", false); - response.put("message", "No roads found for ward: " + ward); - response.put("data", Collections.emptyList()); - } - return response; - } - - - @GetMapping("/getRoadType") - public Map getRoadType() { - Map response = new HashMap<>(); - List> roadTypes = registerService.getRoadType(); - if (!roadTypes.isEmpty()) { - response.put("status", true); - response.put("message", "Road types fetched successfully"); - response.put("data", roadTypes); - } else { - response.put("status", false); - response.put("message", "No road types found"); - response.put("data", Collections.emptyList()); - } - return response; - } - - - @GetMapping("/getRoadTypeMaterial") - public Map getRoadTypeMaterial() { - Map response = new HashMap<>(); - List> roadTypes = registerService.getRoadTypeMaterial(); - if (!roadTypes.isEmpty()) { - response.put("status", true); - response.put("message", "Roadtype Material fetched successfully"); - response.put("data", roadTypes); - } else { - response.put("status", false); - response.put("message", "No roadtype material found"); - response.put("data", Collections.emptyList()); - } - return response; - } - - @GetMapping("/getFootpathType") - public Map getFootpathType() { - Map response = new HashMap<>(); - List> roadTypes = registerService.getFootpathType(); - if (!roadTypes.isEmpty()) { - response.put("status", true); - response.put("message", "Footpath Types fetched successfully"); - response.put("data", roadTypes); - } else { - response.put("status", false); - response.put("message", "No Footpath Types found"); - response.put("data", Collections.emptyList()); - } - return response; - } - - @GetMapping("/getRoadSide") - public Map getRoadSide() { - Map response = new HashMap<>(); - List> roadTypes = registerService.getRoadSide(); - if (!roadTypes.isEmpty()) { - response.put("status", true); - response.put("message", "Road sides fetched successfully"); - response.put("data", roadTypes); - } else { - response.put("status", false); - response.put("message", "No Road sides found"); - response.put("data", Collections.emptyList()); - } - return response; - } - - @GetMapping("/getMonthList") - public Map getMonthList() { - Map response = new HashMap<>(); - List> months = registerService.getMonthList(); - if (!months.isEmpty()) { - response.put("status", true); - response.put("message", "Month list fetched successfully"); - response.put("data", months); - } else { - response.put("status", false); - response.put("message", "No months found"); - response.put("data", Collections.emptyList()); - } - return response; - } - - - - @GetMapping("/getYearList") - public Map getYearList() { - Map response = new HashMap<>(); - List> years = registerService.getYearList(); - if (!years.isEmpty()) { - response.put("status", true); - response.put("message", "Year list fetched successfully"); - response.put("data", years); - } else { - response.put("status", false); - response.put("message", "No Year found"); - response.put("data", Collections.emptyList()); - } - return response; - } - - - @PostMapping("/saveRoadWarDetails") - public Map saveRoadWarDetails(@RequestBody Map payload) { - return registerService.saveRoadWarDetails(payload); - } - - - @GetMapping("/getAllRoadWarDetails") - public ResponseEntity getAllRoadWarDetails( - @RequestParam(required = false) String userid, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam(required = false) String roadId) { - - try { - - List> response = - registerService.getAllRoadWarDetails(userid,zone, ward, roadId); - - return ResponseEntity.ok(response); - - } catch (Exception e) { - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", - "Failed to fetch data : " + e.getMessage())); - } - } - - - - @GetMapping("/getRoadWarDetailsById") - public ResponseEntity getRoadWarDetailsById( - @RequestParam String refid) { - - try { - - Map response = - registerService.getRoadWarDetailsById(refid); - - return ResponseEntity.ok(response); - - } catch (Exception e) { - - Map error = new HashMap<>(); - error.put("status", false); - error.put("message", "Failed to fetch data : " + e.getMessage()); - - return ResponseEntity - .status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(error); - } - } - - @GetMapping("/checkRoadExists") - public Map checkRoadExists(@RequestParam("roadId") Integer roadId) { - return registerService.checkRoadExists(roadId); - } - - @PostMapping("/updateRoadWarDetails") - public Map updateRoadWarDetails(@RequestBody Map payload) { - return registerService.updateRoadWarDetails(payload); - } - - @PostMapping("/deleteRoadWarDetails") - public Map deleteRoadWarDetails( - @RequestParam String refId,@RequestParam String updatedby) { - - return registerService.deleteRoadWarDetails(refId,updatedby); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/service/LoginMappingService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/service/LoginMappingService.java deleted file mode 100644 index d8d97b8a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/service/LoginMappingService.java +++ /dev/null @@ -1,51 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.roadwar.service; - -import java.util.Collections; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class LoginMappingService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlGCCUserDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public String getZoneByUserId(String userid) { - - String sql = "SELECT zone FROM user_mapping_details WHERE userid=?"; - - try { - return jdbcTemplate.queryForObject(sql, String.class, userid); - }catch (EmptyResultDataAccessException e) { - return ""; - } catch (Exception e) { - e.printStackTrace(); - return ""; - } - } - - public String getWardByUserId(String userid) { - - String sql = "SELECT ward FROM user_mapping_details WHERE userid=?"; - - try { - return jdbcTemplate.queryForObject(sql, String.class, userid); - } catch (EmptyResultDataAccessException e) { - return ""; - }catch (Exception e) { - e.printStackTrace(); - return ""; - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/service/RegisterService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/service/RegisterService.java deleted file mode 100644 index 6c44dd2e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/roadwar/service/RegisterService.java +++ /dev/null @@ -1,777 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.roadwar.service; - -import java.net.URI; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -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.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.web.client.RestTemplate; -import org.springframework.transaction.annotation.Transactional; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Service -public class RegisterService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private Environment environment; - - @Autowired - public void setDataSource(@Qualifier("mysqlRoadWarDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public List> ViewZoneDropdown() { - String sql = "SELECT zone_name " - + "FROM zone_master " - + "WHERE is_active=1 AND is_delete=0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> ViewWardDropdown(String zone) { - String sql = "SELECT ward_name " - + "FROM ward_master " - + "WHERE is_active=1 AND is_delete=0 AND zone_id=?"; - try { - return jdbcTemplate.queryForList(sql, zone); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getRoadNamesByWard(String ward) { - try { - String encodedWard = URLEncoder.encode("'" + ward + "'", StandardCharsets.UTF_8.toString()); - String url = "https://gisgcc.chennaicorporation.gov.in/server/rest/services/GCCDepts/EDPMobile2025/FeatureServer/0/query" - + "?where=new_ward%3D" + encodedWard - + "&fullText=&objectIds=&time=&geometry=&geometryType=esriGeometryPoint&inSR=4326&defaultSR=4326&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Meter&relationParam=" - + "&outFields=road_id%2Croad_name%2Clocality%2Carea_name%2Ctype" - + "&returnGeometry=false" - + "&maxAllowableOffset=&geometryPrecision=&outSR=&havingClause=&gdbVersion=&historicMoment=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=xyFootprint&resultOffset=&resultRecordCount=&returnTrueCurves=false&returnExceededLimitFeatures=false&quantizationParameters=&returnCentroid=false&returnEnvelope=false&timeReferenceUnknownClient=false&maxRecordCountFactor=&sqlFormat=none&resultType=&featureEncoding=esriDefault&datumTransformation=&cacheHint=false" - + "&f=geojson"; - - RestTemplate restTemplate = new RestTemplate(); - String responseBody = restTemplate.getForObject(URI.create(url), String.class); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode root = objectMapper.readTree(responseBody); - JsonNode features = root.path("features"); - - List> roadList = new ArrayList<>(); - if (features.isArray()) { - for (JsonNode feature : features) { - JsonNode props = feature.path("properties"); - String roadId = props.path("road_id").asText(); - String roadName = props.path("road_name").asText(); - String locality = props.path("locality").asText(); - String areaName = props.path("area_name").asText(); - String type = props.path("type").asText(); - - Map roadInfo = new HashMap<>(); - roadInfo.put("road_id", roadId); - roadInfo.put("road_name", roadName); - roadInfo.put("locality", locality); - roadInfo.put("area_name", areaName); - roadInfo.put("type", type); - - roadList.add(roadInfo); - } - } - return roadList; - - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getRoadType() { - String sql = "Select id,road_type as roadType from road_type_master where is_active = 1 and is_delete = 0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getRoadTypeMaterial() { - String sql = "Select id,roadtype_material from roadtype_material_master where is_active = 1 and is_delete = 0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getFootpathType() { - String sql = "Select id,footpath_type_name from footpath_type_master where is_active = 1 and is_delete = 0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getRoadSide() { - String sql = "Select id,road_side_name from road_side_master where is_active = 1 and is_delete = 0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getMonthList() { - String sql = "SELECT id, month_name FROM month_master WHERE is_active = 1 AND is_delete = 0 ORDER BY id"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> getYearList() { - String sql = "SELECT id, year_name FROM year_master WHERE is_active = 1 AND is_delete = 0 ORDER BY id DESC"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public Map saveRoadWarDetails(Map payload) { - Map result = new HashMap<>(); - try { - String roadId = String.valueOf(payload.get("road_id")); - - Integer count = jdbcTemplate.queryForObject( - "SELECT COUNT(*) " + - "FROM road_details_master " + - "WHERE road_id = ? " + - "AND is_active = 1 " + - "AND is_delete = 0", - Integer.class, - roadId); - - if (count != null && count > 0) { - - result.put("status", false); - result.put("message", - "Selected road is already mapped to another Road War record"); - - return result; - } - - String insertRoad = "INSERT INTO road_details_master " - + "(zone, ward, road_name, road_type, road_length, road_avg_width, road_area, " - + " footpath_material, footpath_length, footpath_width, footpath_from_location, footpath_to_location, " - + " is_swd, swd_from, swd_to, swd_length, swd_size, " - + " is_scp, scp_count, is_manhole, manhole_count, manhole_at, " - + " is_cpipe, cpipe_count, is_rwh, rwh_count, " - + " sewer_length, sewer_size, " - + " is_electric_poles, ep_count, is_hml, culvert_bridge_count, details, " - + " is_busshelter, busshelter_count, is_centermedian, erp_asset_code, cby,road_id,road_type_material,road_min_width,road_max_width, " - + " hml_count,is_streetlight_poles,streetlight_poles_count,is_mml,mml_count,road_from,road_to,is_footpath,footpath_at,area_name,locality_name,road_row_width, " - + " r_footpath_material,r_footpath_length,r_footpath_width,swd_at,rhs_swdlength,rhs_swdsize,scp_at,rhs_scpCount,r_mhCount,cp_at,r_cpCount,rwh_at,r_rwCount )" - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update((PreparedStatementCreator) con -> { - var ps = con.prepareStatement(insertRoad, new String[] { "id" }); - ps.setObject(1, payload.get("zone")); - ps.setObject(2, payload.get("ward")); - ps.setObject(3, payload.get("road_name")); - ps.setObject(4, payload.get("road_type")); - // ps.setObject(5, payload.get("highway_ans")); - ps.setObject(5, payload.get("road_length")); - ps.setObject(6, payload.get("road_avg_width")); - ps.setObject(7, payload.get("road_area")); - ps.setObject(8, payload.get("footpath_material")); - ps.setObject(9, payload.get("footpath_length")); - ps.setObject(10, payload.get("footpath_width")); - ps.setObject(11, payload.get("footpath_from_location")); - ps.setObject(12, payload.get("footpath_to_location")); - ps.setObject(13, payload.get("is_swd")); - ps.setObject(14, payload.get("swd_from")); - ps.setObject(15, payload.get("swd_to")); - ps.setObject(16, payload.get("swd_length")); - ps.setObject(17, payload.get("swd_size")); - ps.setObject(18, payload.get("is_scp")); - ps.setObject(19, payload.get("scp_count")); - ps.setObject(20, payload.get("is_manhole")); - ps.setObject(21, payload.get("manhole_count")); - ps.setObject(22, payload.get("manhole_at")); - ps.setObject(23, payload.get("is_cpipe")); - ps.setObject(24, payload.get("cpipe_count")); - ps.setObject(25, payload.get("is_rwh")); - ps.setObject(26, payload.get("rwh_count")); - ps.setObject(27, payload.get("sewer_length")); - ps.setObject(28, payload.get("sewer_size")); - ps.setObject(29, payload.get("is_electric_poles")); - ps.setObject(30, payload.get("ep_count")); - ps.setObject(31, payload.get("is_hml")); - ps.setObject(32, payload.get("culvert_bridge_count")); - ps.setObject(33, payload.get("details")); - ps.setObject(34, payload.get("is_busshelter")); - ps.setObject(35, payload.get("busshelter_count")); - ps.setObject(36, payload.get("is_centermedian")); - ps.setObject(37, payload.get("erp_asset_code")); - ps.setObject(38, payload.get("cby")); - ps.setObject(39, payload.get("road_id")); - ps.setObject(40, payload.get("road_type_material")); - ps.setObject(41, payload.get("road_min_width")); - ps.setObject(42, payload.get("road_max_width")); - ps.setObject(43, payload.get("hml_count")); - ps.setObject(44, payload.get("is_streetlight_poles")); - ps.setObject(45, payload.get("streetlight_poles_count")); - ps.setObject(46, payload.get("is_mml")); - ps.setObject(47, payload.get("mml_count")); - ps.setObject(48, payload.get("roadfrom")); - ps.setObject(49, payload.get("roadto")); - ps.setObject(50, payload.get("is_footpath")); - ps.setObject(51, payload.get("footpathat")); - ps.setObject(52, payload.get("areaname")); - ps.setObject(53, payload.get("localityname")); - ps.setObject(54, payload.get("road_row_width")); - ps.setObject(55, payload.get("rhs_footpathDropdown")); - ps.setObject(56, payload.get("rhs_fplength")); - ps.setObject(57, payload.get("rhs_fpwidth")); - ps.setObject(58, payload.get("swd_at")); - ps.setObject(59, payload.get("rhs_swdlength")); - ps.setObject(60, payload.get("rhs_swdsize")); - ps.setObject(61, payload.get("scp_at")); - ps.setObject(62, payload.get("rhs_scpCount")); - ps.setObject(63, payload.get("r_mhCount")); - ps.setObject(64, payload.get("cp_at")); - ps.setObject(65, payload.get("r_cpCount")); - ps.setObject(66, payload.get("rwh_at")); - ps.setObject(67, payload.get("r_rwCount")); - return ps; - }, keyHolder); - - long generatedId = keyHolder.getKey().longValue(); - String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("ddMMYYYY")); - String refId = datePrefix + generatedId; - - jdbcTemplate.update( - "UPDATE road_details_master SET ref_id = ? WHERE id = ?", - refId, generatedId); - - List> relayingList = (List>) payload.get("relaying_details"); - - if (relayingList != null && !relayingList.isEmpty()) { - String insertRelay = "INSERT INTO relaying_details " - + "(road_ref_id, relay_month, relay_year,road_type_material ,cr_value, road_type, remarks, cby) " - + "VALUES (?,?,?,?,?,?,?,?)"; - - for (Map relay : relayingList) { - jdbcTemplate.update(insertRelay, - refId, - relay.get("relay_month"), - relay.get("relay_year"), - relay.get("road_type_material"), - relay.get("cr_value"), - relay.get("road_type"), - relay.get("remarks"), - payload.get("cby")); - } - } - - result.put("status", true); - result.put("message", "Road war details saved successfully"); - result.put("ref_id", refId); - - } catch (Exception e) { - e.printStackTrace(); - result.put("status", false); - result.put("message", "Failed to save road war details: " + e.getMessage()); - } - return result; - } - - public List> getAllRoadWarDetails( - String userid, - String zone, - String ward, - String roadId) { - - StringBuilder sql = new StringBuilder( - " SELECT rdm.*,rtm.road_type as road_type_name,rtmm.roadtype_material as roadtype_material_name,ftm.footpath_type_name as footpath_material_name FROM road_details_master rdm " - + - " LEFT JOIN road_type_master rtm ON rtm.id= rdm.road_type " + - " LEFT JOIN roadtype_material_master rtmm ON rtmm.id= rdm.road_type_material " + - " LEFT JOIN footpath_type_master ftm ON ftm.id= rdm.footpath_material " + - " WHERE 1=1 "); - - List params = new ArrayList<>(); - - if (userid != null && !userid.isEmpty()) { - sql.append(" AND rdm.cby = ?"); - params.add(userid); - } - - if (zone != null && !zone.isEmpty()) { - sql.append(" AND rdm.zone = ?"); - params.add(zone); - } - - if (ward != null && !ward.isEmpty()) { - sql.append(" AND rdm.ward = ?"); - params.add(ward); - } - - if (roadId != null && !roadId.isEmpty()) { - sql.append(" AND rdm.road_id = ?"); - params.add(roadId); - } - - sql.append(" AND rdm.is_active=1 AND rdm.is_delete=0 "); - - sql.append(" ORDER BY rdm.id DESC"); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - public Map getRoadWarDetailsById(String refid) { - - Map result = new HashMap<>(); - - try { - - String sql = "SELECT rdm.*, rtm.road_type As road_type_name,rtmm.roadtype_material as roadtype_material,ftm.footpath_type_name as footpath_material_name " - + - "FROM road_details_master rdm " + - "LEFT JOIN road_type_master rtm ON rtm.id = rdm.road_type " + - "LEFT JOIN roadtype_material_master rtmm ON rtmm.id = rdm.road_type_material " + - "LEFT JOIN footpath_type_master ftm ON ftm.id= rdm.footpath_material " + - "WHERE rdm.ref_id = ? AND rdm.is_active=1 AND rdm.is_delete=0 "; - - Map road = jdbcTemplate.queryForMap(sql, refid); - - result.putAll(road); - - List> relayingDetails = jdbcTemplate.queryForList( - " SELECT rd.*,mm.month_name,ym.year_name,rtmm.roadtype_material " - + " FROM relaying_details rd " - + " LEFT JOIN month_master mm on mm.id = rd.relay_month " - + " LEFT JOIN year_master ym on ym.id = rd.relay_year " - + " LEFT JOIN roadtype_material_master rtmm on rtmm.id = rd.road_type_material " - + " WHERE rd.road_ref_id = ? AND rd.is_active=1 AND rd.is_delete=0 ", - refid); - - result.put("relayingDetails", relayingDetails); - result.put("status", true); - - } catch (Exception e) { - - result.put("status", false); - result.put("message", e.getMessage()); - - } - - return result; - } - - public Map checkRoadExists(Integer roadId) { - - Map response = new HashMap<>(); - - try { - - String sql = " SELECT COUNT(*) FROM road_details_master " - - + " WHERE road_id = ? AND is_active=1 AND is_delete = 0 "; - - Integer count = jdbcTemplate.queryForObject( - sql, - Integer.class, - roadId); - - response.put("status", true); - response.put("exists", count != null && count > 0); - - } catch (Exception e) { - - e.printStackTrace(); - - response.put("status", false); - response.put("message", "Error while checking road"); - - } - - return response; - } - - @Transactional - public Map updateRoadWarDetails(Map payload) { - - Map result = new HashMap<>(); - - try { - - String refId = String.valueOf(payload.get("ref_id")); - String updatedBy = String.valueOf(payload.get("updated_by")); - - String roadId = String.valueOf(payload.get("road_id")); - - Integer count = jdbcTemplate.queryForObject( - "SELECT COUNT(*) " + - "FROM road_details_master " + - "WHERE road_id = ? " + - "AND ref_id <> ? " + - "AND is_active = 1 " + - "AND is_delete = 0", - Integer.class, - roadId, - refId); - - if (count != null && count > 0) { - - result.put("status", false); - result.put("message", - "Selected road is already mapped to another Road War record"); - - return result; - } - - // COPY CURRENT RECORD TO LOG TABLE - - String logSql = "INSERT INTO road_details_master_log (" + - "id, zone, ward, road_id, road_name,area_name,locality_name, road_type,road_type_material, highway_ans, " - + - "road_length,road_row_width, road_avg_width,road_min_width,road_max_width, road_area, " + - "road_from,road_to,is_footpath,footpath_at, " + - "footpath_material, footpath_length, footpath_width, " + - "r_footpath_material, r_footpath_length, r_footpath_width, " + - "footpath_from_location, footpath_to_location, " + - "swd_at,rhs_swdlength,rhs_swdsize,scp_at,rhs_scpCount,manhole_at,r_mhCount,cp_at,r_cpCount,rwh_at,r_rwCount, " - + - "is_swd, swd_from, swd_to, swd_length, swd_size, " + - "is_scp, scp_count, is_manhole, manhole_count, manhole_location, " + - "is_cpipe, cpipe_count, is_rwh, rwh_count, " + - "sewer_length, sewer_size, is_electric_poles, ep_count, is_hml,hml_count, " + - "is_streetlight_poles,streetlight_poles_count,is_mml,mml_count, " + - "culvert_bridge_count, details, is_busshelter, busshelter_count, " + - "is_centermedian, erp_asset_code, ref_id, cdate, cby, " + - "updated_date, updated_by, is_active, is_delete) " + - "SELECT " + - "id, zone, ward, road_id, road_name,area_name,locality_name, road_type,road_type_material, highway_ans, " - + - "road_length,road_row_width, road_avg_width,road_min_width,road_max_width, road_area, " + - "road_from,road_to,is_footpath,footpath_at, " + - "footpath_material, footpath_length, footpath_width, " + - "r_footpath_material, r_footpath_length, r_footpath_width, " + - "footpath_from_location, footpath_to_location, " + - "swd_at,rhs_swdlength,rhs_swdsize,scp_at,rhs_scpCount,manhole_at,r_mhCount,cp_at,r_cpCount,rwh_at,r_rwCount, " - + - "is_swd, swd_from, swd_to, swd_length, swd_size, " + - "is_scp, scp_count, is_manhole, manhole_count, manhole_location, " + - "is_cpipe, cpipe_count, is_rwh, rwh_count, " + - "sewer_length, sewer_size, is_electric_poles, ep_count, is_hml,hml_count, " + - "is_streetlight_poles,streetlight_poles_count,is_mml,mml_count, " + - "culvert_bridge_count, details, is_busshelter, busshelter_count, " + - "is_centermedian, erp_asset_code, ref_id, cdate, cby, " + - "updated_date, updated_by, is_active, is_delete " + - "FROM road_details_master " + - "WHERE ref_id=?"; - - jdbcTemplate.update(logSql, refId); - - // 3. UPDATE ROAD MASTER - - String updateSql = "UPDATE road_details_master SET " + - "zone=?, " + - "ward=?, " + - "road_id=?, " + - "road_name=?, " + - "area_name=?, " + - "locality_name=?, " + - "road_type=?, " + - "road_type_material=?, " + - "road_length=?, " + - "road_row_width=?, " + - "road_avg_width=?, " + - "road_min_width=?, " + - "road_max_width=?, " + - "road_area=?, " + - "road_from=?, " + - "road_to=?, " + - "is_footpath=?, " + - "footpath_at=?, " + - "footpath_material=?, " + - "footpath_length=?, " + - "footpath_width=?, " + - "r_footpath_material=?, " + - "r_footpath_length=?, " + - "r_footpath_width=?, " + - "footpath_from_location=?, " + - "footpath_to_location=?, " + - "is_swd=?, " + - "swd_from=?, " + - "swd_to=?, " + - "swd_at=?," + - "swd_length=?, " + - "swd_size=?, " + - "rhs_swdlength=?, " + - "rhs_swdsize=?, " + - "is_scp=?, " + - "scp_at=?, " + - "scp_count=?, " + - "rhs_scpCount=?," + - "is_manhole=?, " + - "manhole_count=?, " + - "manhole_at=?, " + - "r_mhCount=?, " + - "is_cpipe=?, " + - "cpipe_count=?, " + - "cp_at=?, " + - "r_cpCount=?, " + - "is_rwh=?, " + - "rwh_count=?, " + - "rwh_at=?, " + - "r_rwCount=?, " + - "sewer_length=?, " + - "sewer_size=?, " + - "is_electric_poles=?, " + - "ep_count=?, " + - "is_hml=?, " + - "hml_count=?, " + - "is_streetlight_poles=?, " + - "streetlight_poles_count=?, " + - "is_mml=?, " + - "mml_count=?, " + - "culvert_bridge_count=?, " + - "details=?, " + - "is_busshelter=?, " + - "busshelter_count=?, " + - "is_centermedian=?, " + - "updated_date=NOW(), " + - "updated_by=? " + - "WHERE ref_id=?"; - - jdbcTemplate.update(updateSql, - - payload.get("zone"), - payload.get("ward"), - payload.get("road_id"), - payload.get("road_name"), - payload.get("road_areaname"), - payload.get("road_localityname"), - payload.get("road_type"), - payload.get("road_type_material"), - - payload.get("road_length"), - payload.get("road_row_width"), - payload.get("road_avg_width"), - payload.get("road_min_width"), - payload.get("road_max_width"), - payload.get("road_area"), - payload.get("road_from"), - payload.get("road_to"), - - payload.get("is_footpath"), - payload.get("footpath_at"), - - payload.get("footpath_material"), - payload.get("footpath_length"), - payload.get("footpath_width"), - payload.get("rhs_footpathDropdown"), - payload.get("rhs_fplength"), - payload.get("rhs_fpwidth"), - - payload.get("footpath_from_location"), - payload.get("footpath_to_location"), - - payload.get("is_swd"), - payload.get("swd_from"), - payload.get("swd_to"), - payload.get("swd_at"), - payload.get("swd_length"), - payload.get("swd_size"), - payload.get("rhs_swdlength"), - payload.get("rhs_swdsize"), - - payload.get("is_scp"), - payload.get("scp_at"), - payload.get("scp_count"), - payload.get("rhs_scpCount"), - - payload.get("is_manhole"), - payload.get("manhole_count"), - payload.get("manhole_at"), - payload.get("r_mhCount"), - - payload.get("is_cpipe"), - payload.get("cpipe_count"), - payload.get("cp_at"), - payload.get("r_cpCount"), - - payload.get("is_rwh"), - payload.get("rwh_count"), - payload.get("rwh_at"), - payload.get("r_rwCount"), - - payload.get("sewer_length"), - payload.get("sewer_size"), - - payload.get("is_electric_poles"), - payload.get("ep_count"), - - payload.get("is_hml"), - payload.get("hml_count"), - payload.get("is_streetlight_poles"), - payload.get("streetlight_poles_count"), - payload.get("is_mml"), - payload.get("mml_count"), - - payload.get("culvert_bridge_count"), - payload.get("details"), - - payload.get("is_busshelter"), - payload.get("busshelter_count"), - - payload.get("is_centermedian"), - - updatedBy, - refId); - - // 4. SOFT DELETE OLD RELAYING RECORDS - - jdbcTemplate.update( - "UPDATE relaying_details " + - "SET is_active=0, " + - "is_delete=1, " + - "updated_date=NOW(), " + - "updated_by=? " + - "WHERE road_ref_id=? " + - "AND is_active=1", - updatedBy, - refId); - - // 5. INSERT NEW RELAYING RECORDS - - @SuppressWarnings("unchecked") - List> relays = (List>) payload.get("relaying_details"); - - String insertRelay = "INSERT INTO relaying_details " + - "(road_ref_id, relay_month, relay_year,road_type_material, cr_value, road_type, remarks, cby) " + - "VALUES (?,?,?,?,?,?,?,?)"; - - if (relays != null) { - - for (Map relay : relays) { - - jdbcTemplate.update( - insertRelay, - refId, - relay.get("relay_month"), - relay.get("relay_year"), - relay.get("road_type_material"), - relay.get("cr_value"), - relay.get("road_type"), - relay.get("remarks"), - updatedBy); - } - } - - result.put("status", true); - result.put("message", "Road details updated successfully"); - - } catch (Exception e) { - - e.printStackTrace(); - - result.put("status", false); - result.put("message", e.getMessage()); - } - - return result; - } - - public Map deleteRoadWarDetails(String refId, String updatedby) { - Map result = new HashMap<>(); - - try { - - int roadUpdated = jdbcTemplate.update( - "UPDATE road_details_master " + - "SET is_active=0, " + - "is_delete=1, " + - "updated_by=?, " + - "updated_date=NOW() " + - "WHERE ref_id=? " + - "AND is_active=1", - updatedby, refId); - - jdbcTemplate.update( - "UPDATE relaying_details " + - "SET is_active=0, " + - "is_delete=1, " + - "updated_by=?, " + - "updated_date=NOW() " + - "WHERE road_ref_id=? " + - "AND is_active=1", - updatedby, refId); - - if (roadUpdated > 0) { - - result.put("status", true); - result.put("message", - "Road War details deleted successfully"); - - } else { - - result.put("status", false); - result.put("message", "Record not found"); - } - - } catch (Exception e) { - - e.printStackTrace(); - - result.put("status", false); - result.put("message", - "Failed to delete Road War details"); - } - - return result; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/school/.DS_Store deleted file mode 100644 index c2816539..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/school/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/.DS_Store deleted file mode 100644 index 4bd73b29..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/BuildingAssetController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/BuildingAssetController.java deleted file mode 100644 index e67ff543..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/BuildingAssetController.java +++ /dev/null @@ -1,567 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Controller; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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 in.gov.chennaicorporation.gccoffice.school.Service.BuildingAssetService; -import in.gov.chennaicorporation.gccoffice.school.Service.SchoolPropertyService; - -@RestController -@RequestMapping("/gcc/api/gccschool/buildingasset") -public class BuildingAssetController { - - private BuildingAssetService buildingAssetService; - - @Autowired - public BuildingAssetController(BuildingAssetService buildingAssetService) { - this.buildingAssetService = buildingAssetService; - } - - // For Buildings - @PostMapping(value = "/saveBuildings") - public String saveBuildings(@RequestBody List> buildingList) { - try { - for (Map building : buildingList) { - String building_name = (String) building.get("building_name"); - int total_floor = Integer.parseInt(building.get("total_floor").toString()); - int building_material = Integer.parseInt(building.get("building_material").toString()); - int roof_material = Integer.parseInt(building.get("roof_material").toString()); - // int building_order = - // Integer.parseInt(building.get("building_order").toString()); - int school_id = Integer.parseInt(building.get("school_id").toString()); - int check_building = buildingAssetService.checkBuilding(building_name, school_id); - if (check_building == 1) { - return "Building Name Alredy Exist"; - } else if (check_building == 5) { - return "error"; - } - int building_id = buildingAssetService.saveBuildings(building_name, total_floor, building_material, - roof_material, school_id); - System.out.println("Hi"); - for (int i = 1; i <= total_floor; i++) { - Map floor = buildingAssetService.getFloor(i); - - String floor_name = (String) floor.get("content"); - int floor_master_id = Integer.parseInt(floor.get("floor_master_id").toString()); - buildingAssetService.saveFloor(floor_name, building_id, floor_master_id, school_id); - System.out.println("Saved Floor Master ID: " + floor_master_id); - } - } - return "Building Saved sucessfully"; - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - // To Get Saved Buildings - @GetMapping("/getSavedBuildings") - public ResponseEntity> getSavedBuildings(int school_id) { - try { - List> data = buildingAssetService.getSavedBuildings(school_id); - int lastId = buildingAssetService.getLastBuildingOrder(school_id); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - response.put("lastId", lastId); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - response.put("lastId", lastId); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get floor Data by buildings - @GetMapping("/getFloorDetails") - public ResponseEntity> getFloorDetails(int building_id) { - try { - List> data = buildingAssetService.getFloorDetails(building_id); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // For Room mapping --add room - /* - * @PostMapping(value = "/saveRoom") public String saveRoom(@RequestBody - * Map rooms) { try { int building_id = (int) - * rooms.get("building_id"); int floors_id = (int) rooms.get("floors_id"); int - * room_type = Integer.parseInt(rooms.get("room_type").toString()); - * - * String room_num = (String) rooms.get("room_num"); int school_id = (int) - * rooms.get("school_id"); buildingAssetService.saveRoomDetails(room_type, - * room_num, building_id, floors_id, school_id); return - * "Rooms Mapped Sucessfully"; } catch (Exception e) { e.printStackTrace(); - * return "error"; } } - */ - - // vishnu save - @PostMapping(value = "/saveRoom") - public String saveRoom(@RequestBody Map rooms) { - try { - int building_id = Integer.parseInt(rooms.get("building_id").toString()); - int floors_id = Integer.parseInt(rooms.get("floors_id").toString()); - int room_type = Integer.parseInt(rooms.get("room_type").toString()); - String room_num = rooms.get("room_num").toString(); - int school_id = Integer.parseInt(rooms.get("school_id").toString()); - - String anganwadiUniqueNumber = rooms.get("anganwadiUniqueNumber") != null - ? rooms.get("anganwadiUniqueNumber").toString().trim() - : null; - Boolean anganwadi_check = rooms.get("anganwadi_check") != null ? Boolean.parseBoolean(rooms.get("anganwadi_check").toString()) : null; - - return buildingAssetService.roomDetails(room_type, room_num, building_id, floors_id,anganwadiUniqueNumber, anganwadi_check, school_id); - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - // For Edit Room mapping -// @PostMapping(value = "/editRoom") -// public String editRoom(@RequestBody Map rooms) { -// try { -// int room_id = (int) rooms.get("room_id"); -// int building_id = (int) rooms.get("building_id"); -// int floors_id = (int) rooms.get("floors_id"); -// int room_type = (int) rooms.get("room_type"); -// String room_num = (String) rooms.get("room_num"); -// int school_id = (int) rooms.get("school_id"); -// buildingAssetService.editRoom(room_type, room_num, building_id, floors_id, school_id, room_id); -// return "Rooms Edited Sucessfully"; -// } catch (Exception e) { -// e.printStackTrace(); -// return "error"; -// } -// } - - // vishnu edit room - @PostMapping(value = "/editRoom") - public String editRoom(@RequestBody Map rooms) { - try { - if (rooms.get("room_id") == null || rooms.get("building_id") == null || rooms.get("floors_id") == null - || rooms.get("room_type") == null || rooms.get("room_num") == null - || rooms.get("school_id") == null) { - - return "Missing required fields"; - } - - int room_id = Integer.parseInt(rooms.get("room_id").toString()); - int building_id = Integer.parseInt(rooms.get("building_id").toString()); - int floors_id = Integer.parseInt(rooms.get("floors_id").toString()); - int room_type = Integer.parseInt(rooms.get("room_type").toString()); - String room_num = rooms.get("room_num").toString(); - int school_id = Integer.parseInt(rooms.get("school_id").toString()); - String anganwadiUniqueNumber = rooms.get("anganwadiUniqueNumber") != null - ? rooms.get("anganwadiUniqueNumber").toString().trim() - : null; - - Boolean anganwadi_check = rooms.get("anganwadi_check") != null ? Boolean.parseBoolean(rooms.get("anganwadi_check").toString()) : null; - - return buildingAssetService.editRoomsById(room_type, room_num, building_id, floors_id, school_id,anganwadiUniqueNumber,anganwadi_check, room_id); - - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - // For Delete Room mapping - /* - * @PostMapping(value = "/deleteRoom") public String deleteRoom(@RequestParam - * int room_id, @RequestParam boolean is_delete) { try { // // from assets // - * List> assets = buildingAssetService.getAssets(room_id); - * // if(!assets.isEmpty()) { // for(Map asset : assets) { // // - * } // } buildingAssetService.deleteRoom(room_id, is_delete); return - * "Rooms Edited Sucessfully"; } catch (Exception e) { e.printStackTrace(); - * return "error"; } } - */ -//vishnu - - @GetMapping("/getBuildingbyid") - public ResponseEntity> getSimpleBuilding(@RequestParam int building_id) { - try { - Map building = buildingAssetService.getSimpleBuildingById(building_id); - if (building != null) { - return ResponseEntity.ok(Map.of("status", "OK", "data", building)); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(Map.of("status", "Failed", "message", "Building not found")); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Something went wrong")); - } - } - - @GetMapping("/getAllMaterials") - public ResponseEntity> getAllMaterials() { - try { - Map>> materials = buildingAssetService.getAllMaterials(); - - return ResponseEntity.ok(Map.of("status", "OK", "buildingMaterials", materials.get("buildingMaterials"), - "roofMaterials", materials.get("roofMaterials"))); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Failed to load material data")); - } - } - - @GetMapping("/getFloorsByBuildingId") - public ResponseEntity> getFloorsByBuildingId(@RequestParam int buildingId) { - try { - List> floors = buildingAssetService.getFloorsByBuildingId(buildingId); - - return ResponseEntity.ok(Map.of("status", "OK", "floors", floors)); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Could not load floor list")); - } - } - - @PostMapping(value = "/deleteBuilding") - public String deleteBuilding(@RequestParam int building_id, @RequestParam boolean is_delete) { - - return buildingAssetService.executeDelete(building_id, is_delete); - - } - - @PostMapping(value = "/deleteRoom") - public String deleteRoom(@RequestParam int room_id, @RequestParam boolean is_delete) { - try { - // from assets - List asset_ID = buildingAssetService.getassetRoomID(room_id); - List> electrical_asset = buildingAssetService.getElectricalAssetMasterByRoomId(room_id); - List> furniture_asset = buildingAssetService.getFurnitureAssetMasterByRoomId(room_id); - for (Integer it_details_id : asset_ID) { - buildingAssetService.unmapItAssetMaster(it_details_id); - } - for (Map ele_data : electrical_asset) { - int school_id = (Integer) ele_data.get("school_id"); - int sub_asset_id = (Integer) ele_data.get("sub_asset_id"); - int asset_qty = (Integer) ele_data.get("asset_qty"); - String assetType = "electricalasset"; - Map assetMaster = buildingAssetService.getAssetMasterBySchlId(sub_asset_id, school_id, - assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int map = mapped - asset_qty; - int unMap = unMapped + asset_qty; - buildingAssetService.updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - for (Map fur_data : furniture_asset) { - int school_id = (Integer) fur_data.get("school_id"); - int sub_asset_id = (Integer) fur_data.get("sub_asset_id"); - int asset_qty = (Integer) fur_data.get("asset_qty"); - String assetType = "furnitureasset"; - Map assetMaster = buildingAssetService.getAssetMasterBySchlId(sub_asset_id, school_id, - assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int map = mapped - asset_qty; - int unMap = unMapped + asset_qty; - buildingAssetService.updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - buildingAssetService.unmapAssets(room_id, is_delete); - buildingAssetService.deleteRoom(room_id, is_delete); - return "Rooms Edited Sucessfully"; - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - @PostMapping(value = "/editBuildings") - public String editBuilding(@RequestParam int building_id, @RequestParam int floor_id) { - - return buildingAssetService.editBuildings(building_id, floor_id); - } - - @PostMapping(value = "/addFloor") - public String addFloor(@RequestParam int building_id, @RequestParam int exe_order) { - return buildingAssetService.addFloor(building_id, exe_order); - } - - @PostMapping(value = "/updateBuilding") - public String updateBuilding(@RequestParam int building_id, @RequestParam String building_name, - @RequestParam int total_floor, @RequestParam String building_material, @RequestParam String roof_material, - @RequestParam int school_id) { - try { - buildingAssetService.updateBuilding(building_id, building_name, total_floor, building_material, - roof_material, school_id); - return "Success"; - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - @GetMapping("/getRoomDetails") - public ResponseEntity> getRoomDetails(@RequestParam int school_id) { - try { - List> data = buildingAssetService.getRoomDetailsBySchoolId(school_id); - Map response = new HashMap<>(); - - if (data != null && !data.isEmpty()) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error fetching room details: " + e.getMessage())); - } - } - - @GetMapping("/getRoomById") - public ResponseEntity> getRoomById(@RequestParam int room_id) { - try { - Map room = buildingAssetService.getRoomDetailsById(room_id); - return ResponseEntity.ok(Map.of("status", "OK", "data", room)); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "ERROR", "data", "Room not found")); - } - } - - @GetMapping(value = "/getItAssetMapping") - public ResponseEntity> getItAssetMapping(int room_id, String assetType) { - Map response = new HashMap<>(); - List> data = buildingAssetService.getItAssetMapping(room_id, assetType); - response.put("Status", "OK"); - response.put("data", data); - return ResponseEntity.ok(response); - - } - - @PostMapping(value = "/deleteAssetMapping") - public ResponseEntity> deleteAssetMapping(int it_map_id, boolean is_delete) { - Map response = new HashMap<>(); - Map it_Details = buildingAssetService.getIt_Details(it_map_id); - int it_details_id = (Integer) it_Details.get("it_details_id"); - String data = buildingAssetService.deleteAssetMapping(it_map_id, is_delete); - buildingAssetService.unmapItAssetMaster(it_details_id); - response.put("status", "Sucess"); - response.put("data", data); - return ResponseEntity.ok(response); - - } - - // For update assets - @PostMapping(value = "/updateassets") - public String updateassets(@RequestBody List> assets) { - return buildingAssetService.updateAssetExecution(assets); - } - - @GetMapping(value = "/getSchoolAsset") - public ResponseEntity> getSchoolAsset(@RequestParam int school_id, @RequestParam String type) { - Map response = new HashMap<>(); - List> data = buildingAssetService.getSchoolAsset(school_id, type); - if (!data.isEmpty()) { - response.put("status", "Success"); - response.put("data", data); - } else { - response.put("status", "Error"); - } - return ResponseEntity.ok(response); - } - - @PostMapping(value = "/mapAssets") - public String mapAssets(@RequestBody List> assets) { - try { - for (Map asset : assets) { - int room_id = Integer.parseInt(asset.get("room_id").toString()); - int floor_id = Integer.parseInt(asset.get("floor_id").toString()); - int school_id = Integer.parseInt(asset.get("school_id").toString()); - int it_details_id = Integer.parseInt(asset.get("it_details_id").toString()); - int building_id = Integer.parseInt(asset.get("building_id").toString()); - buildingAssetService.mapAssets(room_id, floor_id, school_id, it_details_id, building_id); - } - return "Success"; - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - - } - - @PostMapping(value = "/addFurAsset") - public String addFurAsset(@RequestParam int sub_asset_id, @RequestParam int asset_qty, @RequestParam int room_id, - @RequestParam int building_id, @RequestParam int floor_id, @RequestParam int school_id, - @RequestParam String assetType) { - - return buildingAssetService.assetUpdation(asset_qty, assetType, sub_asset_id, school_id, room_id, building_id, - floor_id); - } - - // Asset Management - - @GetMapping(value = "/getAssetManagement") - public ResponseEntity> getSchoolAssetForManagement(@RequestParam int school_id) { - Map response = new HashMap<>(); - List> data = buildingAssetService.getSchoolAssetForManagement(school_id); - if (!data.isEmpty()) { - response.put("status", "Sucess"); - response.put("data", data); - } else { - response.put("status", "Error"); - } - return ResponseEntity.ok(response); - } - - @PostMapping(value = "/addAsset") - public String addAsset(@RequestParam String code, @RequestParam String name, @RequestParam String source, - @RequestParam String serialNum, @RequestParam String vendorDetail, @RequestParam String invoice_num, - @RequestParam String udise, @RequestParam boolean is_online, @RequestParam int school_id) { - try { - int count = buildingAssetService.getAssetCount(udise, is_online); - String assetCode = ""; - if (count >= 0) { - String series = String.format("%04d", count + 1); - String school = String.format("%03d", school_id); - assetCode = code + school + series; - - } else { - return "Error"; - } - return buildingAssetService.addAsset(assetCode, name, source, serialNum, vendorDetail, invoice_num, udise, - is_online); - - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - - } - - @GetMapping(value = "/getAssets") - public ResponseEntity> getAssets(@RequestParam int it_details_id) { - Map response = new HashMap<>(); - Map data = buildingAssetService.getAssets(it_details_id); - if (!data.isEmpty()) { - response.put("status", "Success"); - response.put("data", data); - } else { - response.put("Status", "Error"); - } - return ResponseEntity.ok(response); - } - - @PostMapping(value = "/editAsset") - public String editAsset(@RequestParam String assetCode, @RequestParam String name, @RequestParam String source, - @RequestParam String serialNum, @RequestParam String vendorDetail, @RequestParam String invoice_num, - @RequestParam int it_details_id) { - try { - - return buildingAssetService.editAsset(assetCode, name, source, serialNum, vendorDetail, invoice_num, - it_details_id); - - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - - } - - @GetMapping("/getStudentStrengthBySchoolId") - public ResponseEntity> getStudentStrengthBySchoolId(@RequestParam int schoolId) { - try { - List> studentStrength = buildingAssetService.getStudentStrengthBySchoolId(schoolId); - - if (!studentStrength.isEmpty()) { - return ResponseEntity.ok(Map.of("status", "OK", "studentStrength", studentStrength)); - } else { - return ResponseEntity.ok(Map.of("status", "NEW", "studentStrength", studentStrength)); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Could not load student strength data")); - } - } - - @GetMapping("/getotherdetailsBySchoolId") - public ResponseEntity> getotherdetailsBySchoolId(@RequestParam int schoolId) { - try { - List> getotherdetailsBySchool = buildingAssetService - .getotherdetailsBySchoolId(schoolId); - - if (!getotherdetailsBySchool.isEmpty()) { - return ResponseEntity.ok(Map.of("status", "OK", "otherdetailsBySchool", getotherdetailsBySchool)); - } else { - return ResponseEntity.ok(Map.of("status", "NEW", "otherdetailsBySchool", getotherdetailsBySchool)); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Could not load student strength data")); - } - } - - @GetMapping("/getStaffStrengthBySchoolId") - public ResponseEntity> getStaffStrengthBySchoolId(@RequestParam int schoolId) { - try { - List> staffStrength = buildingAssetService.getStaffStrengthBySchoolId(schoolId); - List> special_category = buildingAssetService.getSpecialCategoryBySchoolId(schoolId); - - if (!staffStrength.isEmpty()) { - return ResponseEntity.ok(Map.of("status", "OK", "staffStrength", staffStrength,"special_category",special_category)); - } else { - return ResponseEntity.ok(Map.of("status", "NEW", "staffStrength", staffStrength,"special_category",special_category)); - } - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Could not load student strength data")); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/DropdownsController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/DropdownsController.java deleted file mode 100644 index b5d8f0e1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/DropdownsController.java +++ /dev/null @@ -1,500 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Controller; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import in.gov.chennaicorporation.gccoffice.school.Service.DropdownsService; - -@RestController -@RequestMapping("/gcc/api/gccschool/dropdown") -public class DropdownsController { - @Autowired - private DropdownsService dropdownsService; - - @Autowired - public DropdownsController(DropdownsService dropdownsService) { - this.dropdownsService = dropdownsService; - } - - // To Get Court Dropdown Data - @GetMapping("/getCourtData") - public ResponseEntity> getCourtData() { - try { - List> data = dropdownsService.getCourtData(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Equipmengt Dropdown Data - @GetMapping("/getEquipmentData") - public ResponseEntity> getEquipmentData() { - try { - List> data = dropdownsService.getEquipmentData(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Building Material Dropdown Data - @GetMapping("/getBuildingMaterial") - public ResponseEntity> getBuildingMaterial() { - try { - List> data = dropdownsService.getBuildingMaterial(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Roof Material Dropdown Data - @GetMapping("/getRoofMaterial") - public ResponseEntity> getRoofMaterial() { - try { - List> data = dropdownsService.getRoofMaterial(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Water Source Dropdown Data - @GetMapping("/getWaterSource") - public ResponseEntity> getWaterSource() { - try { - List> data = dropdownsService.getWaterSource(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Water Storage Dropdown Data - @GetMapping("/getWaterStorage") - public ResponseEntity> getWaterStorage() { - try { - List> data = dropdownsService.getWaterStorage(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Rooms Dropdown Data - @GetMapping("/getRooms") - public ResponseEntity> getRooms() { - try { - List> data = dropdownsService.getRooms(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - @GetMapping("/getFloorsByBuilding") - public ResponseEntity> getFloorsByBuilding(@RequestParam("building_id") int buildingId) { - try { - List> data = dropdownsService.getFloorsByBuilding(buildingId); - Map response = new HashMap<>(); - if (!data.isEmpty()) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No floors found for the selected building."); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Failed to fetch floors.")); - } - } - - @GetMapping("/getBuildingsBySchoolId") - public ResponseEntity> getBuildingsBySchoolId(@RequestParam int school_id) { - try { - List> data = dropdownsService.getBuildingsBySchoolId(school_id); - Map response = new HashMap<>(); - if (!data.isEmpty()) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No buildings found for the selected school."); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Failed to fetch buildings.")); - } - } - - @GetMapping("/getDropdownValues") - public List> getDropdownValues(@RequestParam String user_id) { - List> resultList = new ArrayList<>(); - Map response = new HashMap<>(); - - String schoolId = dropdownsService.getSchoolId(user_id); - if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) { - response.put("Message", "Failure"); - response.put("Data", List.of()); - resultList.add(response); - return resultList; - } - - List> udiseData = dropdownsService.getUdiseNumbersBySchoolId(schoolId); - if (!udiseData.isEmpty()) { - List udiseList = udiseData.stream().map(m -> (String) m.get("udise")).collect(Collectors.toList()); - - response.put("Message", "Success"); - response.put("Data", udiseList); - } else { - response.put("Message", "No Data Found"); - response.put("Data", List.of()); - } - - resultList.add(response); - return resultList; - } - - @GetMapping("/getCategoryValues") - public List> getCategoryValues(@RequestParam String user_id) { - List> resultList = new ArrayList<>(); - Map response = new HashMap<>(); - - String schoolId = dropdownsService.getSchoolId(user_id); - if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) { - response.put("Message", "Failure"); - response.put("Data", List.of()); - resultList.add(response); - return resultList; - } - - List> categoryData = dropdownsService.getCategoryBySchoolId(schoolId); - if (!categoryData.isEmpty()) { - List categoryList = categoryData.stream().map(m -> (String) m.get("category")) - .collect(Collectors.toList()); - - response.put("Message", "Success"); - response.put("Data", categoryList); - } else { - response.put("Message", "No Data Found"); - response.put("Data", List.of()); - } - - resultList.add(response); - return resultList; - } - - @GetMapping("/getZoneValues") - public List> getZoneValues(@RequestParam String user_id) { - List> resultList = new ArrayList<>(); - Map response = new HashMap<>(); - - String schoolId = dropdownsService.getSchoolId(user_id); - if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) { - response.put("Message", "Failure"); - response.put("Data", List.of()); - resultList.add(response); - return resultList; - } - - List> zoneData = dropdownsService.getZoneBySchoolId(schoolId); - if (!zoneData.isEmpty()) { - List zoneList = zoneData.stream().map(m -> (String) m.get("zone")).collect(Collectors.toList()); - - response.put("Message", "Success"); - response.put("Data", zoneList); - } else { - response.put("Message", "No Data Found"); - response.put("Data", List.of()); - } - - resultList.add(response); - return resultList; - } - - @GetMapping("/getwardValues") - public List> getWardValues(@RequestParam String user_id) { - List> resultList = new ArrayList<>(); - Map response = new HashMap<>(); - - String schoolId = dropdownsService.getSchoolId(user_id); - if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) { - response.put("Message", "Failure"); - response.put("Data", List.of()); - resultList.add(response); - return resultList; - } - - List> wardData = dropdownsService.getWardBySchoolId(schoolId); - if (!wardData.isEmpty()) { - List wardList = wardData.stream().map(m -> (String) m.get("division")).collect(Collectors.toList()); - - response.put("Message", "Success"); - response.put("Data", wardList); - } else { - response.put("Message", "No Data Found"); - response.put("Data", List.of()); - } - - resultList.add(response); - return resultList; - } - - @GetMapping("/getAllDropdownValues") - public ResponseEntity getAllDropdownValues(@RequestParam String user_id, @RequestParam String type) { - Map response = new HashMap<>(); - List dropdownList = Collections.emptyList(); - - // First get school_id(s) for this user - String schoolId = dropdownsService.getSchoolId(user_id); - - if (schoolId.equals("error")) { - response.put("Message", "Failed to fetch school ID"); - response.put("Data", dropdownList); - return ResponseEntity.ok(Collections.singletonList(response)); - } - - try { - List> rawData; - - switch (type.toLowerCase()) { - case "udise": - rawData = dropdownsService.getUdiseNumbersBySchoolId(schoolId); - dropdownList = rawData.stream().map(map -> String.valueOf(map.get("udise"))) - .collect(Collectors.toList()); - break; - case "category": - rawData = dropdownsService.getCategoryBySchoolId(schoolId); - dropdownList = rawData.stream().map(map -> String.valueOf(map.get("category"))).distinct() - .collect(Collectors.toList()); - break; - case "zone": - rawData = dropdownsService.getZoneBySchoolId(schoolId); - dropdownList = rawData.stream().map(map -> String.valueOf(map.get("zone"))).distinct() - .collect(Collectors.toList()); - break; - case "ward": - rawData = dropdownsService.getWardBySchoolId(schoolId); - dropdownList = rawData.stream().map(map -> String.valueOf(map.get("division"))).distinct() - .collect(Collectors.toList()); - break; - default: - response.put("Message", "Invalid dropdown type"); - response.put("Data", dropdownList); - return ResponseEntity.badRequest().body(Collections.singletonList(response)); - } - - response.put("Message", "Success"); - response.put("Data", dropdownList); - return ResponseEntity.ok(Collections.singletonList(response)); - } catch (Exception e) { - e.printStackTrace(); - response.put("Message", "Error while processing dropdown values"); - response.put("Data", dropdownList); - return ResponseEntity.ok(Collections.singletonList(response)); - } - } - - // To Get Asset Types Data - @GetMapping("/getAssetType") - public ResponseEntity> getAssetType() { - try { - List> data = dropdownsService.getAssetType(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - // To Get Sub Asset Types Data - @GetMapping("/getSubAssetType") - public ResponseEntity> getSubAssetType(int assetid) { - try { - List> data = dropdownsService.getSubAssetType(assetid); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - - e.printStackTrace(); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - @GetMapping("/getSplSubAssetType") - public ResponseEntity> getSplSubAssetType(int school_id, int assetid) { - try { - List assets = dropdownsService.getAssetList(school_id, assetid); - List> data = dropdownsService.getSplSubAssetType(assets, assetid); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - - e.printStackTrace(); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - - @GetMapping("/getSpecialCategory") - public ResponseEntity> getSpecialCategory() { - try { - List> data = dropdownsService.getSpecialCategory(); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/MainController.java deleted file mode 100644 index 3da528ab..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/MainController.java +++ /dev/null @@ -1,140 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@Controller("schoolcontroller") -@RequestMapping("/gcc/school") -public class MainController { - - @GetMapping("/otherdetails") - public String otherdetails(Model model) { - - return "modules/school/otherdetails"; - } - - @GetMapping("/schooldetails") - public String viewschool(Model model) { - return "modules/school/schooldetails"; - } - - @GetMapping("/schoolmodule") - public String viewmodule(Model model) { - String loginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("user_id", loginUserId); - System.out.println("loginUserId..........." + loginUserId); - return "modules/school/dashboard"; - } - - @GetMapping("/staffdetails") - public String staffdetails(Model model) { - return "modules/school/staffdetails"; - } - - @GetMapping("/roomassets") - public String roomassets(Model model) { - - return "modules/school/roomassets"; - } - - @GetMapping("/assetmanagement") - public String assetmanagement(Model model) { - - return "modules/school/assetmanagement"; - } - - - @GetMapping("/studentdetails") - public String studentdetails(Model model) { - - return "modules/school/studentdetails"; - } - - @GetMapping("/building") - public String buildings(Model model) { - - return "modules/school/building"; - } - - @GetMapping("/room") - public String roomlist(Model model) { - - return "modules/school/room"; - } - - @GetMapping("/playground") - public String playground(Model model) { - - return "modules/school/playground"; - } - - @GetMapping("/drinkingwater") - public String drinkingwater(Model model) { - - return "modules/school/drinkingwater"; - } - - @GetMapping("/toilets") - public String toilet(Model model) { - - return "modules/school/toilets"; - } - -// @GetMapping("/electricalassets") -// public String electricalassets(Model model) { -// -// return "modules/school/electricalassets"; -// } -// -// @GetMapping("/furnitureassets") -// public String furnitureassets(Model model) { -// -// return "modules/school/furnitureassets"; -// } - - @GetMapping("/kitchen") - public String kitchen(Model model) { - - return "modules/school/kitchen"; - } - - @GetMapping("/addelectricalasset") - public String addelectricalasset(Model model) { - - return "modules/school/addelectricalasset"; - } - - @GetMapping("/addfurnitureasset") - public String addfurnitureasset(Model model) { - - return "modules/school/addfurnitureasset"; - } - @GetMapping("/reports") - public String reportpage(Model model) { - - return "modules/school/reports"; - } - - @GetMapping("/studentregistration") - public String studentRegistrationPage() { - - return "modules/school/studentregister"; - } - - @GetMapping("/aeoschoolentry/aeolist") - public String viewaeolist(Model model) { - - return "modules/school/reportfolder/aeolist"; - } - - - @GetMapping("/aeoschoolentry/aeoallschools") - public String viewaeoallschools(Model model) { - - return "modules/school/reportfolder/aeoallschools"; - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolPropertyController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolPropertyController.java deleted file mode 100644 index 556d108d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolPropertyController.java +++ /dev/null @@ -1,1018 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Controller; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.CrossOrigin; -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 in.gov.chennaicorporation.gccoffice.school.Service.SchoolPropertyService; - -@RestController -@CrossOrigin() -@RequestMapping("/gcc/api/gccschool/schoolproperty") -public class SchoolPropertyController { - - @Autowired - private SchoolPropertyService schoolPropertyService; - - @Autowired - public SchoolPropertyController(SchoolPropertyService schoolPropertyService) { - this.schoolPropertyService = schoolPropertyService; - } - - // To Get School Data - @GetMapping("/getSchoolData") - public ResponseEntity> getSchoolData(@RequestParam String udise) { - try { - List> data = schoolPropertyService.getSchoolData(udise); - Map response = new HashMap<>(); - if (data.size() != 0) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - return ResponseEntity.ok(response); - } catch (Exception e) { - // Log the exception details for debugging - e.printStackTrace(); - - // Provide a user-friendly error message - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage())); - } - } - -// For Other Details - @PostMapping(value = "/saveSchoolBuildupArea") - public String saveSchoolBuildupArea(@RequestParam("land_area") Double land_area, - @RequestParam("buildup_area") Double buildup_area, @RequestParam("is_compound") int is_compound, - @RequestParam("is_nameboard") Boolean is_nameboard, @RequestParam("is_pasystem") Boolean is_pasystem, - @RequestParam("is_bell") Boolean is_bell, @RequestParam("is_generator") Boolean is_generator, - @RequestParam("school_id") int school_id) { - - return schoolPropertyService.saveSchoolBuildupArea(land_area, buildup_area, is_compound, is_nameboard, - is_pasystem, is_bell, is_generator, school_id); - } - -// For Student Strength - @PostMapping(value = "/saveStudentStrength") - public String saveStudentStrength(@RequestParam("total_students") int total_students, - @RequestParam("total_girls") int total_girls, @RequestParam("total_boys") int total_boys, - @RequestParam("others") int others, @RequestParam("special_child") int special_child,@RequestParam("school_id") int school_id) { - - return schoolPropertyService.saveStudentStrength(total_students, total_girls, total_boys, others,special_child, school_id); - } - -// For Staff Strength -// @PostMapping(value="/saveStaffStrength") -// public String saveStaffStrength( -// @RequestParam("tot_staff") int tot_staff, -// @RequestParam("sg_staff") int sg_staff, -// @RequestParam("bt_staff") int bt_staff, -// @RequestParam("pg_staff") int pg_staff, -// @RequestParam("temp_staff") int temp_staff, -// @RequestParam("ngo_staff") int ngo_staff, -// @RequestParam("kg_staff") int kg_staff, -// @RequestParam("pt_staff") int pt_staff, -// @RequestParam("part_staff") int part_staff, -// @RequestParam("qa_staff") int qa_staff, -// @RequestParam("kg_ayha") int kg_ayha, -// @RequestParam("watchman") int watchman, -// @RequestParam("comp_asst") int comp_asst, -// @RequestParam("scavengers") int scavengers, -// @RequestParam("maint_workers") int maint_workers, -// @RequestParam("school_id") int school_id) { -// -// return schoolPropertyService.saveStaffStrength(tot_staff, sg_staff, bt_staff,pg_staff, temp_staff, ngo_staff, kg_staff, pt_staff,part_staff, qa_staff, kg_ayha, watchman, comp_asst, scavengers, maint_workers, school_id); -// } - -// For Toilets - @PostMapping(value = "/saveToilets") - public String saveToilets(@RequestParam(value = "total_toiletBlocks", required = false) Integer total_toiletBlocks, - @RequestParam("total_male_urinals") int total_male_urinals, - @RequestParam("total_female_urinals") int total_female_urinals, - @RequestParam("staff_male_toilets") int staff_male_toilets, - @RequestParam("staff_female_toilets") int staff_female_toilets, - @RequestParam("total_wc_male") int total_wc_male, @RequestParam("total_wc_female") int total_wc_female, - @RequestParam("total_diffAbled_toilet") int total_diffAbled_toilet, - @RequestParam("is_napkins") Boolean is_napkins, @RequestParam("school_id") int school_id) { - - return schoolPropertyService.saveToilets(total_toiletBlocks, total_male_urinals, total_female_urinals,staff_male_toilets,staff_female_toilets,total_wc_male, total_wc_female, - total_diffAbled_toilet, is_napkins, school_id); - } - -// For Kitchen - @PostMapping(value = "/saveKitchen") - public ResponseEntity> saveKitchen(@RequestBody Map payload) { - Map response = new HashMap<>(); - try { - Boolean is_cmbfs = payload.get("is_cmbfs") != null ? Boolean.parseBoolean(payload.get("is_cmbfs").toString()) : null; - Boolean is_cmbfsIndividual = payload.get("is_cmbfsIndividual") != null ? Boolean.parseBoolean(payload.get("is_cmbfsIndividual").toString()) : null; - Boolean is_noonmeal = payload.get("is_noonmeal") != null ? Boolean.parseBoolean(payload.get("is_noonmeal").toString()) : null; - Boolean is_noonIndividual = payload.get("is_noonIndividual") != null ? Boolean.parseBoolean(payload.get("is_noonIndividual").toString()) : null; - Boolean is_vegGarden = payload.get("is_vegGarden") != null ? Boolean.parseBoolean(payload.get("is_vegGarden").toString()) : null; - Boolean is_anganwadi = payload.get("is_anganwadi") != null ? Boolean.parseBoolean(payload.get("is_anganwadi").toString()) : null; - - List> anganwadi = (List>) payload.get("anganwadi"); - - //System.out.println("anganwadi="+ anganwadi); - - int school_id = Integer.parseInt(payload.get("school_id").toString()); - - - int kitchen_id = schoolPropertyService.saveKitchen(is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, - is_vegGarden, is_anganwadi, school_id); - - if(is_anganwadi) { - for(Map data:anganwadi) { - //System.out.println("hi"); - String anganwadi_unique = data.get("anganwadi_unique")!= null ? data.get("anganwadi_unique").toString() : null; - Boolean is_anganwadiIndividual = data.get("is_anganwadiIndividual") != null ? Boolean.parseBoolean(data.get("is_anganwadiIndividual").toString()) : null; - //System.out.printf(anganwadi_unique,is_anganwadiIndividual); - schoolPropertyService.saveAnganwadi(anganwadi_unique, is_anganwadiIndividual, kitchen_id, school_id); - schoolPropertyService.updateAnganwadiCheck(anganwadi_unique, school_id); - } - } - - response.put("status", "OK"); - response.put("message", "Kitchen Details saved successfully"); - return ResponseEntity.ok(response); - - }catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Failed to save Kitchen details"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - -// For Playground - /*@PostMapping(value = "/savePlayground") - public ResponseEntity> savePlayground(@RequestBody Map payload) { - Map response = new HashMap<>(); - try { - Boolean is_playground = (Boolean) payload.get("is_playground"); - Double playground_area = Double.valueOf(payload.get("playground_area").toString()); - Boolean is_court = (Boolean) payload.get("is_court"); - int school_id = Integer.parseInt(payload.get("school_id").toString()); - // Boolean is_active = (Boolean) payload.get("is_active"); - - List equipmentidRaw = (List) payload.get("equipmentid"); - List courtidRaw = (List) payload.get("courtid"); - - // Convert string IDs to integers -// List equipmentid = equipmentidRaw.stream().map(Integer::parseInt).toList(); -// List courtid = courtidRaw.stream().map(Integer::parseInt).toList(); - - int playground_id = schoolPropertyService.savePlayground(is_playground, playground_area, is_court, - school_id); - - for (String equipment_id : equipmentidRaw) { - schoolPropertyService.saveEquipmentDetails(equipment_id, school_id, playground_id); - } - - for (String court_id : courtidRaw) { - schoolPropertyService.saveCourtDetails(court_id, school_id, playground_id); - } - - response.put("status", "OK"); - response.put("message", "Playground Details saved successfully"); - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Failed to save playground details"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - }*/ - @PostMapping("/savePlayground") - public ResponseEntity> savePlayground(@RequestBody Map payload) { - Map response = new HashMap<>(); - try { - Boolean is_playground = (Boolean) payload.get("is_playground"); - Double playground_area = Double.valueOf(payload.get("playground_area").toString()); - Boolean is_court = (Boolean) payload.get("is_court"); - int school_id = Integer.parseInt(payload.get("school_id").toString()); - - List equipmentidRaw = (List) payload.get("equipmentid"); - List courtidRaw = (List) payload.get("courtid"); - - int playground_id = schoolPropertyService.savePlayground(is_playground, playground_area, is_court, school_id); - - boolean insertedAny = false; - - for (String equipment_id : equipmentidRaw) { - if (schoolPropertyService.saveEquipmentDetails(equipment_id, school_id, playground_id)) { - insertedAny = true; - } - } - - for (String court_id : courtidRaw) { - if (schoolPropertyService.saveCourtDetails(court_id, school_id, playground_id)) { - insertedAny = true; - } - } - - if (insertedAny) { - response.put("status", "OK"); - response.put("message", "Playground and related details saved successfully"); - } else { - response.put("status", "SKIPPED"); - response.put("message", "No new data inserted; records already exist"); - } - - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Failed to save playground details"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - -//initial - // For Drinking Water - /*@PostMapping(value = "/saveDrinkingWater") - public ResponseEntity> saveDrinkingWater(@RequestBody Map requestData) { - try { - // Extract data from the map - List> water = (List>) requestData.get("water"); - Boolean is_purifier = "1".equals(requestData.get("is_purifier")); - Double purifier_capacity = requestData.get("purifier_capacity") != null - ? Double.valueOf(requestData.get("purifier_capacity").toString()) - : null; - Boolean is_borewell = "1".equals(requestData.get("is_borewell")); - Integer borewell_count = requestData.get("borewell_count") != null - ? Integer.valueOf(requestData.get("borewell_count").toString()) - : null; - Boolean is_storage = "1".equals(requestData.get("is_storage")); - List> storage = (List>) requestData.get("storage"); - int school_id = Integer.parseInt(requestData.get("school_id").toString()); - - Map response = new HashMap<>(); - - int drinking_water_id = schoolPropertyService.saveDrinkingWater(is_purifier, purifier_capacity, is_borewell, - borewell_count, is_storage, school_id); - for (Map waterSupply : water) { - int source_water_id = (int) waterSupply.get("source_water_id"); - String supply_type = (String) waterSupply.get("supply_type"); - schoolPropertyService.saveWaterSupply(source_water_id, supply_type, drinking_water_id, school_id); - } - if (!storage.isEmpty()) { - for (Map waterStorage : storage) { - double capacity = Double.valueOf(waterStorage.get("capacity").toString()); - int storage_water_id = (int) waterStorage.get("storage_water_id"); - schoolPropertyService.saveWaterStorage(capacity, storage_water_id, drinking_water_id, school_id); - } - } - - response.put("status", "OK"); - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error saving data: " + e.getMessage())); - } - }*/ - @PostMapping("/saveDrinkingWater") - public ResponseEntity> saveDrinkingWater(@RequestBody Map requestData) { - Map response = new HashMap<>(); - try { - int schoolId = Integer.parseInt(requestData.get("school_id").toString()); - - // Check if data already exists for the school - boolean exists = schoolPropertyService.existsDrinkingWaterData(schoolId); - - if (exists) { - // If data exists, respond with SKIPPED status and message - response.put("status", "SKIPPED"); - response.put("message", "Data already exists for this school. Insert skipped."); - return ResponseEntity.ok(response); - } - - // If no existing data, proceed with your save logic - List> water = (List>) requestData.get("water"); - Boolean is_purifier = "1".equals(requestData.get("is_purifier")); - Double purifier_capacity = requestData.get("purifier_capacity") != null - ? Double.valueOf(requestData.get("purifier_capacity").toString()) - : null; - Boolean is_borewell = "1".equals(requestData.get("is_borewell")); - Integer borewell_count = requestData.get("borewell_count") != null - ? Integer.valueOf(requestData.get("borewell_count").toString()) - : null; - - int drinkingwater_tap = requestData.get("drinkingwater_tap") != null - ? Integer.valueOf(requestData.get("drinkingwater_tap").toString()) - : null; - int handwash_tap = requestData.get("handwash_tap") != null - ? Integer.valueOf(requestData.get("handwash_tap").toString()) - : null; - - Boolean is_storage = "1".equals(requestData.get("is_storage")); - List> storage = (List>) requestData.get("storage"); -/* - int drinking_water_id = schoolPropertyService.saveDrinkingWater(is_purifier, purifier_capacity, is_borewell, - borewell_count, is_storage, schoolId); - */ - int drinking_water_id = schoolPropertyService.saveDrinkingWater(is_purifier, purifier_capacity, is_borewell, - borewell_count, is_storage, schoolId,drinkingwater_tap,handwash_tap); - - for (Map waterSupply : water) { - int source_water_id = (int) waterSupply.get("source_water_id"); - String supply_type = (String) waterSupply.get("supply_type"); - schoolPropertyService.saveWaterSupply(source_water_id, supply_type, drinking_water_id, schoolId); - } - if (!storage.isEmpty()) { - for (Map waterStorage : storage) { - double capacity = Double.valueOf(waterStorage.get("capacity").toString()); - int storage_water_id = (int) waterStorage.get("storage_water_id"); - schoolPropertyService.saveWaterStorage(capacity, storage_water_id, drinking_water_id, schoolId); - } - } - - response.put("status", "OK"); - response.put("message", "Drinking water details submitted successfully!"); - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Error saving data: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - //initial - - /*@PostMapping("/saveStaffStrength") - public String saveStaffStrength(@RequestParam int sgRegTeacher, @RequestParam int sgTempTeacher, - @RequestParam int sgPtTeacher, @RequestParam int sgNgoTeacher, @RequestParam int btRegTeacher, - @RequestParam int btTempTeacher, @RequestParam int btPtTeacher, @RequestParam int btNgoTeacher, - @RequestParam int pgRegTeacher, @RequestParam int pgTempTeacher, @RequestParam int pgPtTeacher, - @RequestParam int pgNgoTeacher, @RequestParam int kgRegTeacher, @RequestParam int kgTempTeacher, - @RequestParam int petRegTeacher, @RequestParam int petTempTeacher, @RequestParam int petGrade1Teacher, - @RequestParam int petGrade2Teacher, @RequestParam int totOa, @RequestParam int kgAyah, - @RequestParam int compAss, @RequestParam int watchmen, @RequestParam int scavengers, - @RequestParam int maintenanceWork, @RequestParam int schoolId) { - - // Call service method - schoolPropertyService.saveStaffStrength(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, - btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, totOa, - kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId); - - return "Staff strength details saved successfully!"; - }*/ - @PostMapping("/saveStaffStrength") - public String saveStaffStrength(@RequestBody Map payload) { - - int sgRegTeacher = Integer.parseInt(payload.get("sgRegTeacher").toString()); - int sgTempTeacher = Integer.parseInt(payload.get("sgTempTeacher").toString()); - int sgPtTeacher = Integer.parseInt(payload.get("sgPtTeacher").toString()); - int sgNgoTeacher = Integer.parseInt(payload.get("sgNgoTeacher").toString()); - int btRegTeacher = Integer.parseInt(payload.get("btRegTeacher").toString()); - int btTempTeacher = Integer.parseInt(payload.get("btTempTeacher").toString()); - int btPtTeacher = Integer.parseInt(payload.get("btPtTeacher").toString()); - int btNgoTeacher = Integer.parseInt(payload.get("btNgoTeacher").toString()); - int pgRegTeacher = Integer.parseInt(payload.get("pgRegTeacher").toString()); - int pgTempTeacher = Integer.parseInt(payload.get("pgTempTeacher").toString()); - int pgPtTeacher = Integer.parseInt(payload.get("pgPtTeacher").toString()); - int pgNgoTeacher = Integer.parseInt(payload.get("pgNgoTeacher").toString()); - int kgRegTeacher = Integer.parseInt(payload.get("kgRegTeacher").toString()); - int kgTempTeacher = Integer.parseInt(payload.get("kgTempTeacher").toString()); - int petRegTeacher = Integer.parseInt(payload.get("petRegTeacher").toString()); - int petTempTeacher = Integer.parseInt(payload.get("petTempTeacher").toString()); - int petGrade1Teacher = Integer.parseInt(payload.get("petGrade1Teacher").toString()); - int petGrade2Teacher = Integer.parseInt(payload.get("petGrade2Teacher").toString()); - - int petPtTeacher = Integer.parseInt(payload.get("petPtTeacher").toString()); - Boolean is_hm = (Boolean) payload.get("hmAvailability"); - int stRegTeacher = Integer.parseInt(payload.get("stRegTeacher").toString()); - int stPtTeacher = Integer.parseInt(payload.get("stPtTeacher").toString()); - - int totOa = Integer.parseInt(payload.get("totOa").toString()); - int kgAyah = Integer.parseInt(payload.get("kgAyah").toString()); - int compAss = Integer.parseInt(payload.get("compAss").toString()); - String watchmen = payload.get("watchmen").toString(); - int scavengers = Integer.parseInt(payload.get("scavengers").toString()); - int maintenanceWork = Integer.parseInt(payload.get("maintenanceWork").toString()); - int schoolId = Integer.parseInt(payload.get("schoolId").toString()); - - List specialCategoryId = (List) payload.get("specialCategoryId"); - - return schoolPropertyService.saveStaffStrength(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, - btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, petPtTeacher, - is_hm, stRegTeacher, stPtTeacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId, specialCategoryId); - - - } - - - // For login - @GetMapping(value = "/getLoginDetails") - public List> getLoginDetails(@RequestParam String user_id) { - List> schoolData = new ArrayList<>(); - Map response = new HashMap<>(); - String schoolId = schoolPropertyService.getSchoolId(user_id); - if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) { - response.put("Message", "Failure"); - response.put("Data", List.of()); - schoolData.add(response); - return schoolData; - } - List> sch = schoolPropertyService.getSchoolData1(schoolId); - if (!sch.isEmpty()) { - response.put("Message", "Success"); - response.put("Data", sch); - schoolData.add(response); - return schoolData; - } else { - response.put("Message", "No Data Found"); - response.put("Data", List.of()); - schoolData.add(response); - return schoolData; - } - } - - @GetMapping("/getSchoolDetails") - public ResponseEntity> getSchoolDetails(@RequestParam Long schoolId) { - try { - Map data = schoolPropertyService.getSchoolDetails(schoolId); - if (data != null && !data.isEmpty()) { - return ResponseEntity.ok(data); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(Map.of("status", "Failed", "message", "No school found with given ID")); - } - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", e.getMessage())); - } - } - - @GetMapping("/filterSchools") - public ResponseEntity filterSchools(@RequestParam String user_id, @RequestParam(required = false) String udise, - @RequestParam(required = false) String category, @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward) { - - List> filteredSchools = schoolPropertyService.filterSchools(user_id, udise, category, zone, - ward); - - Map result = new HashMap<>(); - result.put("Message", "Success"); - result.put("Data", filteredSchools); - - return ResponseEntity.ok(Collections.singletonList(result)); - } - - @PostMapping("/updateOtherDetails") - public String updateOtherDetails(@RequestParam("land_area") Double land_area, - @RequestParam("buildup_area") Double buildup_area, @RequestParam("is_compound") int is_compound, - @RequestParam("is_nameboard") Boolean is_nameboard, @RequestParam("is_pasystem") Boolean is_pasystem, - @RequestParam("is_bell") Boolean is_bell, @RequestParam("is_generator") Boolean is_generator, - @RequestParam("school_id") int school_id) { - try { - return schoolPropertyService.updateOtherDetails(land_area, buildup_area, is_compound, is_nameboard, - is_pasystem, is_bell, is_generator, school_id); - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - @PostMapping(value = "/updateStudentDetails") - public String updateStudentDetails(@RequestParam("total_students") int total_students, - @RequestParam("total_girls") int total_girls, @RequestParam("total_boys") int total_boys, - @RequestParam("others") int others,@RequestParam("special_child") int special_child , @RequestParam("school_id") int school_id) { - - try { - return schoolPropertyService.updateStudentDetails(total_students, total_girls, total_boys, others,special_child, - school_id); - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - @GetMapping("/checkPlaygroundDetails") - public ResponseEntity checkPlaygroundDetails(@RequestParam int school_id) { - - Map playgroundDetails = schoolPropertyService.checkPlaygroundDetails(school_id); - List> courtDetails = schoolPropertyService.checkCourtDetails(school_id); - List> equipmentDetails = schoolPropertyService.checkEquipmentDetails(school_id); - - Map result = new HashMap<>(); - result.put("Message", "Success"); - result.put("playgroundDetails", playgroundDetails); - result.put("CourtDetails", courtDetails); - result.put("EquipmentDetails", equipmentDetails); - - return ResponseEntity.ok(Collections.singletonList(result)); - } - - /* - * @PostMapping(value = "/updatePlayground") public ResponseEntity - * updatePlayground(@RequestBody Map payload) { try { Boolean - * is_playground = (Boolean) payload.get("is_playground"); Double - * playground_area = Double.valueOf(payload.get("playground_area").toString()); - * Boolean is_court = (Boolean) payload.get("is_court"); int school_id = - * Integer.parseInt(payload.get("school_id").toString()); int playground_id = - * Integer.parseInt(payload.get("playground_id").toString()); - * - * List> equipments = (List>) - * payload.get("equipments"); List> courts = - * (List>) payload.get("courts"); - * - * String result = schoolPropertyService.updatePlaygroundDetails( is_playground, - * playground_area, is_court, equipments, courts, playground_id, school_id ); - * return ResponseEntity.ok(result); - * - * } catch (Exception e) { e.printStackTrace(); return - * ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } } - */ -// @PostMapping(value = "/updatePlayground") -// public ResponseEntity> updatePlayground(@RequestBody Map payload) { -// Map response = new HashMap<>(); -// try { -// Boolean is_playground = (Boolean) payload.get("is_playground"); -// Double playground_area = Double.valueOf(payload.get("playground_area").toString()); -// Boolean is_court = (Boolean) payload.get("is_court"); -// int school_id = Integer.parseInt(payload.get("school_id").toString()); -// //Boolean is_active = (Boolean) payload.get("is_active"); -// int playground_id = Integer.parseInt(payload.get("playground_id").toString()); -// -// -// List equipmentidRaw = (List) payload.get("equipments"); -// List courtidRaw = (List) payload.get("courts"); -// -// // Convert string IDs to integers -// List equipmentid = equipmentidRaw.stream().map(Integer::parseInt).toList(); -// List courtid = courtidRaw.stream().map(Integer::parseInt).toList(); -// schoolPropertyService.deactiveCourts(school_id); -// schoolPropertyService.deactiveEquipments(school_id); -// schoolPropertyService.updatePlayground(is_playground, playground_area, is_court, school_id, playground_id); -// //int playground_id = schoolPropertyService.savePlayground(is_playground, playground_area, is_court, -// // school_id); -// -// for (Integer equipment_id : equipmentid) { -// schoolPropertyService.saveEquipmentDetails(equipment_id, school_id, playground_id); -// } -// -// for (Integer court_id : courtid) { -// schoolPropertyService.saveCourtDetails(court_id, school_id, playground_id); -// } -// -// response.put("status", "OK"); -// response.put("message", "Playground Details updated successfully"); -// return ResponseEntity.ok(response); -// -// } catch (Exception e) { -// e.printStackTrace(); -// response.put("status", "ERROR"); -// response.put("message", "Failed to updated playground details"); -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); -// } -// } - - @PostMapping(value = "/updatePlayground") - public ResponseEntity> updatePlayground(@RequestBody Map payload) { - Map response = new HashMap<>(); - try { - Boolean is_playground = (Boolean) payload.get("is_playground"); - Double playground_area = Double.valueOf(payload.get("playground_area").toString()); - Boolean is_court = (Boolean) payload.get("is_court"); - int school_id = Integer.parseInt(payload.get("school_id").toString()); - int playground_id = Integer.parseInt(payload.get("playground_id").toString()); - - List> equipmentList = (List>) payload.get("equipments"); - List> courtList = (List>) payload.get("courts"); - - String status = schoolPropertyService.updatePlaygroundDetails(is_playground, playground_area, is_court, - equipmentList, courtList, playground_id, school_id); - - response.put("status", status.equals("Success") ? "OK" : "ERROR"); - response.put("message", - status.equals("Success") ? "Playground updated successfully" : "Failed to update playground"); - - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Exception occurred during update"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - @PostMapping(value = "/updateKitchenDetails") - public ResponseEntity> updateKitchenDetails(@RequestBody Map payload) { - Map response = new HashMap<>(); - try { - - Map kitchenEdit = (Map) payload.get("kitchenEdit"); - System.err.println("kitchenEdit="+kitchenEdit); - List> oldAnganwadiEdit = (List>) payload.get("oldAnganwadiEdit"); - List> newAnganwadiEdit = (List>) payload.get("newAnganwadiEdit"); - - Boolean is_cmbfs = kitchenEdit.get("is_cmbfs") != null ? Boolean.parseBoolean(kitchenEdit.get("is_cmbfs").toString()) : null; - Boolean is_cmbfsIndividual = kitchenEdit.get("is_cmbfsIndividual") != null ? Boolean.parseBoolean(kitchenEdit.get("is_cmbfsIndividual").toString()) : null; - Boolean is_noonmeal = kitchenEdit.get("is_noonmeal") != null ? Boolean.parseBoolean(kitchenEdit.get("is_noonmeal").toString()) : null; - Boolean is_noonIndividual = kitchenEdit.get("is_noonIndividual") != null ? Boolean.parseBoolean(kitchenEdit.get("is_noonIndividual").toString()) : null; - Boolean is_vegGarden = kitchenEdit.get("is_vegGarden") != null ? Boolean.parseBoolean(kitchenEdit.get("is_vegGarden").toString()) : null; - Boolean is_anganwadi = kitchenEdit.get("is_anganwadi") != null ? Boolean.parseBoolean(kitchenEdit.get("is_anganwadi").toString()) : null; - - int school_id = kitchenEdit.get("school_id") != null ?Integer.parseInt(kitchenEdit.get("school_id").toString()) : null; - - - schoolPropertyService.updateKitchenDetails(is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden, is_anganwadi,school_id); - - if(is_anganwadi) { - - if(oldAnganwadiEdit != null) { - - for(Map oldlist:oldAnganwadiEdit) { - - String anganwadi_unique = oldlist.get("anganwadi_unique")!= null ? oldlist.get("anganwadi_unique").toString() : null; - Boolean is_anganwadiIndividual = oldlist.get("is_anganwadiIndividual") != null ? Boolean.parseBoolean(oldlist.get("is_anganwadiIndividual").toString()) : null; - schoolPropertyService.saveOldAnganwadi(anganwadi_unique, is_anganwadiIndividual, school_id); - } - - } - - if(newAnganwadiEdit != null) { - - int kitchen_id=schoolPropertyService.getKitchenIdbySchId(school_id); - - for(Map newlist:newAnganwadiEdit) { - - String new_anganwadi_unique = newlist.get("anganwadi_unique")!= null ? newlist.get("anganwadi_unique").toString() : null; - Boolean new_is_anganwadiIndividual = newlist.get("is_anganwadiIndividual") != null ? Boolean.parseBoolean(newlist.get("is_anganwadiIndividual").toString()) : null; - schoolPropertyService.saveNewAnganwadi(new_anganwadi_unique, new_is_anganwadiIndividual,kitchen_id,school_id); - schoolPropertyService.updateAnganwadiCheck(new_anganwadi_unique, school_id); - } - - } - - - } - - response.put("status", "OK"); - response.put("message", "Kitchen Details Updated successfully"); - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Failed to save Kitchen details"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - - } - - @GetMapping("/checkKitchenDetails") - public ResponseEntity checkKitchenDetails(@RequestParam int school_id) { - - Map kitchenDetails = schoolPropertyService.checkKitchenDetails(school_id); - List> oldAnganwadiDetails = schoolPropertyService.checkOldAnganwadiDetails(school_id); - List> newAnganwadiDetails = schoolPropertyService.checkNewAnganwadiDetails(school_id); - - Map result = new HashMap<>(); - result.put("Message", "Success"); - result.put("kitchenDetails", kitchenDetails); - result.put("anganwadiDetails", oldAnganwadiDetails); - result.put("newAnganwadiDetails", newAnganwadiDetails); - - return ResponseEntity.ok(Collections.singletonList(result)); - } - - @PostMapping("/updateStaffDetails") - public String updateStaffDetails(@RequestBody Map payload) { - - int sgRegTeacher = Integer.parseInt(payload.get("modal_sgRegTeacher").toString()); - int sgTempTeacher = Integer.parseInt(payload.get("modal_sgTempTeacher").toString()); - int sgPtTeacher = Integer.parseInt(payload.get("modal_sgPtTeacher").toString()); - int sgNgoTeacher = Integer.parseInt(payload.get("modal_sgNgoTeacher").toString()); - int btRegTeacher = Integer.parseInt(payload.get("modal_btRegTeacher").toString()); - int btTempTeacher = Integer.parseInt(payload.get("modal_btTempTeacher").toString()); - int btPtTeacher = Integer.parseInt(payload.get("modal_btPtTeacher").toString()); - int btNgoTeacher = Integer.parseInt(payload.get("modal_btNgoTeacher").toString()); - int pgRegTeacher = Integer.parseInt(payload.get("modal_pgRegTeacher").toString()); - int pgTempTeacher = Integer.parseInt(payload.get("modal_pgTempTeacher").toString()); - int pgPtTeacher = Integer.parseInt(payload.get("modal_pgPtTeacher").toString()); - int pgNgoTeacher = Integer.parseInt(payload.get("modal_pgNgoTeacher").toString()); - int kgRegTeacher = Integer.parseInt(payload.get("modal_kgRegTeacher").toString()); - int kgTempTeacher = Integer.parseInt(payload.get("modal_kgTempTeacher").toString()); - int petRegTeacher = Integer.parseInt(payload.get("modal_petRegTeacher").toString()); - int petTempTeacher = Integer.parseInt(payload.get("modal_petTempTeacher").toString()); - int petGrade1Teacher = Integer.parseInt(payload.get("modal_petg1Teacher").toString()); - int petGrade2Teacher = Integer.parseInt(payload.get("modal_petg2Teacher").toString()); - - int petPtTeacher = Integer.parseInt(payload.get("modal_petptTeacher").toString()); - Boolean is_hm = (Boolean) payload.get("is_hmAvailability"); - int stRegTeacher = Integer.parseInt(payload.get("modal_stRegTeacher").toString()); - int stPtTeacher = Integer.parseInt(payload.get("modal_stPtTeacher").toString()); - - int totOa = Integer.parseInt(payload.get("modal_totOa").toString()); - int kgAyah = Integer.parseInt(payload.get("modal_kgAyah").toString()); - int compAss = Integer.parseInt(payload.get("modal_compAss").toString()); - String watchmen = payload.get("modal_watchmen").toString(); - int scavengers = Integer.parseInt(payload.get("modal_scavengers").toString()); - int maintenanceWork = Integer.parseInt(payload.get("modal_maintenanceWork").toString()); - int schoolId = Integer.parseInt(payload.get("schoolId").toString()); - - List specialCategoryId = (List) payload.get("specialCategoryId"); - - return schoolPropertyService.updateStaffStrength(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, - btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, petPtTeacher, - is_hm, stRegTeacher, stPtTeacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId, specialCategoryId); - - - } - /* - * @GetMapping("/checkWaterDetails") public ResponseEntity checkWaterDetails( - * - * @RequestParam int school_id) { - * - * Map drinkingWater = - * schoolPropertyService.checkWaterDetails(school_id); List> - * waterSource = schoolPropertyService.checkWaterSource(school_id); - * List> waterStorage = - * schoolPropertyService.checkWaterStotage(school_id); - * - * Map result = new HashMap<>(); result.put("Message", - * "Success"); result.put("DrinkingWater", drinkingWater); - * result.put("WaterSource", waterSource); result.put("WaterStorage", - * waterStorage); - * - * return ResponseEntity.ok(Collections.singletonList(result)); } - */ -// @PostMapping(value = "/updateDrinkingWater") -// public String updateDrinkingWater(@RequestParam("is_purifier") Boolean is_purifier, @RequestParam("purifier_capacity") Double purifier_capacity, -// @RequestParam("is_borewell") Boolean is_borewell, @RequestParam("borewell_count") int borewell_count, @RequestParam("is_storage") Boolean is_storage, -// @RequestParam("drinking_water_id") int drinking_water_id, @RequestParam("school_id") int school_id, @RequestParam("supply") List> supply, -// @RequestParam("storage") List> storage) { -// try { -// -// return schoolPropertyService.updateDrinkingWater(is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, drinking_water_id, school_id, supply, storage); -// -// } catch (Exception e) { -// e.printStackTrace(); -// return "Error"; -// } -// -// } - - @PostMapping(value = "/updateDrinkingWater") - public ResponseEntity> updateDrinkingWater(@RequestBody Map requestData) { - try { - System.out.println("Received update payload: " + requestData); - - // Extract data from the map - // List> water = (List>) - // requestData.get("water"); - List> water = (List>) requestData.getOrDefault("supply", - new ArrayList<>()); - List> storage = (List>) requestData.getOrDefault("storage", - new ArrayList<>()); - - Boolean is_purifier = (Boolean) requestData.get("is_purifier"); - Double purifier_capacity = requestData.get("purifier_capacity") != null - ? Double.valueOf(requestData.get("purifier_capacity").toString()) - : 0; - Boolean is_borewell = (Boolean) requestData.get("is_borewell"); - Integer borewell_count = requestData.get("borewell_count") != null - ? Integer.valueOf(requestData.get("borewell_count").toString()) - : 0; - - int drinkingwater_tap = requestData.get("drinkingwater_tap") != null - ? Integer.valueOf(requestData.get("drinkingwater_tap").toString()) - : 0; - int handwash_tap= requestData.get("handwash_tap") != null - ? Integer.valueOf(requestData.get("handwash_tap").toString()) - : 0; - - Boolean is_storage = (Boolean) requestData.get("is_storage"); - // List> storage = (List>) - // requestData.get("storage"); - int school_id = Integer.parseInt(requestData.get("school_id").toString()); - int drinking_water_id = Integer.parseInt(requestData.get("drinking_water_id").toString()); - - Map response = new HashMap<>(); -/* - schoolPropertyService.updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count, - is_storage, school_id, drinking_water_id); - */ - schoolPropertyService.updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count, - is_storage, school_id, drinking_water_id,drinkingwater_tap,handwash_tap); - - schoolPropertyService.deactiveWaterSupply(school_id, drinking_water_id); - schoolPropertyService.deactiveWaterStorage(school_id, drinking_water_id); - for (Map waterSupply : water) { - int source_water_id = (int) waterSupply.get("source_water_id"); - String supply_type = (String) waterSupply.get("supply_type"); - schoolPropertyService.saveWaterSupply(source_water_id, supply_type, drinking_water_id, school_id); - } - if (!storage.isEmpty()) { - for (Map waterStorage : storage) { - double capacity = Double.valueOf(waterStorage.get("capacity").toString()); - int storage_water_id = (int) waterStorage.get("storage_water_id"); - schoolPropertyService.saveWaterStorage(capacity, storage_water_id, drinking_water_id, school_id); - } - } - - response.put("status", "OK"); - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error saving data: " + e.getMessage())); - } - } - - @GetMapping("/checkWaterDetails") - public ResponseEntity> checkWaterDetails(@RequestParam int school_id) { - System.out.println("CHECK 11"); - try { - System.out.println("CHECK 1"); - Map drinkingWater = schoolPropertyService.checkWaterDetails(school_id); - List> waterSource = schoolPropertyService.checkWaterSource(school_id); - List> waterStorage = schoolPropertyService.checkWaterStotage(school_id); - System.out.println("WATER SOURCE = " + waterSource); - - Map response = new HashMap<>(); - response.put("DrinkingWater", drinkingWater); - response.put("WaterSource", waterSource); - response.put("WaterStorage", waterStorage); - - // ✅ Set status based on content presence - if (drinkingWater != null && !drinkingWater.isEmpty()) { - response.put("status", "OK"); - } else { - response.put("status", "NEW"); - } - - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Could not load drinking water data")); - } - } - - @GetMapping("/checkToiletDetails") - public ResponseEntity checkToiletDetails(@RequestParam int school_id) { - - List> toiletDetails = schoolPropertyService.checkToiletDetails(school_id); - - Map result = new HashMap<>(); - result.put("Message", "Success"); - result.put("Data", toiletDetails); - - return ResponseEntity.ok(Collections.singletonList(result)); - } - - @PostMapping(value = "/updateToiletDetails") - public String updateToiletDetails(@RequestParam(value = "total_toiletBlocks", required = false) Integer total_toiletBlocks, - @RequestParam("total_male_urinals") int total_male_urinals, - @RequestParam("total_female_urinals") int total_female_urinals, - @RequestParam("staff_male_toilets") int staff_male_toilets, - @RequestParam("staff_female_toilets") int staff_female_toilets, - @RequestParam("total_wc_male") int total_wc_male, @RequestParam("total_wc_female") int total_wc_female, - @RequestParam("total_diffAbled_toilet") int total_diffAbled_toilet, - @RequestParam("is_napkins") Boolean is_napkins, @RequestParam("school_id") int school_id) { - try { - - return schoolPropertyService.updateToiletDetails(total_toiletBlocks, total_male_urinals,total_female_urinals,staff_male_toilets,staff_female_toilets, total_wc_male, - total_wc_female, total_diffAbled_toilet, is_napkins, school_id); - - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - @PostMapping(value = "/saveAssetMaster") - public ResponseEntity> saveAssetMaster(@RequestBody Map payload) { - Map response = new HashMap<>(); - String status = ""; - try { - - int school_id = Integer.parseInt(payload.get("school_id").toString()); - int asset_id = Integer.parseInt(payload.get("asset_id").toString()); - - List> equipmentList = (List>) payload.get("data"); - - for (Map asset : equipmentList) { - int sub_asset_id = Integer.parseInt(asset.get("sub_asset_id").toString()); - int master_qty = Integer.parseInt(asset.get("master_qty").toString()); - - status = schoolPropertyService.saveAssetMaster(sub_asset_id, master_qty, school_id, asset_id); - - } - - response.put("status", status.equals("Success") ? "OK" : "ERROR"); - response.put("message", - status.equals("Success") ? "Asset Master Saved successfully" : "Failed to Save Asset Master"); - - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - response.put("status", "ERROR"); - response.put("message", "Exception occurred during update"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); - } - } - - @GetMapping("/getAssetMaster") - public ResponseEntity getAssetMaster(@RequestParam int school_id, @RequestParam int asset_id) { - - List> data = schoolPropertyService.getAssetMaster(school_id, asset_id); - // System.out.println("data=="+data); - Map result = new HashMap<>(); - result.put("status", "Success"); - result.put("data", data); - - return ResponseEntity.ok(result); - } - - @GetMapping("/getAssetMasterById") - public ResponseEntity getAssetMasterById(@RequestParam int assetMasterId, @RequestParam int asset_id) { - - Map data = schoolPropertyService.getAssetMasterById(assetMasterId, asset_id); - - Map result = new HashMap<>(); - result.put("status", "Success"); - result.put("data", data); - - return ResponseEntity.ok(result); - } - - @PostMapping(value = "/updateAssetMaster") - public String updateStudentDetails(@RequestParam("master_qty") int master_qty, - @RequestParam("assetMasterId") int assetMasterId, @RequestParam("asset_id") int asset_id) { - - try { - Map assetMaster = schoolPropertyService.getAssetMasterById(assetMasterId, asset_id); - int qty = (Integer) assetMaster.get("master_qty"); - int unmapped_asset = (Integer) assetMaster.get("unmapped_qty"); - int mapped_asset = qty - unmapped_asset; - int master = 0; - int unmapped = 0; - - if(master_qty>=mapped_asset) { - master = master_qty; - unmapped = master_qty - mapped_asset; - return schoolPropertyService.updateAssetMaster(assetMasterId, master, asset_id, unmapped); - } - else { - return "lesser than"; - } - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - @GetMapping("/getAnganwadiDetails") - public ResponseEntity> getAnganwadiDetailsBySchId(@RequestParam int school_id) { - try { - List> data = schoolPropertyService.getAnganwadiDetailsBySchId(school_id); - Map response = new HashMap<>(); - - if (data != null && !data.isEmpty()) { - response.put("status", "OK"); - response.put("data", data); - } else { - response.put("status", "Failed"); - response.put("data", "No Data Found"); - } - - return ResponseEntity.ok(response); - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error fetching room details: " + e.getMessage())); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolReportController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolReportController.java deleted file mode 100644 index 0c3b8b4f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolReportController.java +++ /dev/null @@ -1,68 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - - -import in.gov.chennaicorporation.gccoffice.school.Service.SchoolReportService; - - -@RestController -@RequestMapping("/gcc/api/gccschool/report") -public class SchoolReportController { - @Autowired - private SchoolReportService schoolReportService; - - @Autowired - public SchoolReportController(SchoolReportService schoolReportService) { - this.schoolReportService = schoolReportService; - } - - @GetMapping("/getAEOList") - public ResponseEntity getAEOList(){ - return schoolReportService.getAEOList(); - } - - @GetMapping("/getAEOZone") - public ResponseEntity getAEOZone(@RequestParam String udise){ - return schoolReportService.getAEOZone(udise); - } - - @GetMapping("/getAEOWard") - public ResponseEntity getAEOWard(@RequestParam String udise, @RequestParam String zone){ - return schoolReportService.getAEOWard(udise, zone); - } - - @GetMapping("/getAEOSchoolData") - public ResponseEntity getAEOSchoolData(@RequestParam (required = false) List udise, - @RequestParam (required = false) String zone, - @RequestParam (required = false) String ward){ - - - return schoolReportService.getAEOSchoolData(udise, zone, ward); - } - - - @GetMapping("/getAEOStudentData") - public ResponseEntity getAEOStudentData(@RequestParam (required = false) List udise){ - System.out.println("list="+udise); - return schoolReportService.getAEOStudentData(udise); - } - - - @GetMapping("/getAEOStudentsCount") - public ResponseEntity getAEOStudentsCount(){ - return schoolReportService.getAEOStudentsCount(); - } - - @GetMapping("/getRegisteredStud") - public ResponseEntity getRegisteredStud(@RequestParam String udise){ - return schoolReportService.getRegisteredStud(udise); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/StudentInfoController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/StudentInfoController.java deleted file mode 100644 index b66529bb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/StudentInfoController.java +++ /dev/null @@ -1,127 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -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.gccoffice.school.Service.StudentInfoService; - -@RestController -@RequestMapping("/gcc/api/gccschool/studentInfo") -public class StudentInfoController { - @Autowired - private StudentInfoService studentInfoService; - - @Autowired - public StudentInfoController(StudentInfoService studentInfoService) { - this.studentInfoService = studentInfoService; - } - - @GetMapping("/getStandards") - public ResponseEntity getStandards(@RequestParam String udise){ - return studentInfoService.getStandards(udise); - } - - @GetMapping("/getSections") - public ResponseEntity getSections(){ - return studentInfoService.getSections(); - } - - @PostMapping("/saveStudent") - public ResponseEntity saveStudent(@RequestParam String udise, - @RequestParam String student_name, - @RequestParam String emis_no, - @RequestParam String gender, - @RequestParam String std, - @RequestParam String dob, - @RequestParam String age, - @RequestParam String parent_type, - @RequestParam String section, - @RequestParam String medium, - @RequestParam(value = "father_name", required = false) String father_name, - @RequestParam(value = "mother_name", required = false) String mother_name, - @RequestParam(value = "guardian_name", required = false) String guardian_name, - @RequestParam(value = "father_mobile", required = false) String father_mobile, - @RequestParam(value = "mother_mobile", required = false) String mother_mobile, - @RequestParam(value = "guardian_mobile", required = false) String guardian_mobile, - @RequestParam(value = "father_aadhar", required = false) String father_aadhar, - @RequestParam(value = "mother_aadhar", required = false) String mother_aadhar, - @RequestParam(value = "guardian_aadhar", required = false) String guardian_aadhar, - @RequestParam(value = "student_aadhar", required = false) String student_aadhar, - @RequestParam(value = "father_aadhar_file", required = false) MultipartFile father_aadhar_file, - @RequestParam(value = "mother_aadhar_file", required = false) MultipartFile mother_aadhar_file, - @RequestParam(value = "guardian_aadhar_file", required = false) MultipartFile guardian_aadhar_file, - @RequestParam(value = "student_aadhar_file", required = false) MultipartFile student_aadhar_file) { - //return studentInfoService.saveStudent(udise, student_name, emis_no, gender, std, dob, age, parent_type, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file); - return studentInfoService.checkStudent(udise, student_name, emis_no, gender, std, dob, age, parent_type,section,medium, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file); - } - - @GetMapping("/getStudentsClass") - public ResponseEntity getStudentsClass(@RequestParam String std, - @RequestParam String udise){ - return studentInfoService.getStudentsClass(udise, std); - } - - @GetMapping("/getStudentsDetails") - public ResponseEntity getStudentsDetails(@RequestParam String studentId){ - return studentInfoService.getStudentsDetails(studentId); - } - - @GetMapping("/getMedium") - public ResponseEntity getMedium(){ - return studentInfoService.getMedium(); - } - - @PostMapping("/deleteStudent") - public ResponseEntity deleteStudent(@RequestParam String student_id, - @RequestParam String user_id, - @RequestParam String action_type) { - return studentInfoService.deleteProcess(student_id, user_id, action_type); - } - - @PostMapping("/updateStudent") - public ResponseEntity updateStudent(@RequestParam String student_id, - @RequestParam String user_id, - @RequestParam String action_type, - @RequestParam String udise, - @RequestParam String student_name, - @RequestParam String emis_no, - @RequestParam String gender, - @RequestParam String mediums, - @RequestParam String std, - @RequestParam String section, - @RequestParam String dob, - @RequestParam String age, - @RequestParam String parent_type, - @RequestParam(value = "father_name", required = false) String father_name, - @RequestParam(value = "mother_name", required = false) String mother_name, - @RequestParam(value = "guardian_name", required = false) String guardian_name, - @RequestParam(value = "father_mobile", required = false) String father_mobile, - @RequestParam(value = "mother_mobile", required = false) String mother_mobile, - @RequestParam(value = "guardian_mobile", required = false) String guardian_mobile, - @RequestParam(value = "father_aadhar", required = false) String father_aadhar, - @RequestParam(value = "mother_aadhar", required = false) String mother_aadhar, - @RequestParam(value = "guardian_aadhar", required = false) String guardian_aadhar, - @RequestParam(value = "student_aadhar", required = false) String student_aadhar, - @RequestParam(value = "father_aadhar_file", required = false) MultipartFile father_aadhar_file, - @RequestParam(value = "mother_aadhar_file", required = false) MultipartFile mother_aadhar_file, - @RequestParam(value = "guardian_aadhar_file", required = false) MultipartFile guardian_aadhar_file, - @RequestParam(value = "student_aadhar_file", required = false) MultipartFile student_aadhar_file, - @RequestParam (value = "raw_father_aadhar", required = false) String raw_father_aadhar, - @RequestParam (value = "raw_mother_aadhar", required = false) String raw_mother_aadhar, - @RequestParam (value = "raw_guardian_aadhar", required = false) String raw_guardian_aadhar, - @RequestParam (value = "raw_student_aadhar", required = false) String raw_student_aadhar) { - return studentInfoService.updateProcess(student_id, user_id, action_type, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file, raw_father_aadhar, raw_mother_aadhar, raw_guardian_aadhar, raw_student_aadhar); - } - - @GetMapping("/checkStudent") - public ResponseEntity checkStudent(@RequestParam String udise, @RequestParam String schoolId){ - return studentInfoService.checkStudent(udise, schoolId); - } - - } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/.DS_Store deleted file mode 100644 index c3ca84b8..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/BuildingAssetService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/BuildingAssetService.java deleted file mode 100644 index 3b8c32ec..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/BuildingAssetService.java +++ /dev/null @@ -1,1142 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Service; - -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -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.web.bind.annotation.RequestParam; - -@Service -public class BuildingAssetService { - private JdbcTemplate jdbcTemplate; - - @Autowired - private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.namedParameterJdbcTemplate= new NamedParameterJdbcTemplate(dataSource); - } - - @Transactional - public int saveBuildings(String building_name, int total_floor, int building_material, int roof_material, - int school_id) { - String sql = "INSERT INTO buildings (building_name, total_floor, building_material, roof_material, school_id) VALUES (?, ?, ?, ?, ?)"; - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, building_name); - ps.setInt(2, total_floor); - ps.setInt(3, building_material); - ps.setInt(4, roof_material); - ps.setInt(5, school_id); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - int buildingID = generatedDataId.intValue(); - return buildingID; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - - } - - @Transactional - public Map getFloor(int i) { - String sql = "SELECT * FROM floor_master WHERE execution_order = ? "; - return jdbcTemplate.queryForMap(sql, i); - } - - @Transactional - public void saveFloor(String floor_name, int building_id, int floor_master_id, int school_id) { - String sql = "INSERT INTO floor_list (floor_name, building_id, floor_master_id, school_id) VALUES (?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, floor_name, building_id, floor_master_id, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - -// @Transactional -// public List> getFloorDetails(int building_id) { -// String sql = "SELECT fl.*,rd.room_type\r\n" -// + "FROM floor_list fl\r\n" -// + "left JOIN room_details rd ON rd.floors_id=fl.floors_id\r\n" -// + "WHERE fl.building_id = ? ORDER BY fl.floors_id"; -// System.out.println(sql); -// return jdbcTemplate.queryForList(sql, building_id); -// -// -// } - - @Transactional - public List> getFloorDetails(int building_id) { - String sql = "SELECT fl.floors_id, fl.floor_name, fl.building_id, fl.is_active, fl.is_delete, \r\n" - + " fl.floor_master_id, fl.status, \r\n" - + " COALESCE(GROUP_CONCAT( DISTINCT rm.room_type ORDER BY rm.room_master_id SEPARATOR ', '), '') AS room_types \r\n" - + " FROM floor_list fl \r\n" - + " LEFT JOIN room_details rd ON rd.floors_id = fl.floors_id \r\n" - + " LEFT JOIN room_master rm ON rm.room_master_id = rd.room_type \r\n" - + " WHERE fl.building_id = ? \r\n" - + " GROUP BY fl.floors_id, fl.floor_name, fl.building_id, fl.is_active, fl.is_delete, \r\n" - + " fl.floor_master_id, fl.status \r\n" + " ORDER BY fl.floors_id"; - - return jdbcTemplate.queryForList(sql, building_id); - - } - - public int getLastBuildingOrder(@RequestParam int schoolId) { - String sql = "SELECT COALESCE(MAX(building_order), 0) FROM buildings WHERE school_id = ?"; - int lastBuildingOrder = jdbcTemplate.queryForObject(sql, Integer.class, schoolId); - return lastBuildingOrder; - } - - @Transactional - public List> getSavedBuildings(int school_id) { - String sql = "SELECT b.*,bm.content as building_material_name,rm.content as roof_material_name\r\n" - + "FROM buildings b\r\n" + "JOIN building_material_master bm ON bm.bm_id=b.building_material\r\n" - + "JOIN roof_material_master rm ON rm.rm_id=b.roof_material\r\n" - + "WHERE b.school_id = ? and b.is_delete=0 and b.is_active=1 ORDER BY b.buildng_id"; - return jdbcTemplate.queryForList(sql, school_id); - } -/* - @Transactional - public void saveRoomDetails(int room_type, String room_num, int building_id, int floors_id, int school_id) { - String sql = "INSERT INTO room_details (room_type, room_num, building_id, floors_id, school_id) VALUES (?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, room_type, room_num, building_id, floors_id, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } -*/ - @Transactional - public String roomDetails(int room_type, String room_num, int building_id, int floors_id, - String anganwadiUniqueNumber, Boolean anganwadi_check, int school_id) { - String response = ""; - if(anganwadiUniqueNumber!=null) { - int is_avbl = checkAnganwadi(school_id, anganwadiUniqueNumber); - if(is_avbl==0) { - saveRoomDetails(room_type, room_num, building_id, floors_id,anganwadiUniqueNumber, anganwadi_check, school_id); - response = "Saved sucessfully"; - } else if(is_avbl==1) { - response = "Duplicate"; - } else { - response = "Error"; - } - } else { - saveRoomDetails(room_type, room_num, building_id, floors_id,anganwadiUniqueNumber, anganwadi_check, school_id); - response = "Saved sucessfully"; - } - return response; - } - - private int checkAnganwadi(int school_id, String anganwadiUniqueNumber) { - String sql = "SELECT CASE WHEN EXISTS (SELECT 1 FROM room_details WHERE school_id = ? and anganwadi_unique_number = ?) THEN 1 ELSE 0 END AS result"; - try { - return jdbcTemplate.queryForObject(sql, Integer.class, school_id, anganwadiUniqueNumber); - - } catch (Exception e) { - e.printStackTrace(); - return 5; - } - } - - public void saveRoomDetails(int room_type, String room_num, int building_id, int floors_id, String anganwadiUniqueNumber, Boolean anganwadi_check, int school_id) { - String sql = "INSERT INTO room_details (room_type, room_num, building_id, floors_id,anganwadi_unique_number, anganwadi_check, school_id) VALUES (?,?, ?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, room_type, room_num, building_id, floors_id,anganwadiUniqueNumber, anganwadi_check, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - public Map getSimpleBuildingById(int buildingId) { - String sql = "SELECT b.*, rm.content as roofmaterial ,bm.content as buildingmaterial FROM buildings b join building_material_master bm on\r\n" - + " bm.execution_order=b.building_material inner join roof_material_master rm on rm.execution_order=b.roof_material WHERE buildng_id = ?"; - try { - return jdbcTemplate.queryForMap(sql, buildingId); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public List> getFloorsByBuildingId(int buildingId) { - String sql = "SELECT fl.floors_id as floors_id,fl.floor_name as floor_name,fm.execution_order as execution_order FROM floor_list fl left join floor_master fm on fm.floor_master_id=fl.floor_master_id\r\n" - + " WHERE fl.building_id = ? AND fl.is_active = 1 AND fl.is_delete = 0\r\n" - + " ORDER BY 1 DESc"; - - return jdbcTemplate.queryForList(sql, buildingId); - } - - @Transactional - public void updateBuilding(int building_id, String building_name, int total_floor, String building_material, - String roof_material, int school_id) { - String sql = "UPDATE buildings SET building_name = ?, total_floor = ?, building_material = ?, roof_material = ?, school_id = ? WHERE buildng_id = ? "; - try { - jdbcTemplate.update(sql, building_name, total_floor, building_material, roof_material, school_id, - building_id); - - } catch (DataAccessException e) { - e.printStackTrace(); - - } - - } - - // add floor - @Transactional - public String addFloor(int building_id, int exe_order) { - - try { - exe_order = exe_order + 1; - Map data = getfloorName(exe_order); - String name = (String) data.get("content"); - int id = (int) data.get("floor_master_id"); - addFloordetails(name, building_id, id); - return "Sucess"; - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - private void addFloordetails(String name, int building_id, int id) { - String sql = "INSERT INTO floor_list (floor_name, building_id, floor_master_id) VALUES (?, ?, ?)"; - try { - jdbcTemplate.update(sql, name, building_id, id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private Map getfloorName(int exe_order) { - String sql = "SELECT * FROM floor_master WHERE execution_order = ?"; - try { - return jdbcTemplate.queryForMap(sql, exe_order); - } catch (DataAccessException e) { - e.printStackTrace(); - return null; - } - } - - // delete floor - @Transactional - public String editBuildings(int building_id, int floor_id) { - try { - List data = getassetFloorID(floor_id); - for(Integer it_details_id : data) { - unmapItAssetMaster(it_details_id); - } - editItAsset(floor_id, building_id); - - List> electrical_asset= getElectricalAssetMasterByFloorId(floor_id); - List> furniture_asset= getFurnitureAssetMasterByFloorId(floor_id); - - for(Map ele_data : electrical_asset) { - int school_id = (Integer) ele_data.get("school_id"); - int sub_asset_id = (Integer) ele_data.get("sub_asset_id"); - int asset_qty = (Integer) ele_data.get("asset_qty"); - String assetType="electricalasset"; - Map assetMaster = getAssetMasterBySchlId(sub_asset_id, school_id, assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int map = mapped - asset_qty; - int unMap = unMapped+asset_qty; - updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - - editElectricalAsset(floor_id, building_id); - - for(Map fur_data : furniture_asset) { - int school_id = (Integer) fur_data.get("school_id"); - int sub_asset_id = (Integer) fur_data.get("sub_asset_id"); - int asset_qty = (Integer) fur_data.get("asset_qty"); - String assetType="furnitureasset"; - Map assetMaster = getAssetMasterBySchlId(sub_asset_id, school_id, assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int map = mapped-asset_qty; - int unMap = unMapped+asset_qty; - updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - - editFurnitureAsset(floor_id, building_id); - - editRoom(floor_id, building_id); - - editFloor(floor_id, building_id); - - return "sucess"; - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - - } - - - public List getassetFloorID(int floor_id) { - List assetIds = new ArrayList<>(); - try { - String sql = "SELECT it_details_id FROM it_mapping WHERE floor_id = ?"; - assetIds = jdbcTemplate.queryForList(sql, Integer.class, floor_id); - } catch (Exception e) { - e.printStackTrace(); - } - return assetIds; - - } - - private void editElectricalAsset(int floor_id, int building_id) { - String sql = "UPDATE electrical_mapping SET is_active = false, is_delete = true WHERE floor_id = ? And building_id=?"; - try { - jdbcTemplate.update(sql, floor_id, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void editFurnitureAsset(int floor_id, int building_id) { - String sql = "UPDATE furniture_mapping SET is_active = false, is_delete = true WHERE floor_id = ? And building_id=?"; - try { - jdbcTemplate.update(sql, floor_id, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void editItAsset(int floor_id, int building_id) { - String sql = "UPDATE it_mapping SET is_active = false, is_delete = true WHERE floor_id = ? And building_id=?"; - try { - jdbcTemplate.update(sql, floor_id, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void editRoom(int floor_id, int building_id) { - String sql = "UPDATE room_details SET is_active = false, is_delete = true WHERE floors_id = ? And building_id=?"; - try { - jdbcTemplate.update(sql, floor_id, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void editFloor(int floor_id, int building_id) { - String sql = "UPDATE floor_list SET is_active = false, is_delete = true WHERE floors_id = ? And building_id=?"; - try { - jdbcTemplate.update(sql, floor_id, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - @Transactional - public void unmapAssets(int room_id, boolean is_delete) { - String sql = "UPDATE it_mapping SET is_delete = ?,is_active=0 WHERE room_id = ?"; - String sql1 = "UPDATE furniture_mapping SET is_delete = ?,is_active=0 WHERE room_id = ?"; - String sql2 = "UPDATE electrical_mapping SET is_delete = ?,is_active=0 WHERE room_id = ?"; - try { - jdbcTemplate.update(sql, is_delete, room_id); - jdbcTemplate.update(sql1, is_delete, room_id); - jdbcTemplate.update(sql2, is_delete, room_id); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @Transactional - public void deleteRoom(int room_id, boolean is_delete) { - String sql = "UPDATE room_details SET is_delete = ?,is_active=0 WHERE room_id = ? "; - try { - jdbcTemplate.update(sql, is_delete, room_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - @Transactional - public String executeDelete(int building_id, boolean is_delete) { - try { - deleteItAsset(building_id, is_delete); - List data = getassetBuildingID(building_id); - for(Integer it_details_id : data) { - unmapItAssetMaster(it_details_id); - } - - List> electrical_asset= getElectricalAssetMasterByBuildingId(building_id); - List> furniture_asset= getFurnitureAssetMasterByBuildingId(building_id); - - for(Map ele_data : electrical_asset) { - int school_id = (Integer) ele_data.get("school_id"); - int sub_asset_id = (Integer) ele_data.get("sub_asset_id"); - int asset_qty = (Integer) ele_data.get("asset_qty"); - String assetType="electricalasset"; - Map assetMaster = getAssetMasterBySchlId(sub_asset_id, school_id, assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int map = mapped-asset_qty; - int unMap = unMapped+asset_qty; - updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - - deleteElectricalAsset(building_id, is_delete); - - for(Map fur_data : furniture_asset) { - int school_id = (Integer) fur_data.get("school_id"); - int sub_asset_id = (Integer) fur_data.get("sub_asset_id"); - int asset_qty = (Integer) fur_data.get("asset_qty"); - String assetType="furnitureasset"; - Map assetMaster = getAssetMasterBySchlId(sub_asset_id, school_id, assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int map = mapped-asset_qty; - int unMap = unMapped+asset_qty; - updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - - deleteFurnitureAsset(building_id, is_delete); - - deleteRoomById(building_id, is_delete); - deleteFloor(building_id, is_delete); - deleteBuilding(building_id, is_delete); - return "Building Deleted Sucessfully"; - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - public List getassetBuildingID(int building_id) { - List assetIds = new ArrayList<>(); - try { - String sql = "SELECT it_details_id FROM it_mapping WHERE building_id = ?"; - assetIds = jdbcTemplate.queryForList(sql, Integer.class, building_id); - } catch (Exception e) { - e.printStackTrace(); - } - return assetIds; - } - - private void deleteBuilding(int building_id, boolean is_delete) { - String sql = "UPDATE buildings SET is_active=false,is_delete = ? WHERE buildng_id = ?;"; - try { - jdbcTemplate.update(sql, is_delete, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void deleteFloor(int building_id, boolean is_delete) { - String sql = "UPDATE floor_list SET is_active=false,is_delete = ? WHERE building_id = ?;"; - try { - jdbcTemplate.update(sql, is_delete, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void deleteRoomById(int building_id, boolean is_delete) { - String sql = "UPDATE room_details SET is_active=false,is_delete = ? WHERE building_id = ?;"; - try { - jdbcTemplate.update(sql, is_delete, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void deleteElectricalAsset(int building_id, boolean is_delete) { - String sql = "UPDATE electrical_mapping SET is_active=false,is_delete = ? WHERE building_id = ?;"; - try { - jdbcTemplate.update(sql, is_delete, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void deleteFurnitureAsset(int building_id, boolean is_delete) { - String sql = "UPDATE furniture_mapping SET is_active=false,is_delete = ? WHERE building_id = ? ;"; - try { - jdbcTemplate.update(sql, is_delete, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void deleteItAsset(int building_id, boolean is_delete) { - String sql = "UPDATE it_mapping SET is_active=false,is_delete = ? WHERE building_id = ?;"; - try { - jdbcTemplate.update(sql, is_delete, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - public Map>> getAllMaterials() { - String buildingMaterialSql = "SELECT execution_order, content FROM building_material_master ORDER BY execution_order"; - String roofMaterialSql = "SELECT execution_order, content FROM roof_material_master ORDER BY execution_order"; - - List> buildingMaterials = jdbcTemplate.queryForList(buildingMaterialSql); - List> roofMaterials = jdbcTemplate.queryForList(roofMaterialSql); - - Map>> result = new HashMap<>(); - result.put("buildingMaterials", buildingMaterials); - result.put("roofMaterials", roofMaterials); - - return result; - } - - @Transactional - public List> getRoomDetailsBySchoolId(int schoolId) { - String sql = "SELECT rd.room_id, " + " rd.room_num AS room_name, " + " bd.building_name, " - + " rd.building_id, " + " fl.floor_name AS floor, " + // ✅ FIXED HERE - " rm.room_type, " + " rd.school_id, " + " rm.room_master_id, " - + " fl.floors_id " + "FROM room_details rd " - + "JOIN buildings bd ON bd.buildng_id = rd.building_id " - + "JOIN floor_list fl ON fl.floors_id = rd.floors_id " + // ✅ REMOVED floor_master JOIN - "JOIN room_master rm ON rd.room_type = rm.room_master_id " - + "WHERE rd.school_id = ? AND rd.is_active = 1 AND rd.is_delete = 0"; - - return jdbcTemplate.queryForList(sql, schoolId); - } - - @Transactional - public Map getRoomDetailsById(int roomId) { - String sql = "SELECT rd.room_id,rd.room_num AS room_name,bd.building_name, " - + "fl.floor_name AS floor, rm.room_type, rd.school_id, rm.room_master_id,rd.anganwadi_unique_number, " - + "fl.floors_id " + "FROM room_details rd " - + "JOIN buildings bd ON bd.buildng_id = rd.building_id " - + "JOIN floor_list fl ON fl.floors_id = rd.floors_id " + - "JOIN room_master rm ON rd.room_type = rm.room_master_id " - + "WHERE rd.room_id = ? AND rd.is_active = 1 AND rd.is_delete = 0"; - - return jdbcTemplate.queryForMap(sql, roomId); - } - - public String editRoomsById(int room_type, String room_num, int building_id, int floors_id, int school_id, - String anganwadiUniqueNumber, Boolean anganwadi_check,int room_id) { - - String response = ""; - if(anganwadiUniqueNumber!=null) { - int is_avbl = checkAnganwadiEdit(school_id, anganwadiUniqueNumber,room_id); - if(is_avbl==0) { - editRoom(room_type, room_num, building_id, floors_id, school_id,anganwadiUniqueNumber,anganwadi_check,room_id); - response = "Rooms Edited Sucessfully"; - - } else if(is_avbl==1) { - response = "Duplicate"; - - } else { - response = "Error"; - - } - } else { - editRoom(room_type, room_num, building_id, floors_id, school_id,anganwadiUniqueNumber, anganwadi_check,room_id); - response = "Rooms Edited Sucessfully"; - } - return response; - } - - private int checkAnganwadiEdit(int school_id, String anganwadiUniqueNumber,int room_id) { - String sql = "SELECT CASE WHEN EXISTS (SELECT 1 FROM room_details WHERE school_id = ? and anganwadi_unique_number = ? and room_id !=? ) THEN 1 ELSE 0 END AS result"; - try { - return jdbcTemplate.queryForObject(sql, Integer.class, school_id, anganwadiUniqueNumber,room_id); - - } catch (Exception e) { - e.printStackTrace(); - return 5; - } - } - - @Transactional - public void editRoom(int room_type, String room_num, int building_id, int floors_id, int school_id,String anganwadiUniqueNumber,Boolean anganwadi_check, int room_id) { - String sql = "UPDATE room_details SET room_type = ?, room_num = ?, building_id = ?, floors_id = ?, school_id = ?, anganwadi_unique_number=?,anganwadi_check=? WHERE room_id = ? "; - try { - jdbcTemplate.update(sql, room_type, room_num, building_id, floors_id, school_id,anganwadiUniqueNumber, anganwadi_check, room_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - /* - * @Transactional public void deleteRoom(int room_id, boolean is_delete) { - * String sql = "UPDATE room_details SET is_delete = ? WHERE room_id = ? "; try - * { jdbcTemplate.update(sql, is_delete, room_id); }catch (DataAccessException - * e) { e.printStackTrace(); } - * - * } - */ - - @Transactional - public List> getItAssetMapping(int roomId, String assetType) { - String sql = ""; - if (assetType.equalsIgnoreCase("itasset")) { - sql = "SELECT md.*,m.it_map_id \r\n" + "FROM it_mapping m\r\n" - + "JOIN it_master_details md ON m.it_details_id = md.it_details_id\r\n" - + "WHERE m.room_id = ? and m.is_active='1' and m.is_delete='0'\r\n"; - } else if (assetType.equalsIgnoreCase("furnitureasset")) { - sql = " select sm.asset_name as assetname,fm.* from asset_sub_master sm inner join \r\n" - + " furniture_mapping fm on sm.sub_asset_id = fm.sub_asset_id where fm.is_active='1' and fm.is_delete='0' and fm.room_id = ?"; - } else if (assetType.equalsIgnoreCase("electricalasset")) { - sql = "select sm.asset_name as assetname,em.* from asset_sub_master sm inner join \r\n" - + " electrical_mapping em on sm.sub_asset_id = em.sub_asset_id where em.is_active='1' and em.is_delete='0' and em.room_id = ?"; - } - - try { - return jdbcTemplate.queryForList(sql, roomId); - } catch (Exception e) { - e.printStackTrace(); - return new ArrayList<>(); - } - - } - - @Transactional - public String deleteAssetMapping(int it_map_id, boolean is_delete) { - String sql = "UPDATE it_mapping SET is_delete = ? WHERE it_map_id = ? "; - - try { - jdbcTemplate.update(sql, is_delete, it_map_id); - return "Asset Deleted"; - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - @Transactional - public String updateFurturQty(int id, int qty, String assetType) { - - String sql = ""; - if (assetType.equalsIgnoreCase("furnitureasset")) { - sql = "UPDATE furniture_mapping SET asset_qty = ? WHERE furniture_map_id = ?"; - } else if (assetType.equalsIgnoreCase("electricalasset")) { - sql = "UPDATE electrical_mapping SET asset_qty = ? WHERE electrical_map_id = ?"; - } - - try { - jdbcTemplate.update(sql, qty, id); - return "sucess"; - } catch (Exception e) { - e.printStackTrace(); - return "error"; - } - } - - @Transactional - public List> getSchoolAssetForManagement(int school_id) { - String sql = "SELECT md.* FROM school_list m INNER JOIN it_master_details md ON m.udise COLLATE utf8mb4_general_ci = md.udise " - + "WHERE m.id = ? and md.is_online = '0'"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return new ArrayList<>(); - } - } - - @Transactional - public List> getSchoolAsset(int school_id, String type) { - String sql = "SELECT md.* FROM school_list m INNER JOIN it_master_details md ON m.udise COLLATE utf8mb4_general_ci = md.udise\r\n" - + "WHERE m.id = ? and md.is_mapped = 0 and md.hardware_type LIKE '%" + type + "%'"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return new ArrayList<>(); - } - } - - @Transactional - public String addAsset(String assetCode, String name, String source, String serialNum, String vendorDetail, - String invoice_num, String udise, boolean is_online) { - String sql = "INSERT INTO it_master_details (asset_name, source_of_asset, serial_no, hardware_type, vendor_name, udise, is_online, invoice_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, assetCode, source, serialNum, name, vendorDetail, udise, is_online, invoice_num); - return "Sucess"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - - } - - @Transactional - public Map getAssets(int it_details_id) { - - String sql = "SELECT * FROM it_master_details WHERE it_details_id = ? "; - return jdbcTemplate.queryForMap(sql, it_details_id); - } - - @Transactional - public String editAsset(String assetCode, String name, String source, String serialNum, String vendorDetail, - String invoice_num, int it_details_id) { - String sql = "UPDATE it_master_details SET asset_name = ?, source_of_asset = ?, serial_no = ?, hardware_type = ?, vendor_name = ?, invoice_num = ? WHERE it_details_id = ? "; - try { - jdbcTemplate.update(sql, assetCode, source, serialNum, name, vendorDetail, invoice_num, it_details_id); - return "Success"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - - @Transactional - public void mapAssets(int room_id, int floor_id, int school_id, int it_details_id, int building_id) { - - saveAssetMapping(room_id, floor_id, school_id, it_details_id, building_id); - updateMapping(it_details_id); - - } - - private void updateMapping(int it_details_id) { - String sql = "UPDATE it_master_details SET is_mapped = true WHERE it_details_id = ?"; - try { - jdbcTemplate.update(sql, it_details_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void saveAssetMapping(int room_id, int floor_id, int school_id, int it_details_id, int building_id) { - String sql = "INSERT INTO it_mapping (room_id, floor_id, school_id, it_details_id, building_id) VALUES (?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, room_id, floor_id, school_id, it_details_id, building_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - @Transactional - public void addFurAsset(int sub_asset_id, int asset_qty, int room_id, int building_id, int floor_id, int school_id, - String assetType) { - String sql = ""; - if (assetType.equalsIgnoreCase("furnitureasset")) { - sql = "INSERT INTO furniture_mapping (sub_asset_id, asset_qty, room_id,building_id, floor_id, school_id) VALUES (?,?, ?, ?, ?, ?)"; - } else if (assetType.equalsIgnoreCase("electricalasset")) { - sql = "INSERT INTO electrical_mapping (sub_asset_id, asset_qty, room_id,building_id, floor_id, school_id) VALUES (?,?, ?, ?, ?, ?)"; - } - try { - jdbcTemplate.update(sql, sub_asset_id, asset_qty, room_id, building_id, floor_id, school_id); - - } catch (DataAccessException e) { - e.printStackTrace(); - - } - } -//intial - // checking for view - public List> getStudentStrengthBySchoolId(@RequestParam int schoolId) { - String sql = "SELECT total_boys, total_girls, others, total_students,special_child " + - "FROM student_strength " + - "WHERE school_id = ? " + - "ORDER BY student_id DESC LIMIT 1"; - - return jdbcTemplate.queryForList(sql, schoolId); - } - -//initial - /*public List> getotherdetailsBySchoolId(@RequestParam int schoolId) { - String sql = "select*from school_buildup_area where school_id=?" ; - - return jdbcTemplate.queryForList(sql, schoolId); - }*/ - - public List> getotherdetailsBySchoolId(@RequestParam int schoolId) { - //String sql = "select*from school_buildup_area where school_id=? ORDER BY buildup_id DESC LIMIT 1" ; - - String sql = "SELECT buildup_id, land_area, buildup_area, " + - "CAST(is_compound AS SIGNED) AS is_compound, " + - "is_nameboard AS is_nameboard, " + - "is_pasystem AS is_pasystem, " + - "is_bell AS is_bell, " + - "is_generator AS is_generator, " + - "school_id " + - "FROM school_buildup_area WHERE school_id = ? ORDER BY buildup_id DESC LIMIT 1"; - - - return jdbcTemplate.queryForList(sql, schoolId); - } -//initial - /*public List> getStaffStrengthBySchoolId(@RequestParam int schoolId) { - String sql = "SELECT * FROM staff_strength_1 WHERE school_id = ?"; - - return jdbcTemplate.queryForList(sql, schoolId); - } - public List> getStaffStrengthBySchoolId(@RequestParam int schoolId) { - String sql = "SELECT * FROM staff_strength_1 WHERE school_id = ? ORDER BY staff_id DESC LIMIT 1"; - - return jdbcTemplate.queryForList(sql, schoolId); - } -*/ - @Transactional - public Map getIt_Details(int it_map_id) { - Map result = new HashMap<>(); - try { - String sql = "SELECT * FROM it_mapping WHERE it_map_id = ? "; - result = jdbcTemplate.queryForMap(sql, it_map_id); - } catch (Exception e) { - e.printStackTrace(); - } - return result; - } - -// @Transactional -// public String unmapAsset(int it_details_id) { -// String sql = "UPDATE it_master_details SET is_mapped = false WHERE it_details_id = ? "; -// -// try { -// jdbcTemplate.update(sql, it_details_id); -// return "Asset Unmapped"; -// } catch (Exception e) { -// e.printStackTrace(); -// return "error"; -// } -// } - - @Transactional - public List getassetRoomID(int room_id) { - List assetIds = new ArrayList<>(); - try { - String sql = "SELECT it_details_id FROM it_mapping WHERE room_id = ?"; - assetIds = jdbcTemplate.queryForList(sql, Integer.class, room_id); - } catch (Exception e) { - e.printStackTrace(); - } - return assetIds; - } - - @Transactional - public void unmapItAssetMaster(Integer it_details_id) { - String sql = "UPDATE it_master_details SET is_mapped = false WHERE it_details_id = ? "; - - try { - jdbcTemplate.update(sql, it_details_id); - - } catch (Exception e) { - e.printStackTrace(); - - } - - } - - @Transactional - public int checkBuilding(String building_name, int school_id) { - - String sql = "SELECT CASE \r\n" - + " WHEN COUNT(*) > 0 THEN 1 \r\n" - + " ELSE 0 \r\n" - + " END AS is_existing\r\n" - + "FROM buildings\r\n" - + "WHERE school_id = ? AND building_name = ?"; - - try { - return jdbcTemplate.queryForObject(sql, Integer.class, school_id, building_name); - - } catch (Exception e) { - e.printStackTrace(); - return 5; - - } - - - } - - @Transactional - public int getAssetCount(String udise, boolean is_online) { - String sql = "SELECT COUNT(*) FROM it_master_details WHERE is_online = ? and udise = ?;"; - - try { - return jdbcTemplate.queryForObject(sql, Integer.class, is_online, udise); - - } catch (Exception e) { - e.printStackTrace(); - return -1; - - } - } - @Transactional - public String assetUpdation(int asset_qty, String assetType, int sub_asset_id, int school_id, int room_id, - int building_id, int floor_id) { - int check = mapAssetMaster(asset_qty, assetType, sub_asset_id, school_id); - if(check ==1) { - Map data = ckeckAssetQty(room_id, sub_asset_id, assetType); - - int asset_Map_Id = (Integer) data.get("asset_Map_Id") !=null ? (Integer) data.get("asset_Map_Id") : 0; - int qty = (Integer) data.get("asset_qty") !=null ? (Integer) data.get("asset_qty") : 0; - int total = qty+asset_qty; - - if(asset_Map_Id!=0) { - updateAssetQty(asset_Map_Id, assetType, total); - }else { - addFurAsset(sub_asset_id, asset_qty, room_id,building_id, floor_id, school_id, assetType ); - } - return "Sucess"; - } else { - return "Add Sufficient Quantity"; - } - } - - private void updateAssetQty(int asset_Map_Id, String assetType, int total) { - String sql=""; - if (assetType.equalsIgnoreCase("furnitureasset")) { - sql = "UPDATE furniture_mapping SET asset_qty = ? WHERE furniture_map_id = ?"; - } else if (assetType.equalsIgnoreCase("electricalasset")) { - sql = "UPDATE electrical_mapping SET asset_qty = ? WHERE electrical_map_id = ?"; - } - jdbcTemplate.update(sql, total, asset_Map_Id); - - } - - public Map ckeckAssetQty(int room_id, int sub_asset_id, String assetType) { - String sql = ""; - if ("furnitureasset".equalsIgnoreCase(assetType)) { - sql = "SELECT furniture_map_id as asset_Map_Id, asset_qty FROM furniture_mapping WHERE room_id = ? AND sub_asset_id = ?"; - } else if ("electricalasset".equalsIgnoreCase(assetType)) { - sql = "SELECT electrical_map_id as asset_Map_Id, asset_qty FROM electrical_mapping WHERE room_id = ? AND sub_asset_id = ?"; - } - - try { - return jdbcTemplate.queryForMap(sql, room_id, sub_asset_id); - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - @Transactional - public int mapAssetMaster(int asset_qty, String assetType, int sub_asset_id, int school_id) { - Map assetMaster = getAssetMasterBySchlId(sub_asset_id, school_id, assetType); - - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - if(unMapped>=asset_qty) { - int map = mapped+asset_qty; - int unMap = unMapped-asset_qty; - return updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); - } - return 0; - - } - - @Transactional - public int updateAssetmaster(int map, int unMap, int school_id, int sub_asset_id, String assetType) { - String sql=""; - if (assetType.equalsIgnoreCase("furnitureasset")) { - sql = "UPDATE furniture_master SET mapped_qty = ?, unmapped_qty = ? WHERE school_id = ? and sub_asset_id = ?"; - } else if (assetType.equalsIgnoreCase("electricalasset")) { - sql = "UPDATE electrical_master SET mapped_qty = ?, unmapped_qty = ? WHERE school_id = ? and sub_asset_id = ?"; - } - try { - jdbcTemplate.update(sql, map, unMap, school_id, sub_asset_id); - return 1; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - - } - - - - @Transactional - public Map getAssetMasterBySchlId(int sub_asset_id, int school_id, String assetType) { - String sql=""; - if (assetType.equalsIgnoreCase("furnitureasset")) { - sql = "SELECT * from furniture_master where school_id = ? and sub_asset_id = ?"; - } else if (assetType.equalsIgnoreCase("electricalasset")) { - sql = "SELECT * from electrical_master where school_id = ? and sub_asset_id = ?"; - } - try { - List> data =jdbcTemplate.queryForList(sql, school_id, sub_asset_id); - if(data!=null && !data.isEmpty()) { - return data.get(0); - } - return Map.of(); - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - @Transactional - public List> getElectricalAssetMasterByRoomId(int room_id) { - try { - String sql = "select sub_asset_id, school_id, asset_qty from electrical_mapping where room_id=? and is_active = 1 and is_delete = 0"; - - return jdbcTemplate.queryForList(sql, room_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public List> getFurnitureAssetMasterByRoomId(int room_id) { - try { - String sql = "select sub_asset_id, school_id, asset_qty from furniture_mapping where room_id=? and is_active = 1 and is_delete = 0"; - - return jdbcTemplate.queryForList(sql, room_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - private List> getElectricalAssetMasterByFloorId(int floor_id) { - try { - String sql = "select sub_asset_id, school_id, asset_qty from electrical_mapping where floor_id=? and is_active = 1 and is_delete = 0"; - - return jdbcTemplate.queryForList(sql, floor_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - @Transactional - private List> getFurnitureAssetMasterByFloorId(int floor_id) { - try { - String sql = "select sub_asset_id, school_id, asset_qty from furniture_mapping where floor_id=? and is_active = 1 and is_delete = 0"; - - return jdbcTemplate.queryForList(sql, floor_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - private List> getElectricalAssetMasterByBuildingId(int building_id) { - try { - String sql = "select sub_asset_id, school_id, asset_qty from electrical_mapping where building_id=? and is_active = 1 and is_delete = 0"; - - return jdbcTemplate.queryForList(sql, building_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - private List> getFurnitureAssetMasterByBuildingId(int building_id) { - try { - String sql = "select sub_asset_id, school_id, asset_qty from furniture_mapping where building_id=? and is_active = 1 and is_delete = 0"; - - return jdbcTemplate.queryForList(sql, building_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public String updateAssetExecution(List> assets) { - try { - for(Map asset : assets) { - int id = Integer.parseInt(asset.get("id").toString()); - - int qty = Integer.parseInt(asset.get("qty").toString()); - String assetType = (String) asset.get("assetType"); - int school_id = Integer.parseInt(asset.get("schid").toString()); - int sub_asset_id = Integer.parseInt(asset.get("subid").toString()); - int flag = Integer.parseInt(asset.get("flag").toString()); - int originalQty = Integer.parseInt(asset.get("originalQty").toString()); - - Map assetMaster = getAssetMasterBySchlId(sub_asset_id, school_id, assetType); - int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0; - int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0; - int master = assetMaster.get("master_qty") != null ? (Integer) assetMaster.get("master_qty") : 0; - - int map = 0; - int unmap = 0; - - if(flag == -1) { - int diff = originalQty-qty; - map=mapped-diff; - unmap = unMapped+diff; - if(unmap<=master) { - int result = updateAssetmaster(map, unmap, school_id, sub_asset_id, assetType); - } else { - return "Add Sufficient Master Quantity"; - } - - } else if (flag == 0) { - - }else if(flag == 1) { - int diff = qty-originalQty; - map=mapped+diff; - unmap = unMapped-diff; - if(map<=master) { - int result = updateAssetmaster(map, unmap, school_id, sub_asset_id, assetType); - } else { - return "Add Sufficient Master Quantity"; - } - } - String data = updateFurturQty(id, qty, assetType); - - } - return "Sucess"; - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - public List> getStaffStrengthBySchoolId(@RequestParam int schoolId) { - String sql = "SELECT * FROM staff_strength_1 WHERE school_id = ? ORDER BY staff_id DESC LIMIT 1"; - - return jdbcTemplate.queryForList(sql, schoolId); - } - - public List> getSpecialCategoryBySchoolId(int schoolId) { - String sql = "SELECT scd.*,scm.special_category as sc_names FROM special_category_details scd\r\n" - + "INNER JOIN special_category_master scm ON scm.special_category_id=scd.special_category_id\r\n" - + "where scd.school_id=? AND scd.is_active=1 AND scd.is_delete=0"; - - return jdbcTemplate.queryForList(sql, schoolId); - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/DropdownsService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/DropdownsService.java deleted file mode 100644 index 34c765ab..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/DropdownsService.java +++ /dev/null @@ -1,194 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Service; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class DropdownsService { - private JdbcTemplate jdbcTemplate; - -// @Autowired - private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - - - @Autowired - public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.namedParameterJdbcTemplate= new NamedParameterJdbcTemplate(dataSource); - } - - @Transactional - public List> getCourtData() { - String sql = "SELECT * FROM courts_master "; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getEquipmentData() { - String sql = "SELECT * FROM equipment_master "; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getBuildingMaterial() { - String sql = "SELECT * FROM building_material_master ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getRoofMaterial() { - String sql = "SELECT * FROM roof_material_master ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getWaterSource() { - String sql = "SELECT * FROM source_water ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getWaterStorage() { - String sql = "SELECT * FROM water_storage_master ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getRooms() { - String sql = "SELECT * FROM room_master ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - - - - - @Transactional - public List> getFloorsByBuilding(int buildingId) { - String sql = "SELECT * FROM floor_list WHERE building_id = ? and is_active = true and is_delete = false"; - return jdbcTemplate.queryForList(sql, buildingId); - } - - @Transactional - public List> getBuildingsBySchoolId(int schoolId) { - String sql = "SELECT buildng_id, building_name FROM buildings WHERE school_id = ? and is_active = true and is_delete = false"; - return jdbcTemplate.queryForList(sql, schoolId); - } - - // Reuse this for school_id retrieval - @Transactional - public String getSchoolId(String user_id) { - String sql = "SELECT school_id FROM login_details WHERE user_id = ?"; - try { - return jdbcTemplate.queryForObject(sql, String.class, user_id); - } catch (DataAccessException e) { - return "error"; - } - } - - // New method to fetch UDISE numbers for a given school_id - public List> getUdiseNumbersBySchoolId(String schoolId) { - String sql = "SELECT udise FROM school_list WHERE id IN(" + schoolId + ")"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - public List> getCategoryBySchoolId(String schoolId) { - String sql = "SELECT category FROM school_list WHERE id IN(" + schoolId + ")"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - - public List> getZoneBySchoolId(String schoolId) { - String sql = "SELECT zone FROM school_list WHERE id IN(" + schoolId + ")"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - public List> getWardBySchoolId(String schoolId) { - String sql = "SELECT division FROM school_list WHERE id IN(" + schoolId + ")"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public List> getAssetType() { - String sql = "SELECT * FROM asset_master ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - - @Transactional - public List> getSubAssetType(int assetid) { - String sql = "SELECT * FROM asset_sub_master WHERE asset_master_id = ? ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql, assetid); - } - - @Transactional - public List> getSplSubAssetType(List assets, int assetid) { - String sql; - Map params = new HashMap<>(); - params.put("assetid", assetid); - - if (assets == null || assets.isEmpty()) { - - sql = "SELECT * FROM asset_sub_master WHERE asset_master_id = :assetid ORDER BY execution_order"; - - } else { - - sql = "SELECT * FROM asset_sub_master WHERE asset_master_id = :assetid AND asset_name NOT IN (:assets) ORDER BY execution_order"; - params.put("assets", assets); - } - - return namedParameterJdbcTemplate.queryForList(sql, params); - } - @Transactional - public List getAssetList(int school_id, int assetid) { - String sql =""; - if(assetid==2) { - sql = "SELECT asm.asset_name from electrical_master em \r\n" - + "INNER JOIN asset_sub_master asm ON em.sub_asset_id = asm.sub_asset_id\r\n" - + "WHERE em.school_id = ?"; - } else if(assetid==3) { - sql = "SELECT asm.asset_name from furniture_master fm \r\n" - + "INNER JOIN asset_sub_master asm ON fm.sub_asset_id = asm.sub_asset_id\r\n" - + "WHERE fm.school_id = ?"; - } - return jdbcTemplate.queryForList(sql, String.class, school_id); - } - - @Transactional - public List> getSpecialCategory(){ - String sql = "SELECT * FROM special_category_master WHERE is_active=1 AND is_delete=0 ORDER BY execution_order"; - return jdbcTemplate.queryForList(sql); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolPropertyService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolPropertyService.java deleted file mode 100644 index 7571bc53..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolPropertyService.java +++ /dev/null @@ -1,1543 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Service; - -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class SchoolPropertyService { - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - - } - - @Transactional - public List> getSchoolData(String udise) { - String sql = "SELECT * FROM school_list WHERE udise = ?"; - return jdbcTemplate.queryForList(sql, udise); - } -//initial - /*@Transactional - public String saveSchoolBuildupArea(Double land_area, Double buildup_area, Boolean is_compound, - Boolean is_nameboard, Boolean is_pasystem, Boolean is_bell, Boolean is_generator, int school_id) { - String sql = "INSERT INTO school_buildup_area (land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell, is_generator, school_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell, - is_generator, school_id); - return "Other Details saved sucessfully"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "error"; - } - - }*/ - @Transactional - public String saveSchoolBuildupArea(Double land_area, Double buildup_area, int is_compound, - Boolean is_nameboard, Boolean is_pasystem, Boolean is_bell, Boolean is_generator, int school_id) { - - // Step 1: Check if record exists for the given school_id - String checkSql = "SELECT COUNT(*) FROM school_buildup_area WHERE school_id = ?"; - try { - int count = jdbcTemplate.queryForObject(checkSql, new Object[]{school_id}, Integer.class); - - if (count > 0) { - return "Build-up Area details for this school already exist."; - } - - // Step 2: Insert only if no existing record found - String insertSql = "INSERT INTO school_buildup_area (land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell, is_generator, school_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; - jdbcTemplate.update(insertSql, land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell, is_generator, school_id); - - return "Other Details saved successfully"; - - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error saving build-up area details."; - } - } - -//initial live - /*@Transactional - public String saveStudentStrength(int total_students, int total_girls, int total_boys, int others, int school_id) { - String sql = "INSERT INTO student_strength (total_students, total_girls, total_boys,others,school_id) VALUES (?,?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, total_students, total_girls, total_boys, others, school_id); - return "Student Strength saved sucessfully"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "error"; - } - }*/ - @Transactional - public String saveStudentStrength(int total_students, int total_girls, int total_boys, int others,int special_child, int school_id) { - // Check if a record already exists for the given school_id - String checkSql = "SELECT COUNT(*) FROM student_strength WHERE school_id = ?"; - try { - int count = jdbcTemplate.queryForObject(checkSql, new Object[]{school_id}, Integer.class); - if (count > 0) { - return "Student Strength for this school is already recorded."; - } - - // Proceed with insert if no record found - String insertSql = "INSERT INTO student_strength (total_students, total_girls, total_boys, others, special_child,school_id) VALUES (?,?, ?, ?, ?, ?)"; - jdbcTemplate.update(insertSql, total_students, total_girls, total_boys, others,special_child, school_id); - return "Student Strength saved successfully"; - - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error saving student strength."; - } - } - - -// @Transactional -// public String saveStaffStrength(int tot_staff, int sg_staff, int bt_staff, int pg_staff, int temp_staff, -// int ngo_staff, int kg_staff, int pt_staff, int part_staff, int qa_staff, int kg_ayha, int watchman, -// int comp_asst, int scavengers, int maint_workers, int school_id) { -// String sql = "INSERT INTO staff_strength (tot_staff, sg_staff, bt_staff, pg_staff,temp_staff, ngo_staff, kg_staff, pt_staff,part_staff, qa_staff, kg_ayha, watchman, comp_asst, scavengers, maint_workers, school_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; -// try { -// jdbcTemplate.update(sql, tot_staff, sg_staff, bt_staff, pg_staff, temp_staff, ngo_staff, kg_staff, pt_staff, -// part_staff, qa_staff, kg_ayha, watchman, comp_asst, scavengers, maint_workers, school_id); -// return "Staff Strength saved sucessfully"; -// } catch (DataAccessException e) { -// e.printStackTrace(); -// return "error"; -// } -// } - - - //initial - /*@Transactional - public String saveToilets(int total_toiletBlocks, int total_male_urinals, int total_wc_male, int total_wc_female, - int total_diffAbled_toilet, Boolean is_napkins, int school_id) { - String sql = "INSERT INTO toilet (total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female, total_diffAbled_toilet, is_napkins, school_id) VALUES (?, ?, ?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female, - total_diffAbled_toilet, is_napkins, school_id); - return "Toilet Details saved sucessfully"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "error"; - } - }*/ - @Transactional - public String saveToilets(Integer total_toiletBlocks, int total_male_urinals,int total_female_urinals,int staff_male_toilets,int staff_female_toilets, int total_wc_male, int total_wc_female, - int total_diffAbled_toilet, Boolean is_napkins, int school_id) { - String checkSql = "SELECT COUNT(*) FROM toilet WHERE school_id = ?"; - int count = jdbcTemplate.queryForObject(checkSql, Integer.class, school_id); - - if (count > 0) { - return "Toilet data already exists for this school. Insertion not allowed."; - } - - String insertSql = "INSERT INTO toilet (total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female, total_diffAbled_toilet, is_napkins, school_id,total_female_urinals,staff_male_toilet,staff_female_toilet) VALUES (?, ?, ?, ?, ?, ?, ?,?,?,?)"; - - try { - jdbcTemplate.update(insertSql, total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female, - total_diffAbled_toilet, is_napkins, school_id,total_female_urinals,staff_male_toilets,staff_female_toilets); - return "Toilet Details saved successfully"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error while saving toilet details"; - } - } -//initial - /*@Transactional - public String saveKitchen(Boolean is_cmbfs, Boolean is_cmbfsIndividual, Boolean is_noonmeal, - Boolean is_noonIndividual, Boolean is_vegGarden, Boolean is_anganwadi, String anganwadi_unique, - Boolean is_anganwadiIndividual, int school_id) { - String sql = "INSERT INTO kitchen (is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden, is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden, - is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id); - return "Kitchen Details saved sucessfully"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "error"; - } - }*/ - -@Transactional - public int saveKitchen(Boolean is_cmbfs, Boolean is_cmbfsIndividual, Boolean is_noonmeal, Boolean is_noonIndividual, - Boolean is_vegGarden, Boolean is_anganwadi, int school_id) { - String sql = "INSERT INTO kitchen (is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden, is_anganwadi, school_id) VALUES (?, ?, ?, ?, ?, ?, ?)"; - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setObject(1, is_cmbfs, Types.BOOLEAN); - ps.setObject(2, is_cmbfsIndividual, Types.BOOLEAN); - ps.setObject(3, is_noonmeal, Types.BOOLEAN); - ps.setObject(4, is_noonIndividual, Types.BOOLEAN); - ps.setObject(5, is_vegGarden, Types.BOOLEAN); - ps.setObject(6, is_anganwadi, Types.BOOLEAN); - ps.setInt(7, school_id); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - int playgoundID = generatedDataId.intValue(); - return playgoundID; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - } - - @Transactional - public void saveAnganwadi(String anganwadi_unique, Boolean is_anganwadiIndividual, int kitchen_id, int school_id) { - String sql = "INSERT INTO anganwadi_details (anganwadi_unique, is_anganwadiIndividual, kitchen_id, school_id) VALUES (?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, anganwadi_unique, is_anganwadiIndividual, kitchen_id, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - @Transactional - public void updateAnganwadiCheck(String anganwadi_unique, int school_id) { - String sql ="UPDATE room_details SET anganwadi_check = 1 WHERE anganwadi_unique_number = ? AND school_id = ?"; - - try { - jdbcTemplate.update(sql, anganwadi_unique, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - -//initial - /*@Transactional - public int savePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id) { - String sql = "INSERT INTO playground (is_playground, playground_area, is_court, school_id) VALUES (?, ?, ?, ?)"; - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setBoolean(1, is_playground); - ps.setDouble(2, playground_area); - ps.setBoolean(3, is_court); - ps.setInt(4, school_id); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - int playgoundID = generatedDataId.intValue(); - return playgoundID; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - - }*/ - @Transactional - public int savePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id) { - String checkSql = "SELECT playground_id FROM playground WHERE school_id = ?"; - List existing = jdbcTemplate.queryForList(checkSql, Integer.class, school_id); - - if (!existing.isEmpty()) { - // Return existing ID without inserting new row - return existing.get(0); - } - - // Insert new record - String insertSql = "INSERT INTO playground (is_playground, playground_area, is_court, school_id) VALUES (?, ?, ?, ?)"; - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); - ps.setBoolean(1, is_playground); - ps.setDouble(2, playground_area); - ps.setBoolean(3, is_court); - ps.setInt(4, school_id); - return ps; - }, keyHolder); - - Number generatedId = keyHolder.getKey(); - return generatedId != null ? generatedId.intValue() : 0; - } - - - - //initiall - /*@Transactional - public void saveEquipmentDetails(String equipment_id, int school_id, int playground_id) { - String sql = "INSERT INTO equipment_details (equipment_id, school_id, playground_id) VALUES (?, ?, ?)"; - try { - jdbcTemplate.update(sql, equipment_id, school_id, playground_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - }*/ - @Transactional - public boolean saveEquipmentDetails(String equipment_id, int school_id, int playground_id) { - String checkSql = "SELECT COUNT(*) FROM equipment_details WHERE equipment_id = ? AND school_id = ? AND playground_id = ?"; - Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, equipment_id, school_id, playground_id); - if (count != null && count < 0) { - return false; - } - - String insertSql = "INSERT INTO equipment_details (equipment_id, school_id, playground_id) VALUES (?, ?, ?)"; - jdbcTemplate.update(insertSql, equipment_id, school_id, playground_id); - return true; - } - - - - @Transactional - public void updatePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id, int playground_id) { - String sql = "UPDATE playground SET is_playground = ?, playground_area = ?, is_court = ? WHERE playground_id = ? AND school_id = ?"; - try { - int rows = jdbcTemplate.update(sql, is_playground, playground_area, is_court, playground_id, school_id); - System.out.println("✅ Rows affected (playground): " + rows); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - -//initial - /*@Transactional - public void saveCourtDetails(String court_id, int school_id, int playground_id) { - String sql = "INSERT INTO courts_details (court_id, school_id, playground_id) VALUES (?, ?, ?)"; - try { - jdbcTemplate.update(sql, court_id, school_id, playground_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - }*/ - @Transactional - public boolean saveCourtDetails(String court_id, int school_id, int playground_id) { - String checkSql = "SELECT COUNT(*) FROM courts_details WHERE court_id = ? AND school_id = ? AND playground_id = ?"; - Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, court_id, school_id, playground_id); - if (count != null && count > 0) { - return false; - } - - String insertSql = "INSERT INTO courts_details (court_id, school_id, playground_id) VALUES (?, ?, ?)"; - jdbcTemplate.update(insertSql, court_id, school_id, playground_id); - return true; - } - - public boolean existsDrinkingWaterData(int schoolId) { - String drinkingWaterSql = "SELECT COUNT(*) FROM drinking_water WHERE school_id = ?"; - String waterSupplySql = "SELECT COUNT(*) FROM water_supply WHERE school_id = ?"; - String waterStorageSql = "SELECT COUNT(*) FROM water_storage WHERE school_id = ?"; - - int drinkingWaterCount = jdbcTemplate.queryForObject(drinkingWaterSql, Integer.class, schoolId); - int waterSupplyCount = jdbcTemplate.queryForObject(waterSupplySql, Integer.class, schoolId); - int waterStorageCount = jdbcTemplate.queryForObject(waterStorageSql, Integer.class, schoolId); - - return drinkingWaterCount > 0 || waterSupplyCount > 0 || waterStorageCount > 0; - } - - - - - @Transactional - public int saveDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell, - Integer borewell_count, Boolean is_storage, int school_id,int drinkingwater_tap,int handwash_tap) { - String sql = "INSERT INTO drinking_water (is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id,drinkingwater_tap,handwash_tap) VALUES (?, ?, ?, ?, ?, ?,?,?)"; - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setBoolean(1, is_purifier); - // Handle possible null values - if (purifier_capacity != null) { - ps.setDouble(2, purifier_capacity); - } else { - ps.setNull(2, Types.DOUBLE); - } - - ps.setBoolean(3, is_borewell); - if (borewell_count != null) { - ps.setInt(4, borewell_count); - } else { - ps.setNull(4, Types.INTEGER); - } - ps.setBoolean(5, is_storage); - ps.setInt(6, school_id); - ps.setInt(7, drinkingwater_tap); - ps.setInt(8, handwash_tap); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - int drinking_water_id = generatedDataId.intValue(); - return drinking_water_id; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - - } - - @Transactional - public void saveWaterSupply(int source_water_id, String supply_type, int drinking_water_id, int school_id) { - String sql = "INSERT INTO water_supply (source_water_id, supply_type, drinking_water_id, school_id) VALUES (?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, source_water_id, supply_type, drinking_water_id, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - @Transactional - public void saveWaterStorage(double capacity, int storage_water_id, int drinking_water_id, int school_id) { - String sql = "INSERT INTO water_storage (capacity, storage_water_id, drinking_water_id, school_id) VALUES (?, ?, ?, ?)"; - try { - jdbcTemplate.update(sql, capacity, storage_water_id, drinking_water_id, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } -//initial - /*@Transactional - public void saveStaffStrength(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, int pgRegTeacher, int pgTempTeacher, - int pgPtTeacher, int pgNgoTeacher, int kgRegTeacher, int kgTempTeacher, int petRegTeacher, int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int totOa, int kgAyah, int compAss, - int watchmen, int scavengers, int maintenanceWork, int schoolId) { - String sql = "INSERT INTO staff_strength_1 (" - + "sg_reg_teacher, sg_temp_teacher, sg_pt_teacher, sg_ngo_teacher, " - + "bt_reg_teacher, bt_temp_teacher, bt_pt_teacher, bt_ngo_teacher, " - + "pg_reg_teacher, pg_temp_teacher, pg_pt_teacher, pg_ngo_teacher, " - + "kg_reg_teacher, kg_temp_teacher, pet_reg_teacher, pet_temp_teacher, pet_grade1_teacher, pet_grade2_teacher, tot_oa, kg_ayah, comp_ass, " - + "watchmen, scavengers, maintenance_work, school_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, btTempTeacher, - btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, kgRegTeacher, kgTempTeacher, - petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId); - }*/ - @Transactional - public String saveStaffStrength(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, int pgRegTeacher, int pgTempTeacher, - int pgPtTeacher, int pgNgoTeacher, int kgRegTeacher, int kgTempTeacher, int petRegTeacher, - int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int petPtTeacher, Boolean is_hm, - int stRegTeacher, int stPtTeacher, int totOa, int kgAyah, int compAss, String watchmen, int scavengers, - int maintenanceWork, int schoolId, List specialCategoryId) { - try { - int staff_id = saveStaffCounts(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, - btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, petPtTeacher, - is_hm, stRegTeacher, stPtTeacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId); - - if(!specialCategoryId.isEmpty()) { - for(String special_category_id : specialCategoryId) { - saveSpecialCategoryDetails(special_category_id, schoolId, staff_id); - } - } - - - return "Staff Details Saved Sucessfully"; - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - - } - - - - private void saveSpecialCategoryDetails(String special_category_id, int schoolId, int staff_id) { - - String sql = "INSERT INTO special_category_details (special_category_id, school_id, staff_id) VALUES (?, ?, ?)"; - try { - jdbcTemplate.update(sql, special_category_id, schoolId, staff_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - - public int saveStaffCounts(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, int pgRegTeacher, int pgTempTeacher, - int pgPtTeacher, int pgNgoTeacher, int kgRegTeacher, int kgTempTeacher, int petRegTeacher, int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, - int petPtTeacher,Boolean is_hm, int stRegTeacher, int stPtTeacher, - int totOa, int kgAyah, int compAss, String watchmen, int scavengers, int maintenanceWork, int schoolId) { - String sql = "INSERT INTO staff_strength_1 ( " - + " sg_reg_teacher, sg_temp_teacher, sg_pt_teacher, sg_ngo_teacher, " - + " bt_reg_teacher, bt_temp_teacher, bt_pt_teacher, bt_ngo_teacher, " - + " pg_reg_teacher, pg_temp_teacher, pg_pt_teacher, pg_ngo_teacher, " - + " kg_reg_teacher, kg_temp_teacher, " - + " pet_reg_teacher, pet_temp_teacher, pet_grade1_teacher, pet_grade2_teacher, pet_pt_teacher, " - + " is_hm, st_reg_teacher, st_pt_teacher, tot_oa, kg_ayah, comp_ass, " - + " watchmen, scavengers, maintenance_work, school_id) " - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; - - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, sgRegTeacher); - ps.setInt(2, sgTempTeacher); - ps.setInt(3, sgPtTeacher); - ps.setInt(4, sgNgoTeacher); - ps.setInt(5, btRegTeacher); - ps.setInt(6, btTempTeacher); - ps.setInt(7, btPtTeacher); - ps.setInt(8, btNgoTeacher); - ps.setInt(9, pgRegTeacher); - ps.setInt(10, pgTempTeacher); - ps.setInt(11, pgPtTeacher); - ps.setInt(12, pgNgoTeacher); - ps.setInt(13, kgRegTeacher); - ps.setInt(14, kgTempTeacher); - ps.setInt(15, petRegTeacher); - ps.setInt(16, petTempTeacher); - ps.setInt(17, petGrade1Teacher); - ps.setInt(18, petGrade2Teacher); - ps.setInt(19, petPtTeacher); - ps.setBoolean(20, is_hm); - ps.setInt(21, stRegTeacher); - ps.setInt(22, stPtTeacher); - ps.setInt(23, totOa); - ps.setInt(24, kgAyah); - ps.setInt(25, compAss); - ps.setString(26, watchmen); - ps.setInt(27, scavengers); - ps.setInt(28, maintenanceWork); - ps.setInt(29, schoolId); - return ps; - }, keyHolder); - Number generatedDataId = keyHolder.getKey(); - int playgoundID = generatedDataId.intValue(); - return playgoundID; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - } - - - @Transactional - public String getSchoolId(String user_id) { - String sql = "SELECT school_id FROM login_details WHERE user_id = ?"; - try { - return jdbcTemplate.queryForObject(sql, String.class, user_id); - } catch (DataAccessException e) { - - return "error"; - } - } - - public List> getSchoolData1(String schoolId) { - String sql = "SELECT * FROM school_list WHERE id In(" + schoolId + ")"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - - @Transactional - public Map getSchoolDetails(Long schoolId) { - String sql = "SELECT * FROM school_list WHERE id = ?"; - return jdbcTemplate.queryForMap(sql, schoolId); - } - - public List> filterSchools(String userId, String udise, String category, String zone, String division) { - StringBuilder sql = new StringBuilder( - "SELECT s.id, s.udise, s.school_name, s.category, s.zone, s.division, s.address " + - "FROM school_list s " + - "JOIN login_details l ON FIND_IN_SET(s.id, l.school_id) > 0 " + - "WHERE l.user_id = ?" - ); - - List params = new ArrayList<>(); - params.add(userId); // required - - if (udise != null && !udise.isEmpty()) { - sql.append(" AND s.udise = ?"); - params.add(udise); - } - if (category != null && !category.isEmpty()) { - sql.append(" AND s.category = ?"); - params.add(category); - } - if (zone != null && !zone.isEmpty()) { - sql.append(" AND s.zone = ?"); - params.add(zone); - } - if (division != null && !division.isEmpty()) { - sql.append(" AND s.division = ?"); - params.add(division); - } - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - @Transactional - public String updateOtherDetails(Double land_area, Double buildup_area, int is_compound, Boolean is_nameboard, - Boolean is_pasystem, Boolean is_bell, Boolean is_generator, int school_id) { - String sql = "UPDATE school_buildup_area SET land_area = ?, buildup_area = ?, is_compound = ?, is_nameboard = ?, is_pasystem = ?, is_bell = ?, is_generator = ? WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell, - is_generator, school_id); - return "Success"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - @Transactional - public String updateStudentDetails(int total_students, int total_girls, int total_boys, int others, int special_child,int school_id) { - String sql = "UPDATE student_strength SET total_students = ?, total_girls = ?, total_boys = ?, others = ?, special_child=? WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, total_students, total_girls, total_boys, others,special_child, school_id); - return "Success"; - }catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - //initial - /*@Transactional - public Map checkPlaygroundDetails(int school_id) { - String sql = "SELECT * FROM playground WHERE school_id = ? "; - try { - return jdbcTemplate.queryForMap(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - }*/ - @Transactional - public Map checkPlaygroundDetails(int school_id) { - String sql = "SELECT * FROM playground WHERE school_id = ? ORDER BY playground_id DESC LIMIT 1 "; - try { - return jdbcTemplate.queryForMap(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - } - private void updateCourtDetails(int court_id, int courts_detais_id) { - String sql = "UPDATE courts_details SET court_id = ? WHERE courts_detais_id = ? "; - try { - jdbcTemplate.update(sql, court_id, courts_detais_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - - } -// @Transactional -// public List> checkCourtDetails(int school_id) { -// String sql = "select cm.court_type,cd.Courts_detais_id " -// + "FROM " -// + "playground p\r\n" -// + "INNER JOIN " -// + " courts_details cd ON p.playground_id = cd.playground_id\r\n" -// + "INNER JOIN " -// + " courts_master cm ON cd.court_id = cm.court_id\r\n" -// + " WHERE " -// + " p.school_id = ?"; -// try { -// return jdbcTemplate.queryForList(sql, school_id); -// } catch (Exception e) { -// e.printStackTrace(); -// return List.of(); -// } -// } - //initial - /*@Transactional - public List> checkCourtDetails(int school_id) { - String sql = """ - SELECT cm.court_type, cd.Courts_detais_id, cd.court_id - FROM playground p - INNER JOIN courts_details cd ON p.playground_id = cd.playground_id - INNER JOIN courts_master cm ON cd.court_id = cm.court_id - WHERE p.school_id = ? and cd.is_active = 1 - """; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - }*/ - - @Transactional - public List> checkCourtDetails(int schoolId) { - String sql = "" + - "SELECT \n" + - " cm.court_type, \n" + - " cd.Courts_detais_id, \n" + - " cd.court_id, \n" + - " p.* \n" + - "FROM gcc_school.playground p \n" + - "INNER JOIN gcc_school.courts_details cd ON p.playground_id = cd.playground_id \n" + - "INNER JOIN gcc_school.courts_master cm ON cd.court_id = cm.court_id \n" + - "WHERE p.school_id = ? \n" + - " AND cd.is_active = 1 \n" + - " AND p.playground_id = ( \n" + - " SELECT MAX(playground_id) \n" + - " FROM gcc_school.playground \n" + - " WHERE school_id = ? \n" + - " )"; - - try { - return jdbcTemplate.queryForList(sql, schoolId, schoolId); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - - @Transactional -// public List> checkEquipmentDetails(int school_id) { -// String sql = "select em.equipment_type,ed.equipment_detais_id " -// + "FROM " -// + "playground p\r\n" -// + "INNER JOIN " -// + " equipment_details ed ON p.playground_id = ed.playground_id\r\n" -// + "INNER JOIN " -// + " equipment_master em ON ed.equipment_id = em.equipment_id\r\n" -// + " WHERE " -// + " p.school_id = ?"; -// try { -// return jdbcTemplate.queryForList(sql, school_id); -// } catch (Exception e) { -// e.printStackTrace(); -// return List.of(); -// } -// } - //ajith - //initial - /*public List> checkEquipmentDetails(int school_id) { - String sql = """ - SELECT em.equipment_id, em.equipment_type, ed.equipment_detais_id - FROM playground p - INNER JOIN equipment_details ed ON p.playground_id = ed.playground_id - INNER JOIN equipment_master em ON ed.equipment_id = em.equipment_id - WHERE p.school_id = ? and ed.is_active = 1 """; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - }*/ - public List> checkEquipmentDetails(int school_id) { - String sql = "" + - "SELECT em.equipment_id, em.equipment_type, ed.equipment_detais_id \n" + - "FROM playground p \n" + - "INNER JOIN equipment_details ed ON p.playground_id = ed.playground_id \n" + - "INNER JOIN equipment_master em ON ed.equipment_id = em.equipment_id \n" + - "WHERE p.school_id = ? \n" + - " AND ed.is_active = 1 \n" + - " AND p.playground_id = ( \n" + - " SELECT MAX(playground_id) \n" + - " FROM playground \n" + - " WHERE school_id = ? \n" + - " )"; - - try { - return jdbcTemplate.queryForList(sql, school_id, school_id); // pass school_id twice - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - -private void updateEquipmentDetails(Integer equipment_id, int equipment_detais_id) { - - String sql = "UPDATE equipment_details SET equipment_id = ? WHERE equipment_detais_id = ? "; - try { - jdbcTemplate.update(sql, equipment_id, equipment_detais_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - } - - /*private void updatePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id, int playground_id) { - String sql = "UPDATE playground SET is_playground = ?, playground_area = ?, is_court = ? WHERE playground_id = ? and school_id = ? "; - try { - jdbcTemplate.update(sql, is_playground, playground_area, is_court, playground_id, school_id); - - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - - }*/ - - - - - - -// @Transactional -// public String updatePlaygroundDetails(Boolean is_playground, Double playground_area, Boolean is_court, -// List> equipments, List> courts, int playground_id, int school_id) { -// try { -// // Update playground main record -// updatePlayground(is_playground, playground_area, is_court, school_id, playground_id); -// -// // Update equipment details with null-safe checks -// for (Map equipment : equipments) { -// Object equipDetIdObj = equipment.get("equipment_detais_id"); -// Object equipIdObj = equipment.get("equipment_id"); -// -// if (equipDetIdObj != null && equipIdObj != null) { -// int equipment_detais_id = Integer.parseInt(equipDetIdObj.toString()); -// int equipment_id = Integer.parseInt(equipIdObj.toString()); -// updateEquipmentDetails(equipment_id, equipment_detais_id); -// } else { -// System.out.println("⚠️ Skipping equipment update — missing equipment_id or equipment_detais_id: " + equipment); -// } -// } -// if(is_court.booleanValue()) { -// // Update court details with null-safe checks -// for (Map court : courts) { -// Object courtDetIdObj = court.get("Courts_detais_id"); -// Object courtIdObj = court.get("court_id"); -// -// if (courtDetIdObj != null && courtIdObj != null) { -// int Courts_detais_id = Integer.parseInt(courtDetIdObj.toString()); -// int court_id = Integer.parseInt(courtIdObj.toString()); -// updateCourtDetails(court_id, Courts_detais_id); -// } else { -// System.out.println("⚠️ Skipping court update — missing court_id or Courts_detais_id: " + court); -// } -// } -// } -// else { -// //inactiveCourtDetails(school_id); -// } -// return "Success"; -// -// } catch (Exception e) { -// e.printStackTrace(); -// return "Error"; -// } -// } -@Transactional -public String updatePlaygroundDetails(Boolean is_playground, Double playground_area, Boolean is_court, - List> equipments, List> courts, int playground_id, int school_id) { - try { - // Step 1: Update main playground table - updatePlayground(is_playground, playground_area, is_court, school_id, playground_id); - - // Step 2: Deactivate old entries - deactiveCourts(school_id); - deactiveEquipments(school_id); - - // Step 3: Re-insert new equipment selections - for (Map equipment : equipments) { - Object equipmentIdObj = equipment.get("equipment_id"); - if (equipmentIdObj != null) { - String equipment_id = equipmentIdObj.toString(); - saveEquipmentDetails(equipment_id, school_id, playground_id); - } else { - System.out.println("⚠️ Skipping equipment insert — missing equipment_id: " + equipment); - } - } - - // Step 4: Re-insert new court selections (only if court is enabled) - if (Boolean.TRUE.equals(is_court)) { - for (Map court : courts) { - Object courtIdObj = court.get("court_id"); - if (courtIdObj != null) { - String court_id = courtIdObj.toString(); - saveCourtDetails(court_id, school_id, playground_id); - } else { - System.out.println("⚠️ Skipping court insert — missing court_id: " + court); - } - } - } - - return "Success"; - - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } -} - - @Transactional - public void deactiveCourts(int school_id) { - String sql = "UPDATE courts_details SET is_active = false WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, school_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - } - - @Transactional - public void deactiveEquipments(int school_id) { - String sql = "UPDATE equipment_details SET is_active = false WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, school_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - - } - - public void updateKitchenDetails(Boolean is_cmbfs, Boolean is_cmbfsIndividual, Boolean is_noonmeal, - Boolean is_noonIndividual, Boolean is_vegGarden, Boolean is_anganwadi,int school_id) { - System.out.println("inside"); - String sql = "UPDATE kitchen SET is_cmbfs = ?, is_cmbfsIndividual = ?, is_noonmeal = ?, is_noonIndividual = ?, is_vegGarden = ?, is_anganwadi = ? WHERE school_id = ? "; - - try { - jdbcTemplate.update(sql, is_cmbfs,is_cmbfsIndividual,is_noonmeal,is_noonIndividual,is_vegGarden,is_anganwadi, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - public void saveOldAnganwadi(String anganwadi_unique, Boolean is_anganwadiIndividual, int school_id) { - - String sql = "UPDATE anganwadi_details SET is_anganwadiIndividual = ? WHERE school_id = ? AND anganwadi_unique=?"; - - try { - jdbcTemplate.update(sql,is_anganwadiIndividual,school_id,anganwadi_unique); - } catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - public int getKitchenIdbySchId(int school_id) { - - String sql = "SELECT kitchen_id FROM kitchen WHERE school_id=? Limit 1"; - - try { - return jdbcTemplate.queryForObject(sql, new Object[]{school_id}, Integer.class); - } catch (EmptyResultDataAccessException e) { - // No kitchen found for this school_id - return 0; - } - - } - - public void saveNewAnganwadi(String new_anganwadi_unique, Boolean new_is_anganwadiIndividual, int kitchen_id, - int school_id) { - - String sql = "INSERT INTO anganwadi_details (anganwadi_unique, is_anganwadiIndividual, kitchen_id, school_id) VALUES (?, ?, ?, ?)"; - - try { - jdbcTemplate.update(sql, new_anganwadi_unique, new_is_anganwadiIndividual, kitchen_id, school_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - //initial - /*@Transactional - public Map checkKitchenDetails(int school_id) { - String sql = "SELECT * FROM kitchen WHERE school_id = ?"; - try { - return jdbcTemplate.queryForMap(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - }*/ - @Transactional - public Map checkKitchenDetails(int school_id) { - String sql = "SELECT * FROM kitchen WHERE school_id = ? ORDER BY kitchen_id DESC LIMIT 1"; - try { - return jdbcTemplate.queryForMap(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - } - @Transactional - public List> checkOldAnganwadiDetails(int school_id) { - String sql = "SELECT * FROM anganwadi_details WHERE school_id = ? AND is_active = 1 AND is_delete = 0"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - @Transactional - public List> checkNewAnganwadiDetails(int school_id) { - String sql = "SELECT * FROM room_details WHERE school_id = ? AND anganwadi_check = 0 AND is_active = 1 AND is_delete = 0"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - /*@Transactional - public String updateStaffDetails(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, - int pgRegTeacher, int pgTempTeacher, int pgPtTeacher, int pgNgoTeacher, - int kgTeacher, int petTeacher, int totOa, int kgAyah, int compAss, - int watchmen, int scavengers, int maintenanceWork, int school_id) { - String sql = "UPDATE staff_strength_1 SET sg_reg_teacher = ?, sg_temp_teacher = ?, sg_pt_teacher = ?, sg_ngo_teacher = ?," - + " bt_reg_teacher = ?, bt_temp_teacher = ?, bt_pt_teacher = ?, bt_ngo_teacher = ?, " - + "pg_reg_teacher = ?, pg_temp_teacher = ?, pg_pt_teacher = ?, pg_ngo_teacher = ?," - + "kg_teacher = ?, pet_teacher = ?, tot_oa = ?, kg_ayah = ?, comp_ass = ?, watchmen = ?," - + " scavengers = ?, maintenance_work = ?WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, - btRegTeacher, btTempTeacher, btPtTeacher, btNgoTeacher, - pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgTeacher, petTeacher, totOa, kgAyah, compAss, - watchmen, scavengers, maintenanceWork, school_id); - return "Success"; - }catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - }*/ - @Transactional - public String updateStaffDetails(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, - int pgRegTeacher, int pgTempTeacher, int pgPtTeacher, int pgNgoTeacher, - int kgRegTeacher, int kgTempTeacher, int petRegTeacher, int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int totOa, int kgAyah, int compAss, - int watchmen, int scavengers, int maintenanceWork, int school_id) { - - String sql = "UPDATE staff_strength_1 SET sg_reg_teacher = ?, sg_temp_teacher = ?, sg_pt_teacher = ?, sg_ngo_teacher = ?," + - " bt_reg_teacher = ?, bt_temp_teacher = ?, bt_pt_teacher = ?, bt_ngo_teacher = ?, " + - " pg_reg_teacher = ?, pg_temp_teacher = ?, pg_pt_teacher = ?, pg_ngo_teacher = ?," + - " kg_reg_teacher = ?, kg_temp_teacher = ?, pet_reg_teacher = ?, pet_temp_teacher = ?, pet_grade1_teacher = ?, pet_grade2_teacher = ?, tot_oa = ?, kg_ayah = ?, comp_ass = ?, watchmen = ?," + - " scavengers = ?, maintenance_work = ? WHERE school_id = ?"; - - try { - int rowsAffected = jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, - btRegTeacher, btTempTeacher, btPtTeacher, btNgoTeacher, - pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, totOa, kgAyah, compAss, - watchmen, scavengers, maintenanceWork, school_id); - - if (rowsAffected == 0) { - return "No data found for given school_id"; - } else { - return "Success"; - } - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - //initial - /*@Transactional - public Map checkWaterDetails(int school_id) { - String sql = "select drinking_water_id, is_purifier, borewell_count, is_borewell, is_storage, purifier_capacity from drinking_water where school_id = ?"; - try { - return jdbcTemplate.queryForMap(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - }*/ - @Transactional - public Map checkWaterDetails(int school_id) { - String sql = "select drinking_water_id, is_purifier, borewell_count, is_borewell, is_storage, purifier_capacity from drinking_water where school_id = ? ORDER BY drinking_water_id DESC LIMIT 1"; - try { - return jdbcTemplate.queryForMap(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyMap(); - } - } - //initial - /*@Transactional - public List> checkWaterSource(int school_id) { - String sql = "select ws.water_supply_id, ws.source_water_id, ws.supply_type, sw.water_type " - + "FROM " - + "drinking_water dw\r\n" - + "INNER JOIN " - + " water_supply ws ON dw.drinking_water_id = ws.drinking_water_id\r\n" - + "INNER JOIN " - + " source_water sw ON ws.source_water_id = sw.source_water_id\r\n" - + " WHERE " - + " dw.school_id = ? and ws.is_active = 1"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - }*/ - @Transactional - public List> checkWaterSource(int school_id) { - String sql = "select ws.water_supply_id, ws.source_water_id, ws.supply_type, sw.water_type " - + "FROM " - + "drinking_water dw\r\n" - + "INNER JOIN " - + " water_supply ws ON dw.drinking_water_id = ws.drinking_water_id\r\n" - + "INNER JOIN " - + " source_water sw ON ws.source_water_id = sw.source_water_id\r\n" - + " WHERE " - + " dw.school_id = ? and ws.is_active = 1 ORDER BY water_supply_id";// DESC LIMIT 1"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } -// @Transactional -// public String updateDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell, -// int borewell_count, Boolean is_storage, int drinking_water_id, int school_id, -// List> supply, List> storage) { -// try { -// updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id, drinking_water_id); -// for (Map supplies : supply) { -// int water_supply_id = Integer.parseInt(supplies.get("water_supply_id").toString()); -// int source_water_id = Integer.parseInt(supplies.get("source_water_id").toString()); -// String supply_type = (String) supplies.get("supply_type"); -// updateWaterSupplyDetails(water_supply_id, source_water_id, supply_type); -// } -// -// for (Map store : storage) { -// int water_storage_id = Integer.parseInt(store.get("water_storage_id").toString()); -// int storage_water_id = Integer.parseInt(store.get("storage_water_id").toString()); -// Double capacity = (Double) store.get("capacity"); -// updateWaterStorageDetails(water_storage_id, storage_water_id, capacity); -// } -// return "Sucess"; -// } catch (Exception e) { -// e.printStackTrace(); -// return "Error"; -// } -// } - - //Ajithh - @Transactional - public String updateDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell, - int borewell_count, Boolean is_storage, int drinking_water_id, int school_id, - List> supply, List> storage) { - try { - // Step 1: Update main table - //updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id, drinking_water_id); - - // Step 2: UPSERT for water supply - for (Map item : supply) { - int source_water_id = Integer.parseInt(item.get("source_water_id").toString()); - String supply_type = item.get("supply_type").toString(); - - // Check if record exists - String checkSql = "SELECT COUNT(*) FROM water_supply WHERE drinking_water_id = ? AND source_water_id = ?"; - Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, drinking_water_id, source_water_id); - - if (count != null && count > 0) { - // Update existing - jdbcTemplate.update("UPDATE water_supply SET supply_type = ?, is_active = 1 WHERE drinking_water_id = ? AND source_water_id = ?", - supply_type, drinking_water_id, source_water_id); - - - } else { - // Insert new - jdbcTemplate.update("INSERT INTO water_supply (drinking_water_id, source_water_id, supply_type, school_id) VALUES (?, ?, ?, ?)", - drinking_water_id, source_water_id, supply_type, school_id); - } - } - - // Step 3: UPSERT for water storage - for (Map item : storage) { - int storage_water_id = Integer.parseInt(item.get("storage_water_id").toString()); - double capacity = Double.parseDouble(item.get("capacity").toString()); - - String checkSql = "SELECT COUNT(*) FROM water_storage WHERE drinking_water_id = ? AND storage_water_id = ?"; - Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, drinking_water_id, storage_water_id); - - if (count != null && count > 0) { - jdbcTemplate.update("UPDATE water_storage SET capacity = ?, is_active = 1 WHERE drinking_water_id = ? AND storage_water_id = ?", - capacity, drinking_water_id, storage_water_id); - - } else { - jdbcTemplate.update("INSERT INTO water_storage (drinking_water_id, storage_water_id, capacity, school_id) VALUES (?, ?, ?, ?)", - drinking_water_id, storage_water_id, capacity, school_id); - } - } - - return "Sucess"; - - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - - -// private void updateWaterStorageDetails(int water_storage_id, int storage_water_id, Double capacity) { -// String sql = "UPDATE water_storage SET capacity = ?, storage_water_id = ? WHERE water_storage_id = ? "; -// try { -// jdbcTemplate.update(sql, capacity, storage_water_id, water_storage_id); -// -// }catch (DataAccessException e) { -// e.printStackTrace(); -// -// } -// -// } -// -// private void updateWaterSupplyDetails(int water_supply_id, int source_water_id, String supply_type) { -// String sql = "UPDATE water_supply SET source_water_id = ?, supply_type = ? WHERE water_supply_id = ? "; -// try { -// jdbcTemplate.update(sql, source_water_id, supply_type, water_supply_id); -// -// }catch (DataAccessException e) { -// e.printStackTrace(); -// -// } -// -// } -// -// private void updateDrinkWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell, -// int borewell_count, Boolean is_storage, int school_id, int drinking_water_id) { -// -// String sql = "UPDATE drinking_water SET is_purifier = ?, purifier_capacity = ?, is_borewell = ?, borewell_count = ?, is_storage = ? WHERE drinking_water_id = ? and school_id = ? "; -// try { -// jdbcTemplate.update(sql, is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, drinking_water_id, school_id); -// -// }catch (DataAccessException e) { -// e.printStackTrace(); -// -// } -// } - //ajith - @Transactional - public void updateDrinkWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell, - int borewell_count, Boolean is_storage, int school_id, int drinking_water_id,int drinkingwater_tap,int handwash_tap) { - - - String sql = "UPDATE drinking_water SET is_purifier = ?, purifier_capacity = ?, is_borewell = ?, borewell_count = ?, is_storage = ?,drinkingwater_tap=?,handwash_tap=? WHERE drinking_water_id = ? and school_id = ? "; - try { - jdbcTemplate.update(sql, is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage,drinkingwater_tap, handwash_tap,drinking_water_id, school_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - } - - @Transactional - public void deactiveWaterSupply(int school_id, int drinking_water_id) { - String sql = "UPDATE water_supply SET is_active = false WHERE school_id = ? and drinking_water_id = ? "; - try { - jdbcTemplate.update(sql, school_id, drinking_water_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - - } - - @Transactional - public void deactiveWaterStorage(int school_id, int drinking_water_id) { - String sql = "UPDATE water_storage SET is_active = false WHERE school_id = ? and drinking_water_id = ? "; - try { - jdbcTemplate.update(sql, school_id, drinking_water_id); - - }catch (DataAccessException e) { - e.printStackTrace(); - - } - - } - - private void updateWaterSupplyDetails(int water_supply_id, int source_water_id, String supply_type) { - String sql = "UPDATE water_supply SET source_water_id = ?, supply_type = ? WHERE water_supply_id = ?"; - try { - jdbcTemplate.update(sql, source_water_id, supply_type, water_supply_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - - private void updateWaterStorageDetails(int water_storage_id, int storage_water_id, Double capacity) { - String sql = "UPDATE water_storage SET capacity = ?, storage_water_id = ? WHERE water_storage_id = ?"; - try { - jdbcTemplate.update(sql, capacity, storage_water_id, water_storage_id); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - - //initial - - /*@Transactional - public List> checkWaterStotage(int school_id) { - String sql = " select wst.water_storage_id, wst.capacity, wstm.storage_type\r\n" - + " FROM " - + " drinking_water dw\r\n" - + " INNER JOIN\r\n" - + " water_storage wst ON dw.drinking_water_id = wst.drinking_water_id " - + "INNER JOIN\r\n" - + " water_storage_master wstm ON wst.storage_water_id = wstm.storage_water_id " - + "WHERE " - + " dw.school_id = ? and wst.is_active = 1"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - }*/ - @Transactional - public List> checkWaterStotage(int school_id) { - String sql = " select wst.water_storage_id, wst.capacity, wstm.storage_type\r\n" - + " FROM " - + " drinking_water dw\r\n" - + " INNER JOIN\r\n" - + " water_storage wst ON dw.drinking_water_id = wst.drinking_water_id " - + "INNER JOIN\r\n" - + " water_storage_master wstm ON wst.storage_water_id = wstm.storage_water_id " - + "WHERE " - + " dw.school_id = ? and wst.is_active = 1 ORDER BY water_storage_id"; //DESC LIMIT 1"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } -//initial - /*@Transactional - public List> checkToiletDetails(int school_id) { - String sql = "SELECT * FROM toilet WHERE school_id = ?"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - }*/ - @Transactional - public List> checkToiletDetails(int school_id) { - String sql = "SELECT * FROM toilet WHERE school_id = ? ORDER BY toilet_id DESC LIMIT 1"; - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public String updateToiletDetails(Integer total_toiletBlocks, int total_male_urinals, int total_female_urinals,int staff_male_toilets,int staff_female_toilets,int total_wc_male, - int total_wc_female, int total_diffAbled_toilet, Boolean is_napkins, int school_id) { - String sql = "UPDATE toilet SET total_toiletBlocks = ?, total_male_urinals = ?,total_female_urinals=?,staff_male_toilet=?,staff_female_toilet=?, total_wc_male = ?, total_wc_female = ?, total_diffAbled_toilet = ?, is_napkins = ? WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, total_toiletBlocks, total_male_urinals,total_female_urinals,staff_male_toilets,staff_female_toilets, total_wc_male, total_wc_female, - total_diffAbled_toilet, is_napkins, school_id); - return "Success"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - - @Transactional - public String saveAssetMaster(int sub_asset_id, int master_qty, int school_id, int asset_id) { - String sql =""; - if(asset_id==2) { - sql = "INSERT INTO electrical_master (sub_asset_id, master_qty, unmapped_qty, school_id) VALUES (?, ?, ?, ?)"; - } else if(asset_id==3) { - sql = "INSERT INTO furniture_master (sub_asset_id, master_qty, unmapped_qty, school_id) VALUES (?, ?, ?, ?)"; - } - try { - jdbcTemplate.update(sql, sub_asset_id, master_qty, master_qty, school_id); - return "Success"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - - @Transactional - public List> getAssetMaster(int school_id, int asset_id) { - String sql=""; - if(asset_id==2) { - sql = "SELECT asm.asset_name, em.electrical_master_id, em.master_qty, em.mapped_qty, em.unmapped_qty, em.scrap_qty from electrical_master em " - + "INNER JOIN asset_sub_master asm ON em.sub_asset_id = asm.sub_asset_id\r\n" - + " WHERE em.school_id = ?"; - } else if(asset_id==3) { - sql = "SELECT asm.asset_name, fm.furniture_master_id, fm.master_qty, fm.mapped_qty, fm.unmapped_qty, fm.scrap_qty from furniture_master fm " - + "INNER JOIN asset_sub_master asm ON fm.sub_asset_id = asm.sub_asset_id\r\n" - + " WHERE fm.school_id = ?"; - } - try { - return jdbcTemplate.queryForList(sql, school_id); - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public Map getAssetMasterById(int assetMasterId, int asset_id) { - String sql=""; - if(asset_id==2) { - sql = "SELECT em.*,asm.asset_name from electrical_master em INNER JOIN asset_sub_master asm ON em.sub_asset_id = asm.sub_asset_id where em.electrical_master_id = ?"; - } else if(asset_id==3) { - sql = "SELECT fm.*,asm.asset_name from furniture_master fm INNER JOIN asset_sub_master asm ON fm.sub_asset_id = asm.sub_asset_id where fm.furniture_master_id = ?"; - } - try { - return jdbcTemplate.queryForMap(sql, assetMasterId); - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - @Transactional - public String updateAssetMaster(int assetMasterId, int master, int asset_id, int unmapped) { - String sql =""; - if (asset_id == 2) { - sql = "UPDATE electrical_master SET master_qty = ?, unmapped_qty = ? WHERE electrical_master_id = ? "; - } else if(asset_id==3) { - sql = "UPDATE furniture_master SET master_qty = ?, unmapped_qty = ? WHERE furniture_master_id = ? "; - } - try { - jdbcTemplate.update(sql, master, unmapped, assetMasterId); - return "Success"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "Error"; - } - } - - public List> getAnganwadiDetailsBySchId(int school_id) { - - String sql = "SELECT rd.room_id,rd.room_num AS room_name,bd.building_name, " - + "rd.building_id,fl.floor_name AS floor, " - + "rm.room_type,rd.school_id,rm.room_master_id,rd.anganwadi_unique_number, " - + "fl.floors_id FROM room_details rd " - + "JOIN buildings bd ON bd.buildng_id = rd.building_id " - + "JOIN floor_list fl ON fl.floors_id = rd.floors_id " - + "JOIN room_master rm ON rd.room_type = rm.room_master_id " - + "WHERE rd.school_id = ? AND rd.is_active = 1 AND rd.is_delete = 0 AND rd.room_type='32' AND rd.anganwadi_check = 0"; - - return jdbcTemplate.queryForList(sql, school_id); - } - public String updateStaffStrength(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, int pgRegTeacher, int pgTempTeacher, - int pgPtTeacher, int pgNgoTeacher, int kgRegTeacher, int kgTempTeacher, int petRegTeacher, - int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int petPtTeacher, Boolean is_hm, - int stRegTeacher, int stPtTeacher, int totOa, int kgAyah, int compAss, String watchmen, int scavengers, - int maintenanceWork, int schoolId, List specialCategoryId) { - - try { - updateStaffCounts(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, - btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, - kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, petPtTeacher, - is_hm, stRegTeacher, stPtTeacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId); - - if(specialCategoryId.isEmpty()) { - deactivateSpecialCategory(schoolId); - } - - if(!specialCategoryId.isEmpty()) { - - int staffId=getstaffId(schoolId); - if(staffId!=0) { - deactivateSpecialCategory(schoolId); - for(String special_category_id : specialCategoryId) { - saveSpecialCategoryDetails(special_category_id, schoolId, staffId); - } - } - - } - - - return "Staff Details Updated Sucessfully"; - } catch (Exception e) { - e.printStackTrace(); - return "Error"; - } - } - - private int getstaffId(int schoolId) { - - String sql = "SELECT staff_id FROM staff_strength_1 WHERE school_id = ? ORDER BY staff_id DESC LIMIT 1"; - try { - return jdbcTemplate.queryForObject(sql, new Object[]{schoolId}, Integer.class); - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; // or any default/fallback value - } - } - - @Transactional - public void deactivateSpecialCategory(int schoolId) { - - String sql = "UPDATE special_category_details SET is_active = 0 AND is_delete = 1 WHERE school_id = ? "; - try { - jdbcTemplate.update(sql, schoolId); - }catch (DataAccessException e) { - e.printStackTrace(); - } - - } - - private void updateStaffCounts(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher, - int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, int pgRegTeacher, int pgTempTeacher, - int pgPtTeacher, int pgNgoTeacher, int kgRegTeacher, int kgTempTeacher, int petRegTeacher, - int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int petPtTeacher, Boolean is_hm, - int stRegTeacher, int stPtTeacher, int totOa, int kgAyah, int compAss, String watchmen, int scavengers, - int maintenanceWork, int schoolId) { - - String sql = "UPDATE staff_strength_1 SET " - + "sg_reg_teacher = ?, sg_temp_teacher = ?, sg_pt_teacher = ?, sg_ngo_teacher = ?, " - + "bt_reg_teacher = ?, bt_temp_teacher = ?, bt_pt_teacher = ?, bt_ngo_teacher = ?, " - + "pg_reg_teacher = ?, pg_temp_teacher = ?, pg_pt_teacher = ?, pg_ngo_teacher = ?, " - + "kg_reg_teacher = ?, kg_temp_teacher = ?, " - + "pet_reg_teacher = ?, pet_temp_teacher = ?, pet_grade1_teacher = ?, pet_grade2_teacher = ?, pet_pt_teacher = ?, " - + "is_hm = ?, st_reg_teacher = ?, st_pt_teacher = ?, tot_oa = ?, kg_ayah = ?, comp_ass = ?, " - + "watchmen = ?, scavengers = ?, maintenance_work = ? " - + "WHERE school_id = ?"; - - - try { - - jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, - btRegTeacher, btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, - pgPtTeacher, pgNgoTeacher, kgRegTeacher, kgTempTeacher, petRegTeacher, - petTempTeacher, petGrade1Teacher, petGrade2Teacher, petPtTeacher, is_hm, - stRegTeacher, stPtTeacher, totOa, kgAyah, compAss, watchmen, scavengers, - maintenanceWork, schoolId); - } catch (DataAccessException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolReportService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolReportService.java deleted file mode 100644 index 12470d70..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolReportService.java +++ /dev/null @@ -1,540 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Service; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.stereotype.Service; - -@Service -public class SchoolReportService { - private JdbcTemplate jdbcTemplate; - - - private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); - } - - @Transactional - public ResponseEntity getAEOList() { - Map result = new HashMap<>(); - String sql = "SELECT aeo_details_id, aeo_num, udise FROM aeo_details"; - - try { - List> data = jdbcTemplate.queryForList(sql); - result.put("Message", "Success"); - result.put("data", data); - return ResponseEntity.ok(result); - } catch (Exception e) { - e.printStackTrace(); - result.put("Message", "Error"); - result.put("Error", "Failed to fetch AEO List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - - @Transactional - public ResponseEntity getAEOZone(String udise) { - Map result = new HashMap<>(); - - String sql = "SELECT DISTINCT zone FROM school_list WHERE udise In(" + udise + ") ORDER BY zone ASC"; - try { - List data = jdbcTemplate.queryForList(sql, String.class); - result.put("message", "Success"); - result.put("data", data); - return ResponseEntity.ok(result); - } catch (DataAccessException e) { - e.printStackTrace(); - result.put("message", "Error"); - result.put("Error", "Failed to Zone List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - - @Transactional - public ResponseEntity getAEOWard(String udise, String zone) { - Map result = new HashMap<>(); - - String sql = "SELECT DISTINCT division AS Ward FROM school_list WHERE udise In(" + udise + ") and zone = ? ORDER BY Ward ASC"; - try { - List data = jdbcTemplate.queryForList(sql, String.class, zone); - result.put("message", "Success"); - result.put("data", data); - return ResponseEntity.ok(result); - } catch (DataAccessException e) { - e.printStackTrace(); - result.put("message", "Error"); - result.put("Error", "Failed to Ward List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - - @Transactional - public ResponseEntity getAEOSchoolData(List udise, String zone, String ward) { - Map response = new HashMap<>(); - - List> data = new ArrayList>(); - if(udise==null || udise.isEmpty()) { - udise=getUDISE(); - } - for(String udises:udise) { - List school = getschoolId(udises, zone, ward); - if(!school.isEmpty() && school!=null) { - for(String sch:school) { - //System.out.println("School_ID = "+sch); - - Map result = new HashMap<>(); - Map report = getSchoolReport(sch); - result.putAll(report); - String num = (String) report.get("udise"); - Map report1 = getSchoolReport1(sch); - result.putAll(report1); - int pending=0; - for (Map.Entry entry : report1.entrySet()) { - if(entry.getValue().toString().equalsIgnoreCase("Pending")) { - - ++pending; - } - } - result.put("overall_status", pending==0 ? "Completed" : "Pending"); - - Map report2 = getAEO(num); - result.putAll(report2); - data.add(result); - - } - response.put("message", "Success"); - response.put("data", data); - } - } -// System.out.println(data.get(0)); -// System.out.println(data.get(1)); - System.out.println(response.get("message")); -// System.out.println(response.get("data")); - return ResponseEntity.ok(response); - - } - - private List getUDISE() { - String sql = "SELECT udise FROM aeo_details"; - try { - return jdbcTemplate.queryForList(sql, String.class); - - } catch (Exception e) { - e.printStackTrace(); - return List.of(); - } - } - - private Map getAEO(String num) { - String sql = "SELECT aeo_num FROM aeo_details WHERE FIND_IN_SET(?, udise) > 0"; - try { - return jdbcTemplate.queryForMap(sql, num); - - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - private Map getSchoolReport1(String sch) { - String sql = "SELECT " - + " CASE " - + " WHEN EXISTS ( " - + " SELECT 1 " - + " FROM school_buildup_area sba " - + " WHERE sba.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS other_details, " - + " CASE " - + " WHEN EXISTS ( " - + " SELECT 1 " - + " FROM staff_strength_1 ss " - + " WHERE ss.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS staff_details, " - + " CASE " - + " WHEN EXISTS ( " - + " SELECT 1 " - + " FROM student_strength sts " - + " WHERE sts.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS students_details, " - + " CASE " - + " WHEN EXISTS ( " - + " SELECT 1 " - + " FROM playground pg " - + " WHERE pg.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS playground_details, " - + " CASE " - + " WHEN EXISTS (" - + " SELECT 1 " - + " FROM drinking_water dw " - + " WHERE dw.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS drinkingwater_details, " - + " CASE " - + " WHEN EXISTS ( " - + " SELECT 1 " - + " FROM toilet tot " - + " WHERE tot.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS toilet_details, " - + " CASE " - + " WHEN EXISTS ( " - + " SELECT 1 " - + " FROM kitchen kit " - + " WHERE kit.school_id = ? " - + " ) THEN 'Completed' " - + " ELSE 'Pending' " - + " END AS kitchen_details, " - + " CASE " - + " WHEN NOT EXISTS ( " - + " SELECT 1 FROM buildings WHERE school_id = ? and is_active=1 and is_delete=0 " - + " ) THEN 'Pending' " - + " WHEN ( " - + " SELECT COUNT(*) FROM buildings WHERE school_id = ? and is_active=1 and is_delete=0 " - + " ) = ( " - + " SELECT COUNT(DISTINCT rd.building_id) " - + " FROM room_details rd " - + " JOIN buildings b ON b.buildng_id = rd.building_id " - + " WHERE b.school_id = ? and b.is_active=1 and b.is_delete=0 and rd.is_active=1 and rd.is_delete=0 " - + " ) THEN 'Completed' " - + " ELSE 'Partially Completed' " - + "END AS buildings, " - + "CASE " - + " WHEN NOT EXISTS ( " - + " SELECT 1 FROM room_details WHERE school_id = ? and is_active=1 and is_delete=0 " - + " ) THEN 'Pending' " - + " WHEN ( " - + " SELECT COUNT(DISTINCT room_id) " - + " FROM room_details " - + " WHERE school_id = ? and is_active=1 and is_delete=0 " - + " ) = ( " - + " SELECT COUNT(DISTINCT rd.room_id) " - + " FROM room_details rd " - + " JOIN it_mapping im ON im.room_id = rd.room_id " - + " JOIN electrical_mapping em ON em.room_id = rd.room_id " - + " JOIN furniture_mapping fm ON fm.room_id = rd.room_id " - + " WHERE rd.school_id = ? and rd.is_active=1 and rd.is_delete=0 " - + " and im.is_active=1 and im.is_delete=0 and em.is_active=1 and em.is_delete=0 " - + " and fm.is_active=1 and fm.is_delete=0 " - + " AND (im.room_id IS NOT NULL OR em.room_id IS NOT NULL OR fm.room_id IS NOT NULL) " - + " ) THEN 'Completed' " - + " WHEN ( " - + " SELECT COUNT(DISTINCT rd.room_id) " - + " FROM room_details rd " - + " JOIN it_mapping im ON im.room_id = rd.room_id " - + " JOIN electrical_mapping em ON em.room_id = rd.room_id " - + " JOIN furniture_mapping fm ON fm.room_id = rd.room_id " - + " WHERE rd.school_id = ? and rd.is_active=1 and rd.is_delete=0 " - + " and im.is_active=1 and im.is_delete=0 and em.is_active=1 and em.is_delete=0 " - + " and fm.is_active=1 and fm.is_delete=0 " - + " AND (im.room_id IS NOT NULL OR em.room_id IS NOT NULL OR fm.room_id IS NOT NULL) " - + " ) > 0 THEN 'Partially Completed' " - + " ELSE 'Pending' " - + "END AS school_assets "; - try { - return jdbcTemplate.queryForMap(sql, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch); - - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - private Map getSchoolReport(String sch) { - String sql = "SELECT id as school_id, zone, division, udise FROM school_list WHERE id = ?"; - try { - return jdbcTemplate.queryForMap(sql, sch); - - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - private List getschoolId(String udise, String zone, String ward) { - String sql = ""; - if (zone != null && !zone.isEmpty() && ward != null && !ward.isEmpty()) { - //System.out.println("check1"); - sql = "SELECT id FROM school_list WHERE udise In(" + udise + ") and zone = ? and division = ?"; - } else if (zone != null && !zone.isEmpty() && (ward == null || ward.isEmpty())) { - sql = "SELECT id FROM school_list WHERE udise In(" + udise + ") and zone = ?"; - } else if ((zone == null || zone.isEmpty()) && (ward == null || ward.isEmpty())) { - sql = "SELECT id FROM school_list WHERE udise In(" + udise + ")"; - } - try { - if (sql.contains("zone = ?") && sql.contains("division = ?")) { - return jdbcTemplate.queryForList(sql, String.class, zone, ward); - } else if (sql.contains("zone = ?")) { - return jdbcTemplate.queryForList(sql, String.class, zone); - } else { - return jdbcTemplate.queryForList(sql, String.class); - } - - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public ResponseEntity getAEOStudentData(List udise) { - Map response = new HashMap<>(); - - List> data = new ArrayList>(); - if(udise.isEmpty()) { - udise = getUDISE(); - System.out.println("udise="+udise); - } - for(String udises:udise) { - List> school = getschoolsId(udises); - - if(!school.isEmpty() && school!=null) { - for(Map sch:school) { - Map result = new HashMap<>(); - int id = (Integer)sch.get("id"); - Map report = getTotalStudents(id); - result.putAll(report); - - String num = (String) sch.get("udise"); - - String sch_name=(String)sch.get("school_name"); - String hm_name=(String)sch.get("hm_name"); - String hm_mob_num=(String)sch.get("hm_phone_number"); - String zone=(String)sch.get("zone"); - String division=(String)sch.get("division"); - - - Map report1 = getStudentsReg(num); - result.putAll(report1); - long totalStud = (long) report.get("total_students"); - long regStud = (long) report1.get("students_registered"); - long pending = totalStud - regStud; - result.put("pending", pending); - - result.put("udise", num); - - result.put("school_name",sch_name ); - result.put("hm_name",hm_name ); - result.put("hm_mobile", hm_mob_num); - result.put("zone", zone); - result.put("division",division ); - - - Map report2 = getAEO(num); - result.putAll(report2); - - data.add(result); - } - response.put("Message", "Success"); - response.put("data", data); - System.out.println("data="+data); - } else { - response.put("Message", "No Data"); - response.put("data", "No Data Found"); - } - - } - return ResponseEntity.ok(response); - } - - private Map getStudentsReg(String udises) { - String sql = "SELECT count(*) as students_registered FROM student_info WHERE udise = ? AND is_active = 1 AND is_delete = 0"; - try { - return jdbcTemplate.queryForMap(sql, udises); - - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - private Map getTotalStudents(int sch) { - String sql = "SELECT COALESCE((SELECT total_students FROM student_strength WHERE school_id = ?), 0) AS total_students"; - try { - return jdbcTemplate.queryForMap(sql, sch); - - } catch (Exception e) { - e.printStackTrace(); - return Map.of(); - } - } - - - - private List> getschoolsId(String udises) { - String sql = "SELECT id, udise,school_name,hm_name,hm_phone_number,zone,division FROM school_list WHERE udise In(" + udises + ")"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - //////////////////////////////////////////////// - - - @Transactional - public ResponseEntity getAEOStudentsCount() { - Map response = new HashMap<>(); - List> data = new ArrayList>(); - - List> aeos = getAeoDetails(); - - for(Map aeo : aeos) { - - Map result = new HashMap<>(); - - String aoeNum = (String) aeo.get("aeo_num"); - result.put("aoe", aoeNum); - - String udises = (String) aeo.get("udise"); - - List schoolId = getSchoolId(udises); - int school_count = schoolId.size(); - result.put("school_count", school_count); - - int total_stud = getTotalStudentsCount(schoolId); - result.put("total_students", total_stud); - - int students_registered = getRegisteredStudents(udises); - result.put("student_registered", students_registered); - - int pending = total_stud - students_registered; - result.put("pending", pending); - - data.add(result); - } - response.put("Message", "Success"); - response.put("data", data); - return ResponseEntity.ok(response); - } - - - private int getRegisteredStudents(String udises) { - - String[] udiseArray = udises.split(","); - - String placeholders = String.join(",", Collections.nCopies(udiseArray.length, "?")); - - String sql = "SELECT COUNT(student_id) FROM student_info WHERE udise IN (" + placeholders - + ") AND is_active = 1 AND is_delete = 0"; - - try { - - Integer count = jdbcTemplate.queryForObject(sql, Integer.class, (Object[]) udiseArray); - return count != null ? count : 0; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - } - - - - private int getTotalStudentsCount(List schoolId) { - String sql = "SELECT SUM(total_students) FROM student_strength WHERE school_id IN (:schoolId)"; - try { - MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("schoolId", schoolId); - - Integer total = namedParameterJdbcTemplate.queryForObject(sql, parameters, Integer.class); - return total != null ? total : 0; - } catch (DataAccessException e) { - e.printStackTrace(); - return 0; - } - } - - - private List getSchoolId(String udises) { - String sql = "SELECT id FROM school_list WHERE FIND_IN_SET(udise, :udises) > 0"; - try { - MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("udises", udises); - return namedParameterJdbcTemplate.queryForList(sql, parameters, Integer.class); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - private List> getAeoDetails() { - String sql = "SELECT aeo_num, udise FROM aeo_details"; - try { - return jdbcTemplate.queryForList(sql); - } catch (DataAccessException e) { - e.printStackTrace(); - return List.of(); - } - } - - @Transactional - public ResponseEntity getRegisteredStud(String udise) { - Map result = new HashMap<>(); - String sql = "SELECT * " - + " FROM student_info " - + " WHERE udise = ? " - + " AND is_active = 1 " - + " AND is_delete = 0 " - + " ORDER BY " - + " CASE " - + " WHEN std = 'PreKG' THEN 1 " - + " WHEN std = 'LKG' THEN 2 " - + " WHEN std = 'UKG' THEN 3 " - + " WHEN std LIKE 'Class1' THEN 4 " - + " WHEN std LIKE 'Class2' THEN 5 " - + " WHEN std LIKE 'Class3' THEN 6 " - + " WHEN std LIKE 'Class4' THEN 7 " - + " WHEN std LIKE 'Class5' THEN 8 " - + " WHEN std LIKE 'Class6' THEN 9 " - + " WHEN std LIKE 'Class7' THEN 10 " - + " WHEN std LIKE 'Class8' THEN 11 " - + " WHEN std LIKE 'Class9' THEN 12\r\n" - + " WHEN std LIKE 'Class10' THEN 13\r\n" - + " WHEN std LIKE 'Class11' THEN 14\r\n" - + " WHEN std LIKE 'Class12' THEN 15\r\n" - + " ELSE 100 \r\n" - + " END "; - - try { - List> data = jdbcTemplate.queryForList(sql, udise); - result.put("Message", "Success"); - result.put("Data", data); - return ResponseEntity.ok(result); - } catch (Exception e) { - e.printStackTrace(); - result.put("Message", "Error"); - result.put("Error", "Failed to fetch AEO List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/StudentInfoService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/StudentInfoService.java deleted file mode 100644 index 745762cb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/StudentInfoService.java +++ /dev/null @@ -1,857 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.school.Service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; -import javax.transaction.Transactional; - -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.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -@Service -public class StudentInfoService { - private JdbcTemplate jdbcTemplate; - - private String fileBaseUrl; - - @Autowired - public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.fileBaseUrl=environment.getProperty("fileBaseUrl"); - } - - @Autowired - private Environment environment; - - @Transactional - public ResponseEntity getStandards(String udise) { - Map result = new HashMap<>(); - String standard = getStandardsCount(udise); - List standards = Arrays.asList(standard.split(",")); - List> updateSTD = new ArrayList<>(); - for (String std:standards) { - Map data = new HashMap<>(); - String clas = std; - String count = getStudentCount(udise, clas); - data.put("Designation", clas); - data.put("Student_Count", count); - updateSTD.add(data); - } - if(!updateSTD.isEmpty()) { - result.put("Message", "Success"); - result.put("Data", updateSTD); - return ResponseEntity.ok(result); - } else { - result.put("Message", "Error"); - result.put("Error", "Failed to fetch class List"); - return ResponseEntity.ok(result); - } - - } - - @Transactional - public ResponseEntity getSections() { - Map result = new HashMap<>(); - String sql = "SELECT id,section FROM class_sections_master WHERE is_active=1 AND is_delete=0 ORDER BY id"; - try { - List> data = jdbcTemplate.queryForList(sql); - result.put("Message", "Success"); - result.put("Data", data); - return ResponseEntity.ok(result); - } catch (Exception e) { - e.printStackTrace(); - result.put("Message", "Error"); - result.put("Error", "Failed to fetch medium List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - - @Transactional - private String getStudentCount(String udise, String clas) { - String sql = "SELECT count(student_id) FROM student_info where udise = ? AND std = ? AND is_active = 1 AND is_delete = 0 "; - try { - String data = jdbcTemplate.queryForObject(sql, new Object[]{udise, clas}, String.class); - return data; - }catch (Exception e) { - e.printStackTrace(); - return ""; - } - } - @Transactional - public String getStandardsCount(String udise) { - - String sql = "SELECT CONCAT_WS(',', " - + " IF(prekg = 1, 'PreKg', NULL), " - + " IF(lkg = 1, 'LKG', NULL), " - + " IF(ukg = 1, 'UKG', NULL), " - + " IF(class1 = 1, 'Class1', NULL), " - + " IF(class2 = 1, 'Class2', NULL), " - + " IF(class3 = 1, 'Class3', NULL), " - + " IF(class4 = 1, 'Class4', NULL), " - + " IF(class5 = 1, 'Class5', NULL), " - + " IF(class6 = 1, 'Class6', NULL), " - + " IF(class7 = 1, 'Class7', NULL), " - + " IF(class8 = 1, 'Class8', NULL), " - + " IF(class9 = 1, 'Class9', NULL), " - + " IF(class10 = 1, 'Class10', NULL), " - + " IF(class11 = 1, 'Class11', NULL), " - + " IF(class12 = 1, 'Class12', NULL) " - + " ) AS active_classes " - + " FROM school_class_master " - + " WHERE udise = ? "; - - try { - String data = jdbcTemplate.queryForObject(sql, String.class, udise); - return data; - } catch (Exception e) { - e.printStackTrace(); - - //return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - return null; - } - - } - -// @Transactional -// public ResponseEntity getStandards(String udise) { -// Map result = new HashMap<>(); -// String sql = "SELECT Designation, Student_Count FROM ( " -// + "SELECT 'PreKG' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'PreKG' " -// + " WHERE sem.UDISE = ? " -// + " AND (PreKg_Boys > 0 OR PreKg_Girls > 0 OR PreKg_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'LKG' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'LKG' " -// + " WHERE sem.UDISE = ? " -// + " AND (LKG_Boys > 0 OR LKG_Girls > 0 OR LKG_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'UKG' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'UKG' " -// + " WHERE sem.UDISE = ? " -// + " AND (UKG_Boys > 0 OR UKG_Girls > 0 OR UKG_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class1' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class1' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class1_Boys > 0 OR Class1_Girls > 0 OR Class1_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class2' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class2' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class2_Boys > 0 OR Class2_Girls > 0 OR Class2_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class3' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class3' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class3_Boys > 0 OR Class3_Girls > 0 OR Class3_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class4' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class4' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class4_Boys > 0 OR Class4_Girls > 0 OR Class4_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class5' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class5' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class5_Boys > 0 OR Class5_Girls > 0 OR Class5_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class6' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class6' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class6_Boys > 0 OR Class6_Girls > 0 OR Class6_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class7' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class7' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class7_Boys > 0 OR Class7_Girls > 0 OR Class7_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class8' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class8' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class8_Boys > 0 OR Class8_Girls > 0 OR Class8_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class9' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class9' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class9_Boys > 0 OR Class9_Girls > 0 OR Class9_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class10' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class10' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class10_Boys > 0 OR Class10_Girls > 0 OR Class10_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class11' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class11' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class11_Boys > 0 OR Class11_Girls > 0 OR Class11_Transgen > 0) AND si.is_active = 1 AND si.is_delete = 0 " -// + " UNION ALL " -// + " SELECT 'Class12' AS Designation, " -// + " COUNT(si.student_id) AS Student_Count " -// + " FROM student_enrollment_master sem " -// + " LEFT JOIN student_info si " -// + " ON sem.UDISE = si.udise AND si.std = 'Class12' " -// + " WHERE sem.UDISE = ? " -// + " AND (Class12_Boys > 0 OR Class12_Girls > 0 OR Class12_Transgen > 0)AND si.is_active = 1 AND si.is_delete = 0 " -// + " ) AS result WHERE Student_Count > 0"; -// -// try { -// List> data = jdbcTemplate.queryForList(sql, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise); -// result.put("Message", "Success"); -// result.put("Data", data); -// return ResponseEntity.ok(result); -// } catch (Exception e) { -// e.printStackTrace(); -// result.put("Message", "Error"); -// result.put("Error", "Failed to fetch class List: " + e.getMessage()); -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); -// } -// -// } - -// @Transactional -// public ResponseEntity getStandards(String udise) { -// Map result = new HashMap<>(); -// String sql = "SELECT 'PreKG' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (PreKg_Boys > 0 OR PreKg_Girls > 0 OR PreKg_Transgen > 0) " -// + " UNION " -// + " SELECT 'LKG' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (LKG_Boys > 0 OR LKG_Girls > 0 OR LKG_Transgen > 0) " -// + " UNION " -// + " SELECT 'UKG' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (UKG_Boys > 0 OR UKG_Girls > 0 OR UKG_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class1' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class1_Boys > 0 OR Class1_Girls > 0 OR Class1_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class2' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class2_Boys > 0 OR Class2_Girls > 0 OR Class2_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class3' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class3_Boys > 0 OR Class3_Girls > 0 OR Class3_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class4' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class4_Boys > 0 OR Class4_Girls > 0 OR Class4_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class5' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class5_Boys > 0 OR Class5_Girls > 0 OR Class5_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class6' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class6_Boys > 0 OR Class6_Girls > 0 OR Class6_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class7' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class7_Boys > 0 OR Class7_Girls > 0 OR Class7_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class8' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class8_Boys > 0 OR Class8_Girls > 0 OR Class8_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class9' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class9_Boys > 0 OR Class9_Girls > 0 OR Class9_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class10' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class10_Boys > 0 OR Class10_Girls > 0 OR Class10_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class11' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class11_Boys > 0 OR Class11_Girls > 0 OR Class11_Transgen > 0) " -// + " UNION " -// + " SELECT 'Class12' AS Designation " -// + " FROM student_enrollment_master " -// + " WHERE UDISE = ? " -// + " AND (Class12_Boys > 0 OR Class12_Girls > 0 OR Class12_Transgen > 0)"; -// -// try { -// List> data = jdbcTemplate.queryForList(sql, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise, udise); -// result.put("Message", "Success"); -// result.put("Data", data); -// return ResponseEntity.ok(result); -// } catch (Exception e) { -// e.printStackTrace(); -// result.put("Message", "Error"); -// result.put("Error", "Failed to fetch class List: " + e.getMessage()); -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); -// } -// -// } - @Transactional - public ResponseEntity checkStudent(String udise, String student_name, String emis_no, String gender, String std, - String dob, String age, String parent_type,String section,String medium, String father_name, String mother_name, String guardian_name, - String father_mobile, String mother_mobile, String guardian_mobile, String father_aadhar, - String mother_aadhar, String guardian_aadhar, String student_aadhar, MultipartFile father_aadhar_file, - MultipartFile mother_aadhar_file, MultipartFile guardian_aadhar_file, MultipartFile student_aadhar_file) { - Map result = new HashMap<>(); - int is_avbl = checkEmis(emis_no); - if(is_avbl==0) { - String data = saveStudent(udise, student_name, emis_no, gender, std, dob, age, parent_type,section,medium, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file); - if (data.equalsIgnoreCase("sucess")) { - result.put("Message", "Saved Sucessfully"); - result.put("Data", "Success"); - } else { - result.put("Message", "Error"); - result.put("Error", "Failed to save"); - } - - } else if(is_avbl==1){ - result.put("Message", "Duplicate"); - result.put("Error", "EMIS No already registered"); - - }else { - result.put("Message", "Error"); - result.put("Error", "Failed to save"); - } - return ResponseEntity.ok(result); - - } - - private int checkEmis(String emis_no) { - String sql = "SELECT CASE WHEN EXISTS (SELECT 1 FROM student_info WHERE emis_no = ? and is_active=1 and is_delete=0) THEN 1 ELSE 0 END AS result"; - try { - return jdbcTemplate.queryForObject(sql, Integer.class, emis_no); - - } catch (Exception e) { - e.printStackTrace(); - return 5; - } - } - @Transactional - public String saveStudent(String udise, String student_name, String emis_no, String gender, String std, - String dob, String age, String parent_type,String section,String medium, String father_name, String mother_name, String guardian_name, String father_mobile, String mother_mobile, String guardian_mobile, - String father_aadhar, String mother_aadhar, String guardian_aadhar, String student_aadhar, MultipartFile father_aadhar_file, - MultipartFile mother_aadhar_file, MultipartFile guardian_aadhar_file, MultipartFile student_aadhar_file) { - - String sql = "INSERT INTO student_info (udise, student_name, emis_no, gender, std, dob, age, parent_type,section,mediums, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file) VALUES (?, ?, ?, ?, ?, ?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; - try { - String fatherUrl = null; - String motherUrl = null; - String guardianUrl = null; - String studentUrl = null; - - if(student_aadhar.isEmpty()) { - student_aadhar=null; - } - - String sec=section.toUpperCase(); - - if(father_aadhar_file!=null && !father_aadhar_file.isEmpty()) { - fatherUrl = saveFile(father_aadhar_file); - } - if(mother_aadhar_file!=null && !mother_aadhar_file.isEmpty()) { - motherUrl = saveFile(mother_aadhar_file); - } - if(guardian_aadhar_file!=null && !guardian_aadhar_file.isEmpty()) { - guardianUrl = saveFile(guardian_aadhar_file); - } - if(student_aadhar_file!=null && !student_aadhar_file.isEmpty()) { - studentUrl = saveFile(student_aadhar_file); - } - - - -// System.out.println("----- Student Info -----"); -// System.out.println("UDISE: " + udise); -// System.out.println("Student Name: " + student_name); -// System.out.println("EMIS No: " + emis_no); -// System.out.println("Gender: " + gender); -// System.out.println("Class: " + std); -// System.out.println("DOB: " + dob); -// System.out.println("Age: " + age); -// System.out.println("Parent Type: " + parent_type); -// -// System.out.println("----- Parent Details -----"); -// System.out.println("Father Name: " + father_name); -// System.out.println("Mother Name: " + mother_name); -// System.out.println("Guardian Name: " + guardian_name); -// -// System.out.println("Father Mobile: " + father_mobile); -// System.out.println("Mother Mobile: " + mother_mobile); -// System.out.println("Guardian Mobile: " + guardian_mobile); -// -// System.out.println("Father Aadhar: " + father_aadhar); -// System.out.println("Mother Aadhar: " + mother_aadhar); -// System.out.println("Guardian Aadhar: " + guardian_aadhar); -// System.out.println("Student Aadhar: " + student_aadhar); -// -// System.out.println("----- Uploaded Files -----"); -// System.out.println("Father Aadhar File: " + (father_aadhar_file != null ? father_aadhar_file.getOriginalFilename() : "null")); -// System.out.println("Mother Aadhar File: " + (mother_aadhar_file != null ? mother_aadhar_file.getOriginalFilename() : "null")); -// System.out.println("Guardian Aadhar File: " + (guardian_aadhar_file != null ? guardian_aadhar_file.getOriginalFilename() : "null")); -// System.out.println("Student Aadhar File: " + (student_aadhar_file != null ? student_aadhar_file.getOriginalFilename() : "null")); - - - jdbcTemplate.update(sql, udise, student_name, emis_no, gender, std, dob, age, parent_type,sec,medium, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, fatherUrl, motherUrl, guardianUrl, studentUrl); - return "sucess"; - } catch (IOException e) { - e.printStackTrace(); - return "error"; - } - - } - -// private String saveFile(MultipartFile file) throws IOException { -// -// String uploadDirectory = environment.getProperty("file.upload.directory"); -// -// String folderName = environment.getProperty("education.foldername"); -// -// String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + "_" + file.getOriginalFilename(); -// -// String folderPath = uploadDirectory + "/" + folderName; -// -// Path dirPath = Paths.get(folderPath); -// if (!Files.exists(dirPath)) { -// Files.createDirectories(dirPath); -// } -// -// Path filePath = dirPath.resolve(fileName); -// -// Files.write(filePath, file.getBytes()); -// -// return filePath.toAbsolutePath().toString(); -// } - - private String saveFile(MultipartFile file) throws IOException { - String uploadDirectory = environment.getProperty("file.upload.directory"); - String folderName = environment.getProperty("education.foldername"); - - String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + "_" + file.getOriginalFilename(); - - String FilePath = "/"+ folderName +"/"+fileName; - // Create the directory path - Path dirPath = Paths.get(uploadDirectory, folderName); - if (!Files.exists(dirPath)) { - Files.createDirectories(dirPath); - } - - // Create the full file path - Path filePath = dirPath.resolve(fileName); - - // Save the file - Files.write(filePath, file.getBytes()); - - return FilePath; - - // Return the full file path as a string - //return filePath.toString().replace("\\", "/"); - } - - - @Transactional - public ResponseEntity getStudentsClass(String udise, String std) { - Map result = new HashMap<>(); - String sql = "SELECT student_id, student_name, emis_no FROM student_info WHERE udise = ? AND std = ? AND is_active=1 AND is_delete=0"; - try { - List> data = jdbcTemplate.queryForList(sql, udise, std); - result.put("Message", "Success"); - result.put("Data", data); - return ResponseEntity.ok(result); - } catch (Exception e) { - e.printStackTrace(); - result.put("Message", "Error"); - result.put("Error", "Failed to fetch students in class List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - - } - - @Transactional - public ResponseEntity getStudentsDetails(String studentId) { - Map result = new HashMap<>(); - String sql = "SELECT *, " + - "CONCAT('" + fileBaseUrl + "/gcc/files', father_aadhar_file) AS view_father_aadhar_file, " + - "CONCAT('" + fileBaseUrl + "/gcc/files', mother_aadhar_file) AS view_mother_aadhar_file, " + - "CONCAT('" + fileBaseUrl + "/gcc/files', guardian_aadhar_file) AS view_guardian_aadhar_file, " + - "CONCAT('" + fileBaseUrl + "/gcc/files', student_aadhar_file) AS view_student_aadhar_file " + - " FROM student_info WHERE student_id = ?"; - try { - List> data = jdbcTemplate.queryForList(sql, studentId); - result.put("Message", "Success"); - result.put("Data", data); - return ResponseEntity.ok(result); - } catch (Exception e) { - e.printStackTrace(); - result.put("Message", "Error"); - result.put("Error", "Failed to fetch student detail: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - - @Transactional - public ResponseEntity getMedium() { - Map result = new HashMap<>(); - String sql = "SELECT * FROM medium_master ORDER BY execution_order ASC"; - try { - List> data = jdbcTemplate.queryForList(sql); - result.put("Message", "Success"); - result.put("Data", data); - return ResponseEntity.ok(result); - } catch (Exception e) { - e.printStackTrace(); - result.put("Message", "Error"); - result.put("Error", "Failed to fetch medium List: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result); - } - } - - private String logEntry(String student_id, String user_id, String action_type) { - String sql="INSERT INTO student_info_log (student_id, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file, user_id, action_type) " - + " SELECT student_id, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file, ?, ? FROM student_info WHERE student_id = ?"; - - try { - jdbcTemplate.update(sql, user_id, action_type, student_id); - return "sucess"; - - } catch (DataAccessException e) { - e.printStackTrace(); - return "failure"; - - } - - } - - @Transactional - public ResponseEntity deleteProcess(String student_id, String user_id, String action_type) { - Map result = new HashMap<>(); - - String data = logEntry(student_id, user_id, action_type); - String data1 = ""; - if(data.equalsIgnoreCase("sucess")) { - data1 = deleteStudent(student_id); - } else { - result.put("Message", "Error"); - result.put("Data", "Failed"); - return ResponseEntity.ok(result); - } - if(data1.equalsIgnoreCase("sucess")) { - result.put("Message", "Success"); - result.put("Data", "Deleted sucessfully"); - }else { - result.put("Message", "Error"); - result.put("Data", "Failed to Delete"); - } - return ResponseEntity.ok(result); - } - - private String deleteStudent(String student_id) { - String sql="UPDATE student_info SET is_delete = 1, is_active = 0 WHERE student_id = ? "; - - - try { - jdbcTemplate.update(sql, student_id); - return "sucess"; - } catch (DataAccessException e) { - e.printStackTrace(); - return "failure"; - } - } - - - @Transactional - public ResponseEntity updateProcess(String student_id, String user_id, String action_type, String udise, - String student_name, String emis_no, String gender, String mediums, String std, String section, String dob, - String age, String parent_type, String father_name, String mother_name, String guardian_name, - String father_mobile, String mother_mobile, String guardian_mobile, String father_aadhar, - String mother_aadhar, String guardian_aadhar, String student_aadhar, MultipartFile father_aadhar_file, - MultipartFile mother_aadhar_file, MultipartFile guardian_aadhar_file, MultipartFile student_aadhar_file, String raw_father_aadhar, String raw_mother_aadhar, String raw_guardian_aadhar, String raw_student_aadhar) { - Map result = new HashMap<>(); - - String data = logEntry(student_id, user_id, action_type); - String data1 = ""; - if(data.equalsIgnoreCase("sucess")) { - data1 = updateStudent(student_id, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, father_aadhar_file, mother_aadhar_file, guardian_aadhar_file, student_aadhar_file, raw_father_aadhar, raw_mother_aadhar, raw_guardian_aadhar, raw_student_aadhar); - } - else { - result.put("Message", "Error"); - result.put("Data", "Failed"); - return ResponseEntity.ok(result); - } - - if(data1.equalsIgnoreCase("sucess")) { - result.put("Message", "Success"); - result.put("Data", "Updated successfully"); - }else { - result.put("Message", "Error"); - result.put("Data", "Failed to update"); - } - - return ResponseEntity.ok(result); - } - - private String updateStudent(String student_id, String udise, String student_name, String emis_no, String gender, - String mediums, String std, String section, String dob, String age, String parent_type, String father_name, - String mother_name, String guardian_name, String father_mobile, String mother_mobile, - String guardian_mobile, String father_aadhar, String mother_aadhar, String guardian_aadhar, - String student_aadhar, MultipartFile father_aadhar_file, MultipartFile mother_aadhar_file, - MultipartFile guardian_aadhar_file, MultipartFile student_aadhar_file, String raw_father_aadhar, String raw_mother_aadhar, String raw_guardian_aadhar, String raw_student_aadhar) { - - String sql = ""; - - String fatherUrl = null; - String motherUrl = null; - String guardianUrl = null; - String studentUrl = null; - - - try { - - //// for parent - if("Parent".equalsIgnoreCase(parent_type)) { - - if(raw_father_aadhar!=null && !raw_father_aadhar.isEmpty() ) { - fatherUrl = raw_father_aadhar; - if(father_aadhar_file!=null && !father_aadhar_file.isEmpty()) { - fatherUrl = saveFile(father_aadhar_file); - } - - } - else { - if(father_aadhar_file!=null && !father_aadhar_file.isEmpty()) { - fatherUrl = saveFile(father_aadhar_file); - } - else { - fatherUrl = null; - } - - } - - if(raw_mother_aadhar!=null && !raw_mother_aadhar.isEmpty() ) { - - motherUrl = raw_mother_aadhar; - if(mother_aadhar_file!=null && !mother_aadhar_file.isEmpty()) { - - motherUrl = saveFile(mother_aadhar_file); - } - - } - else { - - if(mother_aadhar_file!=null && !mother_aadhar_file.isEmpty()) { - motherUrl = saveFile(mother_aadhar_file); - } - else { - motherUrl =null; - } - - } - - } - - else { - if (father_aadhar_file != null && !father_aadhar_file.isEmpty()) { - fatherUrl = saveFile(father_aadhar_file); - } else { - //fatherUrl = (raw_father_aadhar != null) ? raw_father_aadhar : null; - fatherUrl = (raw_father_aadhar != null && !raw_father_aadhar.isEmpty()) ? raw_father_aadhar : null; - } - - if (mother_aadhar_file != null && !mother_aadhar_file.isEmpty()) { - motherUrl = saveFile(mother_aadhar_file); - } else { - //motherUrl = (raw_mother_aadhar != null) ? raw_mother_aadhar : null; - motherUrl = (raw_mother_aadhar != null && !raw_mother_aadhar.isEmpty()) ? raw_mother_aadhar : null; - } - } - - - - //// - guardianUrl = raw_guardian_aadhar; - if(guardian_aadhar_file!=null && !guardian_aadhar_file.isEmpty()) { - guardianUrl = saveFile(guardian_aadhar_file); - } - - /// - studentUrl = raw_student_aadhar; - if(student_aadhar_file!=null && !student_aadhar_file.isEmpty()) { - studentUrl = saveFile(student_aadhar_file); - } - - //father_mobile mother_mobile - if (father_mobile != null && father_mobile.trim().isEmpty()) { - father_mobile = null; - } - if (mother_mobile != null && mother_mobile.trim().isEmpty()) { - mother_mobile = null; - } - - // father_aadhar mother_aadhar student_aadhar - if (father_aadhar != null && father_aadhar.trim().isEmpty()) { - father_aadhar = null; - } - if (mother_aadhar != null && mother_aadhar.trim().isEmpty()) { - mother_aadhar = null; - } - - if (student_aadhar != null && student_aadhar.trim().isEmpty()) { - student_aadhar = null; - } - - //////// - if(parent_type.equalsIgnoreCase("Parent")) { - sql="UPDATE student_info SET udise = ?, student_name = ?, emis_no = ?, gender = ?, mediums = ?, std = ?, section = ?, dob = ?, age = ?, parent_type = ?, father_name = ?, mother_name = ?, father_mobile = ?, mother_mobile = ?, father_aadhar = ?, mother_aadhar = ?, student_aadhar = ?, father_aadhar_file = ?, mother_aadhar_file = ?, student_aadhar_file = ? WHERE student_id = ? "; - jdbcTemplate.update(sql, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, mother_name, father_mobile, mother_mobile, father_aadhar, mother_aadhar, student_aadhar, fatherUrl, motherUrl, studentUrl, student_id); - } else if(parent_type.equalsIgnoreCase("SingleParent_Father")) { - sql="UPDATE student_info SET udise = ?, student_name = ?, emis_no = ?, gender = ?, mediums = ?, std = ?, section = ?, dob = ?, age = ?, parent_type = ?, father_name = ?, father_mobile = ?, father_aadhar = ?, student_aadhar = ?, father_aadhar_file = ?, student_aadhar_file = ? WHERE student_id = ? "; - jdbcTemplate.update(sql, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, father_mobile, father_aadhar, student_aadhar, fatherUrl, studentUrl, student_id); - } else if(parent_type.equalsIgnoreCase("SingleParent_Mother")) { - sql="UPDATE student_info SET udise = ?, student_name = ?, emis_no = ?, gender = ?, mediums = ?, std = ?, section = ?, dob = ?, age = ?, parent_type = ?, mother_name = ?, mother_mobile = ?, mother_aadhar = ?, student_aadhar = ?, mother_aadhar_file = ?, student_aadhar_file = ? WHERE student_id = ? "; - jdbcTemplate.update(sql, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, mother_name, mother_mobile, mother_aadhar, student_aadhar, motherUrl, studentUrl, student_id); - } else if(parent_type.equalsIgnoreCase("Guardian")) { - sql="UPDATE student_info SET udise = ?, student_name = ?, emis_no = ?, gender = ?, mediums = ?, std = ?, section = ?, dob = ?, age = ?, parent_type = ?, father_name = ?, mother_name = ?, guardian_name = ?, father_mobile = ?, mother_mobile = ?, guardian_mobile = ?, father_aadhar = ?, mother_aadhar = ?, guardian_aadhar = ?, student_aadhar = ?, father_aadhar_file = ?, mother_aadhar_file = ?, guardian_aadhar_file = ?, student_aadhar_file = ? WHERE student_id = ? "; - jdbcTemplate.update(sql, udise, student_name, emis_no, gender, mediums, std, section, dob, age, parent_type, father_name, mother_name, guardian_name, father_mobile, mother_mobile, guardian_mobile, father_aadhar, mother_aadhar, guardian_aadhar, student_aadhar, fatherUrl, motherUrl, guardianUrl, studentUrl, student_id); - } - return "sucess"; - }catch (Exception e) { - e.printStackTrace(); - return "failure"; - } - } - - @Transactional - public ResponseEntity checkStudent(String udise, String schoolId) { - Map result = new HashMap<>(); - try { - String stu_strength = studentStrength(schoolId); - String aadhar_strength = aadharStrength(udise); - - if (!stu_strength.equalsIgnoreCase("error") && !aadhar_strength.equalsIgnoreCase("error")) { - int allowable_strength = Integer.parseInt(stu_strength) - Integer.parseInt(aadhar_strength); - result.put("Student_Strength", Integer.parseInt(stu_strength)); - result.put("Aadhar_strength", Integer.parseInt(aadhar_strength)); - result.put("Allowable_strength", allowable_strength); - result.put("Message", "Sucessfully student count fetched"); - result.put("Status", "Sucess"); - } else if (stu_strength.equalsIgnoreCase("error") || aadhar_strength.equalsIgnoreCase("error")) { - result.put("Status", "Error"); - result.put("Message", "Error in fetching students count"); - } - } catch (Exception e) { - e.printStackTrace(); - result.put("Status", "Error"); - result.put("Message", "Error in fetching students count"); - } - return ResponseEntity.ok(result); - } - - - private String aadharStrength(String udise) { - String sql = "SELECT count(*) FROM student_info WHERE udise = ? AND is_active = 1 AND is_delete = 0"; - String strength = "0"; - - try { - String result = jdbcTemplate.queryForObject(sql, String.class, udise); - if (result != null && !result.isEmpty()) { - strength = result; - } - } - catch (Exception e) { - System.out.println("Error fetching student strength: " + e.getMessage()); - strength = "error"; - } - - return strength; - } - private String studentStrength(String schoolId) { - String sql = "SELECT total_students FROM student_strength WHERE school_id = ?"; - String strength = "0"; - - try { - String result = jdbcTemplate.queryForObject(sql, String.class, schoolId); - if (result != null && !result.isEmpty()) { - strength = result; - } - } - catch (Exception e) { - System.out.println("Error fetching student strength: " + e.getMessage()); - strength = "error"; - } - - return strength; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/Base64Util.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/Base64Util.java deleted file mode 100644 index dab293a6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/Base64Util.java +++ /dev/null @@ -1,39 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import java.util.Base64; -import java.util.List; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class Base64Util { - - // Encode to Base64 - public static String encodeBase64(String value) { - if (value != null && !value.isEmpty()) { - byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes()); - // Print the original value and its encoded version - // System.out.println(value + " : " + new String(encodedBytes)); - return new String(encodedBytes); - } else { - return ""; - } - } - - // Decode from Base64 - public static String decodeBase64(String encodedValue) { - if (encodedValue != null && !encodedValue.isEmpty()) { - try { - byte[] decodedBytes = Base64.getDecoder().decode(encodedValue); - return new String(decodedBytes); - } catch (IllegalArgumentException e) { - // Handle the exception, e.g., log it or return an error message - System.err.println("Error decoding Base64 string: " + e.getMessage()); - return "error"; // Or return an error message string - } - } else { - return ""; - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/CustomUserDetails.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/CustomUserDetails.java deleted file mode 100644 index db569ec8..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/CustomUserDetails.java +++ /dev/null @@ -1,80 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; - -public class CustomUserDetails implements UserDetails, Serializable { - - private static final long serialVersionUID = 1L; - - private String username; - private String password; - private Collection authorities; - private boolean accountNonExpired; - private boolean accountNonLocked; - private boolean credentialsNonExpired; - private boolean enabled; - private Map additionalAttributes; - - public CustomUserDetails(String username, String password, - Collection authorities, - boolean accountNonExpired, - boolean accountNonLocked, - boolean credentialsNonExpired, - boolean enabled, - Map additionalAttributes) { - this.username = username; - this.password = password; - this.authorities = authorities; - this.accountNonExpired = accountNonExpired; - this.accountNonLocked = accountNonLocked; - this.credentialsNonExpired = credentialsNonExpired; - this.enabled = enabled; - this.additionalAttributes = additionalAttributes; - } - - @Override - public Collection getAuthorities() { - return authorities; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public String getUsername() { - return username; - } - - @Override - public boolean isAccountNonExpired() { - return accountNonExpired; - } - - @Override - public boolean isAccountNonLocked() { - return accountNonLocked; - } - - @Override - public boolean isCredentialsNonExpired() { - return credentialsNonExpired; - } - - @Override - public boolean isEnabled() { - return enabled; - } - - // Getter for additional attributes - public Map getAdditionalAttributes() { - return additionalAttributes; - } -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/CustomUserDetailsService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/CustomUserDetailsService.java deleted file mode 100644 index 15cfe7ce..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/CustomUserDetailsService.java +++ /dev/null @@ -1,87 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.stereotype.Service; - -import in.gov.chennaicorporation.gccoffice.entity.AppUserEntity; -import in.gov.chennaicorporation.gccoffice.repository.AppUserRepository; - -@Service -public class CustomUserDetailsService implements UserDetailsService { - - private final AppUserRepository appUserRepository; - private final UserActivityService userActivityService; - - @Autowired - public CustomUserDetailsService(AppUserRepository appUserRepository,UserActivityService userActivityService ) { - this.appUserRepository = appUserRepository; - this.userActivityService = userActivityService; - } - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - AppUserEntity appUserEntity = appUserRepository.findByUsername(username); - - userActivityService.logUserActivity("0", "Trying to Login with Username: " + username); - //System.out.println(username); - if (appUserEntity == null) { - //System.out.println("User not found"); - userActivityService.logUserActivity("0","User (" + username +") not found"); - throw new UsernameNotFoundException("User not found"); - } - - /* - return org.springframework.security.core.userdetails.User.builder() - .username(appUserEntity.getUsername()) - .password(appUserEntity.getPassword()) - .roles(appUserEntity.getRoles()) - .additionalAttributes(Map.of("userid", appUserEntity.getUserid())) - .build(); - */ - - String userRole = appUserEntity.getRoles(); - // Ensure that the role starts with "ROLE_" - if (!userRole.startsWith("ROLE_")) { - userRole = "ROLE_" + userRole; - //System.out.println("User Role: "+userRole); - } - - // Create a SimpleGrantedAuthority for the user role - SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole); - - // Create a list to hold the authority/role - List authorityList = new ArrayList<>(); - authorityList.add(authority); - - // Construct CustomUserDetails instance with custom attributes - CustomUserDetails userDetails = new CustomUserDetails( - appUserEntity.getUsername(), - appUserEntity.getPassword(), - authorityList, - true, - true, - true, - true, - Map.of("userid",appUserEntity.getUserid().getUserid(), - "usergroupid",appUserEntity.getUsergroup_id().getId(), - "userrole",appUserEntity.getRoles().toString() - ) - ); - - userActivityService.logUserActivity(appUserEntity.getUserid().getUserid().toString(), "Login Success:
    Username: "+appUserEntity.getUsername() - +"
    Role: "+appUserEntity.getRoles().toString() - +"
    Access Group: "+appUserEntity.getUsergroup_id().getName() - +"
    Access Group ID: "+appUserEntity.getUsergroup_id().getId()); - - return userDetails; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java deleted file mode 100644 index c7f79e42..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java +++ /dev/null @@ -1,83 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - - -@Service -public class GetMappingUserDetails { - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getMappingList(String loginId) { - try { - String sqlQuery = "SELECT * FROM `login_mapping_user` WHERE appuser_id=? LIMIT 1"; - //System.out.println(sqlQuery+loginId); - List> result = jdbcTemplate.queryForList(sqlQuery,loginId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public String getOfficerMaster(String loginId) { - System.out.println("SELECT `officer_master_id` FROM `login_mapping_user` WHERE appuser_id = "+loginId+" LIMIT 1"); - try { - String sqlQuery = "SELECT `officer_master_id` FROM `login_mapping_user` WHERE appuser_id = ? LIMIT 1"; - System.out.println(sqlQuery); - System.out.println("SELECT `officer_master_id` FROM `login_mapping_user` WHERE appuser_id = "+loginId+" LIMIT 1"); - List> results = jdbcTemplate.queryForList(sqlQuery, loginId); - - if (results.isEmpty()) { - return null; // No record found - } else { - // Assuming there is only one result because of LIMIT 1 - Map row = results.get(0); - Object officerMasterId = row.get("officer_master_id"); - - return officerMasterId != null ? officerMasterId.toString() : null; - } - } catch (DataAccessException e) { - - e.printStackTrace(); - return null; // Handle error appropriately - } - } - - @Transactional(readOnly = true) - public String getERPUserId(String loginId) { - try { - String sqlQuery = "SELECT `erpuser_id` FROM `login_mapping_user` WHERE appuser_id = ? LIMIT 1"; - List> results = jdbcTemplate.queryForList(sqlQuery, loginId); - - if (results.isEmpty()) { - return null; // No record found - } else { - // Assuming there is only one result because of LIMIT 1 - Map row = results.get(0); - Object erpUserId = row.get("erpuser_id"); - - return erpUserId != null ? erpUserId.toString() : null; - } - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Handle error appropriately - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/LoginUserInfo.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/LoginUserInfo.java deleted file mode 100644 index dc119c07..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/LoginUserInfo.java +++ /dev/null @@ -1,208 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import java.time.LocalDate; -import java.time.temporal.ChronoUnit; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Service; - -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; - -@Service -public class LoginUserInfo { - private JdbcTemplate jdbcAppTemplate; - private JdbcTemplate jdbcKuralTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource sosDataSource, - @Qualifier("mysqlKuralDataSource") DataSource kuralDataSource) { - this.jdbcAppTemplate = new JdbcTemplate(sosDataSource); - this.jdbcKuralTemplate = new JdbcTemplate(kuralDataSource); - } - - public static UserDetails getCurrentUserDetails() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.isAuthenticated()) { - Object principal = authentication.getPrincipal(); - if (principal instanceof UserDetails) { - return (UserDetails) principal; - } - } - return null; - } - - public static String getLoginUserId() { - UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); - - if (userDetails instanceof CustomUserDetails) { - //System.out.println("User Details : "+userDetails.toString()); - CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; - Map additionalAttributes = customUserDetails.getAdditionalAttributes(); - if (additionalAttributes != null) { - Object userId = additionalAttributes.get("userid"); - Object groupId = additionalAttributes.get("groupid"); - if (userId != null) { - return userId.toString(); - } - } - /* - for (Map.Entry entry : additionalAttributes.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - System.out.println("Key: " + key + ", Value: " + value); - }*/ - } - return null; - } - - public static String getUserGroupId() { - UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); - if (userDetails instanceof CustomUserDetails) { - CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; - Map additionalAttributes = customUserDetails.getAdditionalAttributes(); - if (additionalAttributes != null) { - Object userGroupId = additionalAttributes.get("usergroupid"); - if (userGroupId != null) { - return userGroupId.toString(); - } - } - } - return null; - } - - public static String getUserRole() { - UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); - if (userDetails instanceof CustomUserDetails) { - CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; - Map additionalAttributes = customUserDetails.getAdditionalAttributes(); - if (additionalAttributes != null) { - Object userRole = additionalAttributes.get("userrole"); - if (userRole != null) { - return userRole.toString(); - } - } - } - return null; - } - - public String resetPassword(String userid, String oldPassword, String newPassword, String rawPassword) { - BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - - // Query to get the stored encoded password for the given user ID - String fetchPasswordQuery = "SELECT `password` FROM `appusers` WHERE `id` = ?"; - List> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{userid}); - - if (result.isEmpty()) { - // If no matching user is found, return an error message - return "User not found."; - } - - String storedEncodedPassword = (String) result.get(0).get("password"); - - // Verify the old password against the stored encoded password - if (!passwordEncoder.matches(oldPassword, storedEncodedPassword)) { - // If the old password doesn't match, return an error message - return "Old password does not match."; - } - - // Encode the new password using BCrypt - String encodedNewPassword = passwordEncoder.encode(newPassword); - - // Update the password in the database - String updateQuery = "UPDATE `appusers` SET `password` = ?, `pwd_txt` = ? WHERE `id` = ?"; - int rowsAffected = jdbcAppTemplate.update(updateQuery, new Object[]{encodedNewPassword, newPassword, userid}); - - if (rowsAffected > 0) { - // If the update is successful, return a success message - return "success"; - } else { - // If the update fails, return an error message - return "Failed to reset the password. Please try again."; - } - } - - - public List> userCheck(String username, String password) { - - Integer statusCode=404; - String statusTxt="error"; - String msgTxt="User not found."; - - Map response = new HashMap<>(); - - BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - - // Query to get the stored encoded password for the given user ID - String fetchPasswordQuery = "SELECT `id`, `roles`, `usergroup_id`, `isactive`, `dname`, `password` as saltref FROM `appusers` WHERE `username` = ? AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{username}); - - if (result.isEmpty()) { - System.out.println(fetchPasswordQuery); - // If no matching user is found, return an error message - msgTxt = "User not found."; - response.put("Data", Collections.emptyList()); - } - else { - - String storedEncodedPassword = (String) result.get(0).get("saltref"); - - // Verify the password against the stored encoded password - if (!passwordEncoder.matches(password, storedEncodedPassword)) { - msgTxt = "User not found."; - response.put("Data", Collections.emptyList()); - } - else { - statusCode=200; - statusTxt="success"; - msgTxt = "Login Successfully"; - if (result.isEmpty()) { - } else { - response.put("Data", result); - } - } - } - response.put("statusCode", statusCode); - response.put("statusText", statusTxt); - response.put("message", msgTxt); - - return Collections.singletonList(response); - } - - // Dashboard : தினம் ஒரு திருக்குறள் // thirukkural - - public List> getDailyContent() { - // Query to get all content from the table - String contentQuery = "SELECT * FROM kural"; // Replace content_table with your actual table name - List> contentList = jdbcKuralTemplate.queryForList(contentQuery); - - // Total number of records - int totalRecords = contentList.size(); - - if (totalRecords == 0) { - // If there are no records, return an empty list - return Collections.emptyList(); - } - - // Calculate the number of days since a specific start date (e.g., October 21, 2024) - LocalDate startDate = LocalDate.of(2024, 10, 21); - LocalDate currentDate = LocalDate.now(); - long daysSinceStart = ChronoUnit.DAYS.between(startDate, currentDate); - - // Get the content index for today (using modulo to cycle through the records) - int contentIndex = (int) (daysSinceStart % totalRecords); - - // Return the content for today as a list - return Collections.singletonList(contentList.get(contentIndex)); - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/UserActivityService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/UserActivityService.java deleted file mode 100644 index 3f11b1f1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/UserActivityService.java +++ /dev/null @@ -1,29 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import in.gov.chennaicorporation.gccoffice.entity.UserActivityLog; -import in.gov.chennaicorporation.gccoffice.repository.UserActivityLogRepository; - -import java.time.LocalDateTime; - -@Service -public class UserActivityService { - - private final UserActivityLogRepository userActivityLogRepository; - - @Autowired - public UserActivityService(UserActivityLogRepository userActivityLogRepository) { - this.userActivityLogRepository = userActivityLogRepository; - } - - public void logUserActivity(String userId, String activityType) { - UserActivityLog userActivityLog = new UserActivityLog(); - userActivityLog.setUserId(userId); - userActivityLog.setActivityType(activityType); - userActivityLog.setTimestamp(LocalDateTime.now()); - - userActivityLogRepository.save(userActivityLog); - } -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/UserActivityTimelineService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/UserActivityTimelineService.java deleted file mode 100644 index 08d352d2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/UserActivityTimelineService.java +++ /dev/null @@ -1,25 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import in.gov.chennaicorporation.gccoffice.entity.UserActivityLog; -import in.gov.chennaicorporation.gccoffice.repository.UserActivityLogRepository; - -import java.util.List; - -@Service -public class UserActivityTimelineService { - - private final UserActivityLogRepository userActivityLogRepository; - - @Autowired - public UserActivityTimelineService(UserActivityLogRepository userActivityLogRepository) { - this.userActivityLogRepository = userActivityLogRepository; - } - - public List getUserActivityTimeline(String userId) { - return userActivityLogRepository.findByUserIdOrderByTimestampDesc(userId); - } -} - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/APIController.java deleted file mode 100644 index 44c28ab7..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/APIController.java +++ /dev/null @@ -1,64 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.sos.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -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 in.gov.chennaicorporation.gccoffice.sos.service.SOSService; - -@RequestMapping("gcc/api/sos") -@RestController("sosRest") -public class APIController { - private SOSService sosService; - - @Autowired - public APIController(SOSService sosService) { - this.sosService = sosService; - } - - @GetMapping(value="/getZoneAndWard") - public List getZoneAndWard() { - return sosService.getZoneAndWard(); - } - - @GetMapping(value="/getRescueList") - public List getRescueList(@RequestParam(value = "", required = false) String status) { - return sosService.getRescueList(status); - } - - @GetMapping(value="/getRescueUpdateData") - public List getRequestDataById(@RequestParam(value = "", required = false) String rescueid) { - return sosService.getRequestDataById(rescueid); - } - - @PostMapping(value="/saveRequest") - public List saveRequest( - @RequestParam(value="contact_name", required = false) String contact_name, - @RequestParam(value="contact_number", required = false) String contact_number, - @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="streetid", required = false) String streetid, - @RequestParam(value="streetname", required = false) String streetname, - @RequestParam(value="location_details", required = false) String location_details, - @RequestParam(value="request_type", required = false) String request_type, - @RequestParam(value="no_of_count", required = false) String no_of_count, - @RequestParam(value="if_any", required = false) String if_any, - @RequestParam(value="land_mark", required = false) String land_mark, - @RequestParam(value="remarks", required = false) String remarks, - @RequestParam(value="loginId", required = false) String loginId, - @RequestParam(value="mode", required = false) String mode - ){ - return sosService.saveRequest(contact_name, contact_number, - latitude, longitude, zone, ward, streetid, streetname, - location_details, request_type, no_of_count, if_any, - land_mark, remarks, loginId,mode); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/SOSController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/SOSController.java deleted file mode 100644 index 6f1381af..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/SOSController.java +++ /dev/null @@ -1,44 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.sos.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/sos") -@Controller("SOSRestController") -public class SOSController { - - private String BasePath = "modules/sos/"; - - @GetMapping({"", "/", "/index"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"inbox"; - } - - @GetMapping({"/new"}) - public String sosNew(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_sos"; - } - - @GetMapping({"/pending"}) - public String sosPending(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"pending_inbox"; - } - - @GetMapping({"/closed"}) - public String sosClosed(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"closed_inbox"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/package-info.java deleted file mode 100644 index e8c9bf70..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.sos.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/sos/package-info.java deleted file mode 100644 index e52ecfbc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.sos; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/service/SOSService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/sos/service/SOSService.java deleted file mode 100644 index df3cbb36..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/service/SOSService.java +++ /dev/null @@ -1,192 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.sos.service; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -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; - -@Service("sosService") -public class SOSService { - private JdbcTemplate jdbcTemplate; - private final Environment environment; - private String fileBaseUrl; - - @Autowired - public SOSService(Environment environment) { - this.environment = environment; - this.fileBaseUrl="https://gccservices.in"; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlGccSOSDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getZoneAndWard(){ - String SqlQuery = ""; - - SqlQuery = "SELECT LPAD(CAST(zone AS UNSIGNED), 2, '0') AS zone, " - + "GROUP_CONCAT(LPAD(CAST(divid AS UNSIGNED), 3, '0') " - + "ORDER BY CAST(divid AS UNSIGNED) ASC) AS wards " - + "FROM petition_master.councillor GROUP BY CAST(zone AS UNSIGNED) " - + "ORDER BY CAST(zone AS UNSIGNED) ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getRescueList(String status){ - String SqlQuery = ""; - - SqlQuery = "SELECT *,CASE " - + " WHEN status = 1 THEN 'Closed' " - + " WHEN status = 0 THEN 'Pending' " - + " ELSE 'Unknown' " - + " END AS statusText FROM `rescue` where isactive=1"; - if(status!="") { - SqlQuery = SqlQuery + " AND `status`='"+status+"'"; - } - - System.out.println(SqlQuery); - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional - public List> getRequestDataById( - String rescue_id){ - String sqlQuery = "SELECT *,CASE" - + " WHEN status = 0 THEN 'Pending' " - + " WHEN status = 1 THEN 'Closed' " - + " ELSE 'unknown'" - + " END AS status_name " - + " FROM `rescue` WHERE `id`='"+rescue_id+"'"; - List> result = jdbcTemplate.queryForList(sqlQuery); - Map response = new HashMap<>(); - if (result.isEmpty()) { - return result; - }else { - - String sqlQuery2 = "SELECT *,CONCAT('"+fileBaseUrl+"/gccofficialapp/files', filepath) AS imageUrl " - + "FROM `rescue_officer_update` WHERE rescue_id='"+rescue_id+"'"; - List> result2 = jdbcTemplate.queryForList(sqlQuery2); - System.out.println(sqlQuery2); - // Add the result2 and result3 to the main result map - result.get(0).put("officer_activity_data", result2); - } - response.put("status", "success"); - response.put("message", "Request Information"); - response.put("Data", result); - return Collections.singletonList(response); - } - - - @Transactional - public List> saveRequest( - String contact_name, - String contact_number, - String latitude, - String longitude, - String zone, - String ward, - String streetid, - String streetname, - String location_details, - String request_type, - String no_of_count, - String if_any, - String land_mark, - String remarks, - String loginId, - String mode - ) { - List> result=null; - Map response = new HashMap<>(); - int lastInsertId = 0; - - String sqlQuery = "INSERT INTO `rescue`(`contact_name`, `contact_number`, `latitude`, `longitude`, `zone`, `ward`, " - + "`streetid`, `streetname`, `location_details`, `request_type`, `no_of_count`, `if_any`, `land_mark`, " - + "`remarks`, `user_id`,`modeofcomplient`) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - try { - int affectedRows = jdbcTemplate.update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { - PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); - ps.setString(1, contact_name); - ps.setString(2, contact_number); - ps.setString(3, latitude); - ps.setString(4, longitude); - ps.setString(5, zone); - ps.setString(6, ward); - ps.setString(7, streetid); - ps.setString(8, streetname); - ps.setString(9, location_details); - ps.setString(10, request_type); - ps.setString(11, no_of_count); - ps.setString(12, if_any); - ps.setString(13, land_mark); - ps.setString(14, remarks); - ps.setString(15, loginId); - ps.setString(16, mode); - 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 SOS request was inserted successfully!"); - System.out.println("A new SOS request was inserted successfully! Insert ID: " + generatedId); - } else { - response.put("status", "error"); - response.put("message", "Failed to insert a new SOS request."); - } - } 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); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/sos/service/package-info.java deleted file mode 100644 index e10b410f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/sos/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.sos.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/configuration/TaxCollectionRepositoryConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/configuration/TaxCollectionRepositoryConfig.java deleted file mode 100644 index c073962c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/configuration/TaxCollectionRepositoryConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.configuration; - -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@Configuration -public class TaxCollectionRepositoryConfig { - // Additional configuration related to tax collection repositories, if needed -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/controller/MainController.java deleted file mode 100644 index 4ef86a96..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/controller/MainController.java +++ /dev/null @@ -1,70 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.controller; - -import java.nio.file.Paths; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.Asset; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategory; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetCategoryQuestion; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameter; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetParameterQuestions; -import in.gov.chennaicorporation.gccoffice.qrassetfeedback.data.AssetQuestion; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestEntity; -import in.gov.chennaicorporation.gccoffice.taxcollection.repository.TaxCollectionRequestRepository; - -@RequestMapping("/gcc/taxcollection") -@Controller("taxCollectionController") -public class MainController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - private final TaxCollectionRequestRepository taxCollectionRequestRepository; - - @Autowired - public MainController( - RestTemplate restTemplate, - AppConfig appConfig, - TaxCollectionRequestRepository taxCollectionRequestRepository) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - this.taxCollectionRequestRepository = taxCollectionRequestRepository; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return "modules/taxcollection/index"; - } - - @GetMapping("/request-create") - public String CreateRequest(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - List taxCollectionRequestEntities = taxCollectionRequestRepository.showAll(); - model.addAttribute("taxCollectionRequestEntities",taxCollectionRequestEntities); - return "modules/taxcollection/request-create"; - } - - @GetMapping("/request-list") - public String RequestList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - List taxCollectionRequestEntities = taxCollectionRequestRepository.showAll(); - model.addAttribute("taxCollectionRequestEntities",taxCollectionRequestEntities); - return "modules/taxcollection/request-list"; - } - - @GetMapping("/showimage") - public String showimage(Model model) { - return "modules/taxcollection/request-create"; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/controller/TaxCollectionRestController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/controller/TaxCollectionRestController.java deleted file mode 100644 index ee3034e1..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/controller/TaxCollectionRestController.java +++ /dev/null @@ -1,166 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.controller; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.time.LocalDateTime; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletRequest; -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestEntity; -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestStatusEntity; -import in.gov.chennaicorporation.gccoffice.taxcollection.repository.TaxCollectionRequestRepository; -import in.gov.chennaicorporation.gccoffice.taxcollection.service.TaxCollectionService; - -@RequestMapping("/gcc/api/taxcollection") -@RestController("taxCollectionRestController") -public class TaxCollectionRestController { - - private final TaxCollectionRequestRepository taxCollectionRequestRepository; - private final RestTemplate restTemplate; - private final AppConfig appConfig; - private final TaxCollectionService taxCollectionService; - private final String uploadDirectory; - - String bodyMessage = ""; - @Autowired - public TaxCollectionRestController( - TaxCollectionRequestRepository taxCollectionRequestRepository, - RestTemplate restTemplate, - AppConfig appConfig, - TaxCollectionService taxCollectionService, - @Value("${file.upload.directory}") String uploadDirectory) { - this.taxCollectionRequestRepository = taxCollectionRequestRepository; - this.restTemplate = restTemplate; - this.appConfig = appConfig; - this.taxCollectionService = taxCollectionService; - this.uploadDirectory = uploadDirectory; - } - - // API Calls List - @GetMapping(value = "/getPropertTaxPersonalDetails") - public String getPtaxpersonalDetails(@RequestParam String ptax) { - String ptaxTxt=ptax; - String[] ptaxparts = ptaxTxt.split("-"); - String serviceId = "PT"; - String SetInput = "{\"ZONE\":\""+ptaxparts[0]+"\",\"DIV\":\""+ptaxparts[1]+"\",\"BILL\":\""+ptaxparts[2]+"\",\"SB\":\""+ptaxparts[3]+"\"}"; - - ResponseEntity response = restTemplate.getForEntity("https://chennaicorporation.gov.in/gcc/online-payment/property-tax/mobile-reg/mob_Asses_det.jsp?ServiceID={serviceId}&SetInput={SetInput}", - String.class, - serviceId, - SetInput); - bodyMessage = response.getBody().trim(); - - return bodyMessage; - } - - // List - @GetMapping(value = "/getTaxCollectionRequest") - private List getTaxCollectionRequest(){ - return taxCollectionRequestRepository.showAll(); - } - - @GetMapping(value = "/getTaxCollectionRequestById") - private ResponseEntity getTaxCollectionRequestById(@RequestParam("request_id") Integer request_id) { - Optional result = taxCollectionRequestRepository.findById(request_id); - - if (result.isPresent()) { - return ResponseEntity.ok(result.get()); // Return the entity if it exists - } else { - return ResponseEntity.notFound().build(); // Return a 404 Not Found if the entity does not exist - } - } - - // Save & Update - @RequestMapping(value = "/saveTaxCollectionRequest", method = RequestMethod.POST) - public String saveTaxCollectionRequest(HttpServletRequest request, - @RequestParam("name") String name, - @RequestParam("mobile") String mobile, - @RequestParam("ptax") String ptax, - @RequestParam("usertype") String usertype, - @RequestParam("availabilitydate") String availabilitydate, - @RequestParam(name = "created_by", required = false) Integer created_by) { - TaxCollectionRequestEntity taxCollectionRequestEntity = new TaxCollectionRequestEntity(); - - String userId = LoginUserInfo.getLoginUserId(); - System.out.println("TaxCollectionRestController -> Login User ID: "+userId); - - LocalDateTime cdate = LocalDateTime.now(); - - if (created_by == null) { - created_by = 0; - } - - taxCollectionRequestEntity.setName(name); - taxCollectionRequestEntity.setMobile(mobile); - taxCollectionRequestEntity.setPtax(ptax); - taxCollectionRequestEntity.setUsertype(usertype); - taxCollectionRequestEntity.setAvailabilitydate(availabilitydate); - taxCollectionRequestEntity.setCreatedBy(created_by); - taxCollectionRequestEntity.setcDate(cdate.toString()); - taxCollectionRequestEntity.setIsActive(true); - taxCollectionRequestEntity.setIsDelete(false); - taxCollectionRequestEntity.setStatus("open"); - Integer lastinsertid = taxCollectionService.saveTaxCollectionRequest(taxCollectionRequestEntity); - return "Success"; - } - - @RequestMapping(value = "/saveTaxCollectionRequestStatus", method = RequestMethod.POST) - public String saveTaxCollectionRequestStatus(HttpServletRequest request, - @RequestParam("status") String status, - @RequestParam("comments") String comments, - @RequestParam("request_id") TaxCollectionRequestEntity request_id, - @RequestParam(name = "created_by", required = false) Integer created_by) { - - TaxCollectionRequestStatusEntity taxCollectionRequestStatusEntity = new TaxCollectionRequestStatusEntity(); - - LocalDateTime cdate = LocalDateTime.now(); - - if (created_by == null) { - created_by = 0; - } - - taxCollectionRequestStatusEntity.setStatus(status); - taxCollectionRequestStatusEntity.setComments(comments); - taxCollectionRequestStatusEntity.setTaxCollectionRequestEntity(request_id); - taxCollectionRequestStatusEntity.setCreatedBy(created_by); - taxCollectionRequestStatusEntity.setcDate(cdate.toString()); - taxCollectionRequestStatusEntity.setIsActive(true); - taxCollectionRequestStatusEntity.setIsDelete(false); - //Integer lastinsertid = taxCollectionService.saveTaxCollectionRequest(taxCollectionRequestStatusEntity); - return "Success"; - } - - @GetMapping("/files") - public ResponseEntity> listFiles() { - try { - List files = Files.list(Paths.get(uploadDirectory)) - .map(path -> path.getFileName().toString()) - .collect(Collectors.toList()); - - return ResponseEntity.ok(files); - } catch (IOException e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.emptyList()); - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/entity/TaxCollectionRequestEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/entity/TaxCollectionRequestEntity.java deleted file mode 100644 index 380e8318..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/entity/TaxCollectionRequestEntity.java +++ /dev/null @@ -1,198 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@Entity -@Table(name = "collection_request") -@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler"}) -public class TaxCollectionRequestEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "request_id",nullable = false) - private Integer request_id; - - @Column(name = "request_no",nullable = true) - private String requestNo; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "mobile",nullable = false) - private String mobile; - - @Column(name = "ptax",nullable = false) - private String ptax; - - @Column(name = "usertype",nullable = false) - private String usertype; - - @Column(name = "availability_date",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String availabilitydate; - - @Column(name = "status", nullable = false, columnDefinition = "VARCHAR(255) DEFAULT 'open'") - private String status; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - - public TaxCollectionRequestEntity() { - - } - - - public TaxCollectionRequestEntity(Integer request_id, String requestNo, String name, String mobile, String ptax, - String usertype, String availabilitydate, String status, Boolean isDelete, Boolean isActive, - Integer createdBy, String cDate) { - super(); - this.request_id = request_id; - this.requestNo = requestNo; - this.name = name; - this.mobile = mobile; - this.ptax = ptax; - this.usertype = usertype; - this.availabilitydate = availabilitydate; - this.status = status; - this.isDelete = isDelete; - this.isActive = isActive; - this.createdBy = createdBy; - this.cDate = cDate; - } - - - public Integer getRequest_id() { - return request_id; - } - - - public void setRequest_id(Integer request_id) { - this.request_id = request_id; - } - - - public String getRequestNo() { - return requestNo; - } - - - public void setRequestNo(String requestNo) { - this.requestNo = requestNo; - } - - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - public String getMobile() { - return mobile; - } - - - public void setMobile(String mobile) { - this.mobile = mobile; - } - - - public String getPtax() { - return ptax; - } - - - public void setPtax(String ptax) { - this.ptax = ptax; - } - - - public String getUsertype() { - return usertype; - } - - - public void setUsertype(String usertype) { - this.usertype = usertype; - } - - - public String getAvailabilitydate() { - return availabilitydate; - } - - - public void setAvailabilitydate(String availabilitydate) { - this.availabilitydate = availabilitydate; - } - - - public String getStatus() { - return status; - } - - - public void setStatus(String status) { - this.status = status; - } - - - public Boolean getIsDelete() { - return isDelete; - } - - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - - public Boolean getIsActive() { - return isActive; - } - - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } - - - public Integer getCreatedBy() { - return createdBy; - } - - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - - public String getcDate() { - return cDate; - } - - - public void setcDate(String cDate) { - this.cDate = cDate; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/entity/TaxCollectionRequestStatusEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/entity/TaxCollectionRequestStatusEntity.java deleted file mode 100644 index b03e8fbd..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/entity/TaxCollectionRequestStatusEntity.java +++ /dev/null @@ -1,126 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@Entity -@Table(name = "collection_request_status") -@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler"}) -public class TaxCollectionRequestStatusEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "request_status_id",nullable = false) - private Integer request_status_id; - - @ManyToOne - @JoinColumn(name="request_id",nullable = false) - private TaxCollectionRequestEntity taxCollectionRequestEntity; - - @Column(name = "status",nullable = false) - private String status ; - - @Column(name = "comments",nullable = false) - private String comments; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - public TaxCollectionRequestStatusEntity() { - - } - - public TaxCollectionRequestStatusEntity(Integer request_status_id, - TaxCollectionRequestEntity taxCollectionRequestEntity, String status, String comments, Integer createdBy, - String cDate, Boolean isDelete, Boolean isActive) { - super(); - this.request_status_id = request_status_id; - this.taxCollectionRequestEntity = taxCollectionRequestEntity; - this.status = status; - this.comments = comments; - this.createdBy = createdBy; - this.cDate = cDate; - this.isDelete = isDelete; - this.isActive = isActive; - } - - public Integer getRequest_status_id() { - return request_status_id; - } - - public void setRequest_status_id(Integer request_status_id) { - this.request_status_id = request_status_id; - } - - public TaxCollectionRequestEntity getTaxCollectionRequestEntity() { - return taxCollectionRequestEntity; - } - - public void setTaxCollectionRequestEntity(TaxCollectionRequestEntity taxCollectionRequestEntity) { - this.taxCollectionRequestEntity = taxCollectionRequestEntity; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getComments() { - return comments; - } - - public void setComments(String comments) { - this.comments = comments; - } - - public Integer getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(Integer createdBy) { - this.createdBy = createdBy; - } - - public String getcDate() { - return cDate; - } - - public void setcDate(String cDate) { - this.cDate = cDate; - } - - public Boolean getIsDelete() { - return isDelete; - } - - public void setIsDelete(Boolean isDelete) { - this.isDelete = isDelete; - } - - public Boolean getIsActive() { - return isActive; - } - - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/repository/TaxCollectionRequestRepository.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/repository/TaxCollectionRequestRepository.java deleted file mode 100644 index cdc7bd7d..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/repository/TaxCollectionRequestRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.repository; - -import java.util.List; - -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestEntity; - -@Repository -@Transactional -public interface TaxCollectionRequestRepository extends JpaRepository { - - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `collection_request`", nativeQuery = true) - List showAll(); - - // Insert - @Modifying - @Query(value ="insert into `collection_request` (`name`,`mobile`,`ptax`,`usertype`,`availability_date`, `created_by`) values (:name, :mobile, :ptax, :usertype, :availabilitydate, :created_by)", nativeQuery = true) - void saveData(String name, String mobile, String ptax, String usertype, String availabilitydate, Integer created_by); - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/service/TaxCollectionService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/service/TaxCollectionService.java deleted file mode 100644 index 6e4561d2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/taxcollection/service/TaxCollectionService.java +++ /dev/null @@ -1,39 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.taxcollection.service; - -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestEntity; -import in.gov.chennaicorporation.gccoffice.taxcollection.entity.TaxCollectionRequestStatusEntity; -import in.gov.chennaicorporation.gccoffice.taxcollection.repository.TaxCollectionRequestRepository; - -@Service -public class TaxCollectionService { - private final TaxCollectionRequestRepository taxCollectionRequestRepository; - - - @Autowired - public TaxCollectionService(TaxCollectionRequestRepository taxCollectionRequestRepository) { - this.taxCollectionRequestRepository = taxCollectionRequestRepository; - } - - @Transactional - public Integer getLastInsertedId() { - return taxCollectionRequestRepository.getLastInsertedId(); - } - - @Transactional - public Integer saveTaxCollectionRequest(TaxCollectionRequestEntity taxCollectionRequestData) { - TaxCollectionRequestEntity taxCollectionRequestEntity = taxCollectionRequestRepository.save(taxCollectionRequestData); - return taxCollectionRequestEntity.getRequest_id(); - } - /* - @Transactional - public Integer saveTaxCollectionRequestStatus(TaxCollectionRequestEntity taxCollectionRequestData) { - TaxCollectionRequestEntity taxCollectionRequestEntity = taxCollectionRequestRepository.save(taxCollectionRequestData); - return taxCollectionRequestStatusEntity.(); - } - */ -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/.DS_Store deleted file mode 100644 index 4a3b5d22..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/ApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/ApiController.java deleted file mode 100644 index 0d9b4651..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/ApiController.java +++ /dev/null @@ -1,625 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vendor.controller; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataAccessException; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -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.client.RestTemplate; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.vendor.service.StreetVendorService; -import in.gov.chennaicorporation.gccoffice.vendor.service.createventService; - -@RestController("streetvendorApiController") -@RequestMapping("/gcc/api/streetvendor") -public class ApiController { - - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - private StreetVendorService streetVendorService; - - @Autowired - public createventService createventservice; - - @Autowired - public ApiController(RestTemplate restTemplate, AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - } - - @Autowired - private Environment environment; - - @GetMapping("/vendorCommiteeList") - public String getVendorCommiteeDetails(){ - String apiUrl = appConfig.mobileservice + "/gccofficialapp/api/streetvendor/vendingCommiteeList"; - ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); - return responseEntity.getBody(); - } - -// @GetMapping("/vendorCommiteeListbyID") -// public String getVendorCommiteeDetailsByID(@RequestParam("id") Long id) { -// String apiUrl = appConfig.mobileservice + "/gccofficialapp/api/streetvendor/vendingCommiteeListbyId?id=" + id; -// ResponseEntity responseEntity = restTemplate.getForEntity(apiUrl, String.class); -// return responseEntity.getBody(); -// } - - @GetMapping("/vendorCommiteeListbyID") - public ResponseEntity>> getVendorCommiteeDetailsByID(@RequestParam("id") Long id) { - String apiUrl = appConfig.mobileservice + "/gccofficialapp/api/streetvendor/vendingCommiteeListbyId?id=" + id; - ResponseEntity responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, null, List.class); - //System.out.println("responseEntity...."+responseEntity); - return ResponseEntity.ok(responseEntity.getBody()); - } - - @GetMapping("/vendingCommiteeList") - public ResponseEntity>> getVendingCommiteeList(@RequestParam("date") String date) { - String apiUrl = appConfig.mobileservice + "/gccofficialapp/api/streetvendor/vendingCommiteeList?date=" + date; - ResponseEntity responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, null, List.class); - - List saved_request_no=createventservice.removeSavedVendorDetails(); - //System.out.println("saved_request_no="+saved_request_no); - - // Filter out matching vendor_req_id entries - List> originalList = responseEntity.getBody(); - List> filteredList = originalList.stream().filter(item -> !saved_request_no.contains(String.valueOf(item.get("vendor_req_id")))) - .collect(Collectors.toList()); - - return ResponseEntity.ok(filteredList); - } - - -// @GetMapping("/vendorDetailsByReqId") -// public ResponseEntity>> getVendorDetailsByReqId(@RequestParam("requestId") String requestId) { -// String apiUrl = appConfig.mobileservice + "/gccofficialapp/api/streetvendor/vendorDetailsByReqId?requestId=" + requestId; -// ResponseEntity responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, null, List.class); -// return ResponseEntity.ok(responseEntity.getBody()); -// } - - - @PostMapping("/savedetailsforvendor") - public ResponseEntity> savedetailsforvendor(@RequestBody Map payload) - { - return createventservice.saveVendorDetails(payload); - } - - @PostMapping("/saveBulkVendorDetails") - public ResponseEntity> saveBulkVendorDetails(@RequestBody Map payload) { - return createventservice.saveBulkVendorDetails(payload); - } - - - @GetMapping("/vendingCommiteeDetails") - public List> getvendingCommiteeDetails(@RequestParam("event_req_id") String event_req_id) { - - return createventservice.getCommiteeDetails(event_req_id); - } - - @GetMapping("/vendingDetailsWeb") - public List> getvendingDetailsWeb(@RequestParam String cby) { - - return streetVendorService.getCommiteeDetailsWeb(cby); - } - - @GetMapping("/webVendorDetailsByReqId") - public List> getwebVendorDetailsByReqId(@RequestParam("requestId") String requestId) { - - return streetVendorService.getwebVendorDetailsByReqId(requestId); - } - -// sanjay - -// @GetMapping("/wards-by-zone") -// -// public List> getWardsByZone(@RequestParam("zoneId") int zoneId) { -// return streetVendorService.fetchWardsByZone(zoneId); -// } - - - -// @PostMapping("/saveDetails") -// public ResponseEntity> saveVenderDetails( -// -// @RequestParam String latitude, -// @RequestParam String longitude, -// @RequestParam String zone, -// @RequestParam String ward, -// @RequestParam String landmark, -// @RequestParam String vending_district, -// @RequestParam int vending_pincode, -// @RequestParam int vending_category, -// @RequestParam String vending_space, -// @RequestParam boolean pm_svanidhi_loan, -// @RequestParam boolean bank_acc_status, -// @RequestParam (required = false, name = "bank_passbook" )MultipartFile bank_passbook, -// @RequestParam MultipartFile street_vendor_photo, -// @RequestParam String name, -// @RequestParam String f_h_name, -// @RequestParam String mobile_number, -// @RequestParam String dob, -// @RequestParam String gender, -// @RequestParam int social_category, -// @RequestParam boolean diff_abled, -// @RequestParam int education_status, -// @RequestParam int marital_status, -// @RequestParam int no_of_fam_mem, -// @RequestParam boolean are_any_fam_mem_invol_str, -//// @RequestParam String vending_address, -// -// @RequestParam String door_no, -// @RequestParam String streetname, -// @RequestParam String areaname, -// @RequestParam String present_district, -// @RequestParam int present_pincode, -// @RequestParam MultipartFile ration_card_photo, -// @RequestParam MultipartFile aadhar_front_photo, -// @RequestParam MultipartFile aadhar_back_photo, -// @RequestParam String aadharNo) { -// -// String presentAddress = door_no + ", " + streetname + ", " + areaname; -// -// System.out.println("bank_passbook...."+bank_passbook); -// System.out.println("ration_card_photo...."+ration_card_photo); -// System.out.println("street_vendor_photo...."+street_vendor_photo); -// System.out.println("aadhar_front_photo...."+aadhar_front_photo); -// System.out.println("aadhar_back_photo...."+aadhar_back_photo); -// -// String bankPassbookPath = ""; -// -// // Only upload passbook if status is true -// if (bank_acc_status) { -// if (bank_passbook != null && !bank_passbook.isEmpty()) { -// bankPassbookPath = streetVendorService.fileUpload (bank_passbook, "bank_passbook"); -// } else { -// return ResponseEntity.badRequest().body(Map.of( -// "status", false, -// "description", "Bank passbook is required when account status is Yes" -// )); -// } -// } -// String rationCardPath = streetVendorService.fileUpload(ration_card_photo, "ration_card"); -// String streetVendorPhotoPath = streetVendorService.fileUpload(street_vendor_photo, "vendor_photo"); -// String aadharFrontPhotoPath = streetVendorService.fileUpload(aadhar_front_photo, "aadhar_front"); -// String aadharBackPhotoPath = streetVendorService.fileUpload(aadhar_back_photo, "aadhar_back"); -// -// String saveStatus = streetVendorService.saveStreetVendorDetails( -// latitude, longitude,zone, ward, landmark, vending_district, vending_pincode, vending_category, vending_space, -// pm_svanidhi_loan, bank_acc_status, bankPassbookPath, -// streetVendorPhotoPath, name, f_h_name, mobile_number,dob, -// gender, social_category, diff_abled, education_status, marital_status, -// no_of_fam_mem, are_any_fam_mem_invol_str,presentAddress, present_district, present_pincode, -// rationCardPath,aadharFrontPhotoPath, aadharBackPhotoPath,aadharNo); -// -// if (saveStatus == null || saveStatus.equals("error")) { -// return ResponseEntity.ok(Map.of( -// "status", false, -// "message", "failed", -// "description", "Failed to save the details" -// )); -// } -// -// return ResponseEntity.ok(Map.of( -// "status", true, -// "message", "success", -// "description", "Details saved successfully", -// "vendor_req_id", saveStatus -// )); -// } - - - @PostMapping("/saveDetails") - public ResponseEntity> saveVenderDetails( - - - @RequestParam (required = false)String latitude, - @RequestParam (required = false)String longitude, - @RequestParam (required = false)String zone, - @RequestParam (required = false)String ward, - @RequestParam (required = false)String landmark, - @RequestParam (required = false)String vending_district, - @RequestParam (required = false)Integer vending_pincode, - @RequestParam Integer vending_category, - @RequestParam Integer tamilvending_category, - @RequestParam (required = false)String vending_space, - @RequestParam (required = false) Boolean pm_svanidhi_loan, - @RequestParam (required = false) Boolean bank_acc_status, - @RequestParam (required = false, name = "bank_passbook" )MultipartFile bank_passbook, - @RequestParam (required = false) MultipartFile street_vendor_photo, - @RequestParam String name, - @RequestParam (required = false)String f_h_name, - @RequestParam String mobile_number, - @RequestParam (required = false)String dob, - - @RequestParam (required = false)String gender, - @RequestParam (required = false)Integer social_category, - @RequestParam (required = false)Boolean diff_abled, - @RequestParam (required = false)Integer education_status, - @RequestParam (required = false)Integer marital_status, - @RequestParam (required = false)Integer no_of_fam_mem, - @RequestParam (required = false)Boolean are_any_fam_mem_invol_str, - - @RequestParam (required = false)String door_no, - @RequestParam (required = false)String streetname, - @RequestParam (required = false)String areaname, - @RequestParam (required = false)String present_district, - @RequestParam (required = false)Integer present_pincode, - @RequestParam (required = false)MultipartFile ration_card_photo, - @RequestParam (required = false)MultipartFile aadhar_front_photo, - @RequestParam (required = false)MultipartFile aadhar_back_photo, - @RequestParam (required = false)String aadharNo, - @RequestParam (required = false)String tamil_name, - @RequestParam (required = false)String tamil_f_h_name, - @RequestParam (required = false)String tamil_landmark, - @RequestParam (required = false)String tamil_gender, - @RequestParam (required = false)String tamil_present_district, - @RequestParam String userId) { - - //String presentAddress = door_no + ", " + streetname + ", " + areaname; - - String data=tamil_name +"=="+tamil_f_h_name+"=="+tamil_landmark+"=="+tamil_gender+"=="+tamil_present_district; - - //System.out.println("data="+data); - - String doorNoVal = (door_no != null && !door_no.trim().isEmpty()) ? door_no : ""; - String streetNameVal = (streetname != null && !streetname.trim().isEmpty()) ? streetname : ""; - String areaNameVal = (areaname != null && !areaname.trim().isEmpty()) ? areaname : ""; - - - - String presentAddress = String.join(", ", doorNoVal, streetNameVal, areaNameVal); - - String bankPassbookPath = null; - - // Only upload passbook if status is true - if (Boolean.TRUE.equals(bank_acc_status)) { - - if (bank_passbook != null && !bank_passbook.isEmpty()) { - - bankPassbookPath = streetVendorService.fileUpload(bank_passbook, "street_vendor_bank"); - } else { - return ResponseEntity.badRequest().body(Map.of( - "status", false, - "description", "Bank passbook is required when account status is Yes" - )); - } - } - - - String rationCardPath=null; - String streetVendorPhotoPath=null; - String aadharFrontPhotoPath=null; - String aadharBackPhotoPath=null; - - if(ration_card_photo != null && !ration_card_photo.isEmpty()) - { - rationCardPath = streetVendorService.fileUpload(ration_card_photo, "street_vendor_ration"); - } - if (street_vendor_photo != null && !street_vendor_photo.isEmpty()) - { - streetVendorPhotoPath = streetVendorService.fileUpload(street_vendor_photo, "street_vendor_photo"); - } - if (aadhar_front_photo != null && !aadhar_front_photo.isEmpty()) - { - aadharFrontPhotoPath = streetVendorService.fileUpload(aadhar_front_photo, "aadhar_front"); - } - if (aadhar_back_photo != null && !aadhar_back_photo.isEmpty()) - { - aadharBackPhotoPath = streetVendorService.fileUpload(aadhar_back_photo, "aadhar_back"); - } - - - String saveStatus = streetVendorService.saveStreetVendorDetails( - latitude, longitude,zone, ward, landmark, vending_district, vending_pincode, vending_category, vending_space, - pm_svanidhi_loan, bank_acc_status, bankPassbookPath, - streetVendorPhotoPath, name, f_h_name, mobile_number,dob, - gender, social_category, diff_abled, education_status, marital_status, - no_of_fam_mem, are_any_fam_mem_invol_str,presentAddress, present_district, present_pincode, - rationCardPath,aadharFrontPhotoPath, aadharBackPhotoPath,aadharNo,userId,tamil_name,tamil_f_h_name,tamil_landmark,tamil_gender,tamil_present_district,tamilvending_category); - - if (saveStatus == null || saveStatus.equals("error")) { - return ResponseEntity.ok(Map.of( - "status", false, - "message", "failed", - "description", "Failed to save the details" - )); - } - - - return ResponseEntity.ok(Map.of( - "status", true, - "message", "success", - "description", "Details saved successfully", - "vendor_req_id", saveStatus - )); - } - - - - // check mobile number registered -// @GetMapping("/check-mobile") -// public ResponseEntity checkMobileNumber(@RequestParam String mobilenumber) { -// boolean exists = streetVendorService.isMobileRegistered(mobilenumber); -// -// return ResponseEntity.ok(exists); -// } - - - @GetMapping("/check-mobile") - public ResponseEntity> checkMobile(@RequestParam String mobilenumber) { - - Map response = new HashMap<>(); - - // Step 1: streetVendorService → check vendor_details - Integer vdid = streetVendorService.findLatestVendorIdByMobile(mobilenumber); - - if (vdid == null) { - // mobile not registered - response.put("exists", false); - response.put("blocked", false); - return ResponseEntity.ok(response); - } - - // Mobile exists - response.put("exists", true); - response.put("vdid", vdid); - - // Step 2: createventService → check vendor_request_list & vendor_postponed_list - Map vcStatus = createventservice.checkVendorInVendingTables(vdid); - String status = vcStatus.get("status").toString(); - - switch (status) { - case "POSTPONED": - response.put("blocked", true); - break; - case "Approved": - response.put("blocked", true); - break; - case "Rejected": - response.put("blocked", false); - break; - case "NO_EVENT": // exists but never applied in vending committee - response.put("blocked", true); - break; - default: - response.put("blocked", true); - break; - } - - return ResponseEntity.ok(response); - } - - - - - @PostMapping("/updateDetails") - public ResponseEntity> updateVenderDetails( - - @RequestParam (required = false)String latitude, - @RequestParam (required = false)String longitude, - @RequestParam (required = false)String zone, - @RequestParam (required = false)String ward, - @RequestParam (required = false)String landmark, - @RequestParam (required = false)String vending_district, - @RequestParam (required = false)Integer vending_pincode, - @RequestParam Integer vending_category, - @RequestParam Integer tamilvending_category, - @RequestParam (required = false)String vending_space, - @RequestParam (required = false) Boolean pm_svanidhi_loan, - @RequestParam (required = false) Boolean bank_acc_status, - @RequestParam (required = false, name = "bank_passbook" )MultipartFile bank_passbook, - @RequestParam (required = false) MultipartFile street_vendor_photo, - @RequestParam String name, - @RequestParam (required = false)String f_h_name, - @RequestParam String mobile_number, - @RequestParam (required = false)String dob, - - @RequestParam (required = false)String gender, - @RequestParam (required = false)Integer social_category, - @RequestParam (required = false)Boolean diff_abled, - @RequestParam (required = false)Integer education_status, - @RequestParam (required = false)Integer marital_status, - @RequestParam (required = false)Integer no_of_fam_mem, - @RequestParam (required = false)Boolean are_any_fam_mem_invol_str, - - @RequestParam (required = false)String door_no, - @RequestParam (required = false)String streetname, - @RequestParam (required = false)String areaname, - @RequestParam (required = false)String present_district, - @RequestParam (required = false)Integer present_pincode, - @RequestParam (required = false)MultipartFile ration_card_photo, - @RequestParam (required = false)MultipartFile aadhar_front_photo, - @RequestParam (required = false)MultipartFile aadhar_back_photo, - @RequestParam (required = false)String aadharNo, - @RequestParam (required = false)String raw_bank_passbook, - @RequestParam (required = false)String raw_street_vendor_photo, - @RequestParam (required = false)String raw_aadhar_front_photo, - @RequestParam (required = false)String raw_aadhar_back_photo, - @RequestParam (required = false)String raw_ration_card_photo, - @RequestParam (required = false)String tamil_name, - @RequestParam (required = false)String tamil_f_h_name, - @RequestParam (required = false)String tamil_landmark, - @RequestParam (required = false)String tamil_gender, - @RequestParam (required = false)String tamil_present_district, - @RequestParam String userId, - @RequestParam String vendor_req_id){ - - - String data = streetVendorService.logEntry(userId, vendor_req_id); - - if(data.equalsIgnoreCase("success")) { - - String bankPassbookPath = null; - String rationCardPath=null; - String streetVendorPhotoPath=null; - String aadharFrontPhotoPath=null; - String aadharBackPhotoPath=null; - - - - bankPassbookPath=raw_bank_passbook; - if(bank_passbook!=null && !bank_passbook.isEmpty()) { - bankPassbookPath = streetVendorService.fileUpload (bank_passbook, "street_vendor_bank"); - } - - rationCardPath=raw_ration_card_photo; - if(ration_card_photo!=null && !ration_card_photo.isEmpty()) { - rationCardPath = streetVendorService.fileUpload (ration_card_photo, "street_vendor_ration"); - } - - streetVendorPhotoPath=raw_street_vendor_photo; - if(street_vendor_photo!=null && !street_vendor_photo.isEmpty()) { - streetVendorPhotoPath = streetVendorService.fileUpload (street_vendor_photo, "street_vendor_photo"); - } - - aadharFrontPhotoPath=raw_aadhar_front_photo; - if(aadhar_front_photo!=null && !aadhar_front_photo.isEmpty()) { - aadharFrontPhotoPath = streetVendorService.fileUpload (aadhar_front_photo, "aadhar_front"); - } - - aadharBackPhotoPath=raw_aadhar_back_photo; - if(aadhar_back_photo!=null && !aadhar_back_photo.isEmpty()) { - aadharBackPhotoPath = streetVendorService.fileUpload (aadhar_back_photo, "aadhar_back"); - } - - String doorNoVal = (door_no != null && !door_no.trim().isEmpty()) ? door_no : ""; - String streetNameVal = (streetname != null && !streetname.trim().isEmpty()) ? streetname : ""; - String areaNameVal = (areaname != null && !areaname.trim().isEmpty()) ? areaname : ""; - - - String presentAddress = String.join(", ", doorNoVal, streetNameVal, areaNameVal); - - String sts=streetVendorService.updateStreetVendorDetailsWeb( - latitude, longitude,zone, ward, landmark, vending_district, vending_pincode, vending_category, vending_space, - pm_svanidhi_loan, bank_acc_status, bankPassbookPath, - streetVendorPhotoPath, name, f_h_name, mobile_number,dob, - gender, social_category, diff_abled, education_status, marital_status, - no_of_fam_mem, are_any_fam_mem_invol_str,presentAddress, present_district, present_pincode, - rationCardPath,aadharFrontPhotoPath, aadharBackPhotoPath,aadharNo,tamil_name,tamil_f_h_name,tamil_landmark,tamil_gender,tamil_present_district,tamilvending_category,userId,vendor_req_id); - - if(sts.equals("Error")) { - return ResponseEntity.ok(Map.of( - "status", false, - "message", "failed", - "description", "Failed to update the details" - )); - } - - return ResponseEntity.ok(Map.of( - "status", true, - "message", "success", - "description", "Details Updated successfully" - )); - - } - - else { - - return ResponseEntity.ok(Map.of( - "status", false, - "message", "failed", - "description", "Issues in log entry,So failed to update" - )); - } - - } - - @GetMapping("/vendingDetailsbyZoneWeb") - public List> vendingDetailsbyZoneWeb(@RequestParam String zone) { - - return streetVendorService.vendingDetailsbyZoneWeb(zone); - } - - - @GetMapping("/getvedingcommitteelist") - public List> getvedingcommitteelist(@RequestParam String date,@RequestParam String zones) - { - //System.out.println(date); - List> streetdb= streetVendorService.getvedingcommitteelist(date,zones); - List> savedList = createventservice.getsavedids(); - List> postponedList = createventservice.getPostponedList(); - - // Convert savedList → Set - Set savedIds = savedList.stream() - .filter(m -> m.get("vdid") != null) - .map(m -> Integer.parseInt(m.get("vdid").toString())) - .collect(Collectors.toSet()); - - // Convert postponedList → Map - Map> postponedMap = postponedList.stream() - .filter(m -> m.get("vdid") != null) - .collect(Collectors.toMap( - m -> Integer.parseInt(m.get("vdid").toString()), - m -> m - )); - List> finalList = new ArrayList<>(); - - for (Map row : streetdb) { - - int id = Integer.parseInt(row.get("id").toString()); - - // Skip if already saved in vendor_request_list - if (savedIds.contains(id)) { - continue; - } - - // If postponed, add status & remarks - if (postponedMap.containsKey(id)) { - Map postponed = postponedMap.get(id); - - row.put("vcp_status", postponed.get("status")); - row.put("vcp_remarks", postponed.get("remarks")); - - } - - finalList.add(row); - } - - return finalList; - } - - - @GetMapping("/vendorDetailsById") - public Map vendorDetailsById(@RequestParam("requestId") String requestId) { - // From gcc_street_vendor DB - List> mainDetails = streetVendorService.vendorDetailsById(requestId); - Map vendor = mainDetails.get(0); - - // From vendingcommitte DB - Map latestPostponed = createventservice.getLatestPostponed(requestId); - List> postponedHistory = createventservice.getPostponedHistory(requestId); - - vendor.put("latestPostponed", latestPostponed); - vendor.put("postponedHistory", postponedHistory); - - return vendor; - } - - @GetMapping("/getwardbyzone") - public List> ViewWardDropdown(@RequestParam String zone) { - - return streetVendorService.ViewWardDropdown(zone); - - } - - -} - - - diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/CreateEventAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/CreateEventAPIController.java deleted file mode 100644 index 6c004c63..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/CreateEventAPIController.java +++ /dev/null @@ -1,212 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vendor.controller; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.gccoffice.vendor.service.createventService; -import in.gov.chennaicorporation.gccoffice.vendor.service.StreetVendorService; - -@RequestMapping("/gcc/api/vending") -@RestController -public class CreateEventAPIController { - - @Autowired - private createventService createventservices; - - @Autowired - private StreetVendorService StreetVendorService; - - // @Autowired - // private Environment environment; - - @PostMapping("/save") - public ResponseEntity> saveEventWithFile( - @RequestParam("eventName") String eventName, - @RequestParam("eventDate") String eventDateStr, - @RequestParam("file") MultipartFile file, - @RequestParam("cby") String cby) { - - Map response = new HashMap<>(); - - try { - - if (file == null || file.isEmpty()) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "File is required"); - return ResponseEntity.badRequest().body(response); - } - - if (eventName == null || eventName.trim().isEmpty()) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Event name cannot be empty"); - return ResponseEntity.badRequest().body(response); - } - - LocalDate eventDate; - try { - eventDate = LocalDate.parse(eventDateStr); - } catch (Exception ex) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Invalid date format (use yyyy-MM-dd)"); - return ResponseEntity.badRequest().body(response); - } - - String eventFilePath = StreetVendorService.fileUpload(file, "event_file"); - - if (eventFilePath == null) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "File upload failed"); - return ResponseEntity.internalServerError().body(response); - } - - String saveStatus = createventservices.insertEvent(eventName, eventDate, eventFilePath, cby); - - if (saveStatus == null || saveStatus.equalsIgnoreCase("error")) { - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Failed to save event details"); - return ResponseEntity.internalServerError().body(response); - } - - response.put("status", true); - response.put("message", "success"); - response.put("description", "Details saved successfully"); - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - - response.put("status", false); - response.put("message", "failed"); - response.put("description", "Internal server error: " + e.getMessage()); - return ResponseEntity.internalServerError().body(response); - } - } - - // save file and get path - // private String saveFile(MultipartFile file) throws IOException { - // - // String uploadDirectory = environment.getProperty("file.upload.directory"); - // - // String folderName = environment.getProperty("vending.foldername"); - // - // String fileName = - // LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + - // "_" + file.getOriginalFilename(); - // - // String folderPath = uploadDirectory + "/" + folderName + "/"; - // - // - // Path dirPath = Paths.get(folderPath); - // if (!Files.exists(dirPath)) { - // Files.createDirectories(dirPath); - // } - // - // Path filePath = dirPath.resolve(fileName); - // - // Files.write(filePath, file.getBytes()); - // - // return filePath.toAbsolutePath().toString(); - // } - - @GetMapping("/dropdown-Event") - public ResponseEntity>> ViewDropdownEvent(@RequestParam String userId) { - try { - List> result = createventservices.ViewDropdownEvent(userId); - return ResponseEntity.ok(result); - } catch (Exception e) { - Map error = new HashMap<>(); - error.put("error", "Unable to fetch event list"); - error.put("details", e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonList(error)); - } - } - - @GetMapping("/committedropdown") - public List> ViewCommitteeDropdownEvent(@RequestParam String userId) { - - return createventservices.ViewCommitteeDropdownEvent(userId); - - } - - @GetMapping("/getreports") - public List> getreports( - @RequestParam(required = false) String meeting, - @RequestParam(required = false) String status, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam String userId) { - - List> streetdb = StreetVendorService.getdataforreport(zone, ward); // BASE LIST - List> vendingdb = createventservices.getdataforreport(meeting, status, userId); // FILTERED - // REQUEST - // LIST - - // Convert vendingdb to map: vdid → vendor record - Map> vendingMap = vendingdb.stream() - .filter(m -> m.get("vdid") != null) - .collect(Collectors.toMap( - m -> Integer.parseInt(m.get("vdid").toString()), - m -> m)); - - List> finalList = new ArrayList<>(); - - // Merge logic - for (Map row : streetdb) { - - int id = Integer.parseInt(row.get("id").toString()); - - if (!vendingMap.containsKey(id)) { - continue; - } - - // Merge map - Map merged = new HashMap<>(row); - Map vdata = vendingMap.get(id); - - merged.put("status", vdata.get("status")); - merged.put("remarks", vdata.get("remarks")); - merged.put("uid_no", vdata.get("uid_no")); - merged.put("event_req_id", vdata.get("event_req_id")); - merged.put("cdate", vdata.get("cdate")); - - finalList.add(merged); - } - - return finalList; - } - - @GetMapping("/finalvendorDetailsById") - public List> finalvendorDetailsById(String requestId) { - - return createventservices.finalvendorDetailsById(requestId); - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/MainController.java deleted file mode 100644 index 98e83aca..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/controller/MainController.java +++ /dev/null @@ -1,216 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vendor.controller; - -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.configuration.AppConfig; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.vendor.service.StreetVendorService; - -@RequestMapping("/gcc/vendor") -@Controller("vendorMainController") -public class MainController { - - private final LoginUserInfo loginUserInfo; - private final RestTemplate restTemplate; - private final AppConfig appConfig; - - @Autowired - public MainController(RestTemplate restTemplate,LoginUserInfo loginUserInfo, - AppConfig appConfig) { - this.restTemplate = restTemplate; - this.appConfig = appConfig; - this.loginUserInfo = loginUserInfo; - } - - @Autowired - private StreetVendorService streetVendorService; - - @GetMapping("/addevent") - public String viewAddEvent(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/vendors/addevent"; - } - - @GetMapping("/requestlist") - public String viewRequestList(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String zone=streetVendorService.getloginUserZone(userId); - model.addAttribute("zone",zone); - //System.out.println("zone="+zone); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/vendors/RequestList"; - } - - @GetMapping("/eventlist") - public String viewEventList(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String zone=streetVendorService.getloginUserZone(userId); - model.addAttribute("zone",zone); - //System.out.println("zone="+zone); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/vendors/EventList"; - } - - @GetMapping("/streetvendorform") - public String streetvendorform(Model model) - { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - - - List>communities=streetVendorService.fetchCommunities(); - //System.out.println("communities===="+communities); - model.addAttribute("communities", communities); - - - - List>maritalStatuses=streetVendorService.fetchMaritalStatus(); - //System.out.println("maritalStatuses===="+maritalStatuses); - model.addAttribute("maritalStatuses", maritalStatuses); - - - - List>educationList=streetVendorService.fetchEducationStatus(); - //System.out.println("educationList===="+educationList); - model.addAttribute("educationList", educationList); - - - - List>vendingCategories=streetVendorService.fetchvendingCategory(); - //System.out.println("vendingCategory===="+vendingCategories); - model.addAttribute("vendingCategories", vendingCategories); - - List>tamilvendingCategories=streetVendorService.fetchtamilvendingCategory(); - //System.out.println("tamilvendingCategories===="+tamilvendingCategories); - model.addAttribute("tamilvendingCategories", tamilvendingCategories); - - - //List>zones=streetVendorService.fetchZones(); - //System.out.println("zones===="+zones); - //model.addAttribute("zones", zones); - - return "modules/vendors/streetVendorRequestForm"; - } - - - @GetMapping("/streetvendorlist") - public String viewVendorRequestList(Model model) - { - String LoginUserId =LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - LoginUserInfo.getCurrentUserDetails().getUsername(); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - - List>communities=streetVendorService.fetchCommunities(); - model.addAttribute("communities", communities); - - - List>maritalStatuses=streetVendorService.fetchMaritalStatus(); - model.addAttribute("maritalStatuses", maritalStatuses); - - - List>educationList=streetVendorService.fetchEducationStatus(); - model.addAttribute("educationList", educationList); - - - List>vendingCategories=streetVendorService.fetchvendingCategory(); - model.addAttribute("vendingCategories", vendingCategories); - - List>tamilvendingCategories=streetVendorService.fetchtamilvendingCategory(); - model.addAttribute("tamilvendingCategories", tamilvendingCategories); - - return "modules/vendors/streetVendorRequestList"; - } - - @GetMapping("/zonerequests") - public String viewZoneBasedDetails(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - String zone=streetVendorService.getloginUserZone(userId); - model.addAttribute("zone",zone); - //System.out.println("zone="+zone); - - List>communities=streetVendorService.fetchCommunities(); - model.addAttribute("communities", communities); - - - List>maritalStatuses=streetVendorService.fetchMaritalStatus(); - model.addAttribute("maritalStatuses", maritalStatuses); - - - List>educationList=streetVendorService.fetchEducationStatus(); - model.addAttribute("educationList", educationList); - - - List>vendingCategories=streetVendorService.fetchvendingCategory(); - model.addAttribute("vendingCategories", vendingCategories); - - List>tamilvendingCategories=streetVendorService.fetchtamilvendingCategory(); - model.addAttribute("tamilvendingCategories", tamilvendingCategories); - - return "modules/vendors/zonerequests"; - - } - - @GetMapping("/certificate") - public String viewcertificate(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - int userId = Integer.parseInt(LoginUserId); - model.addAttribute("LoginUserId",LoginUserId); - - String zone=streetVendorService.getloginUserZone(userId); - model.addAttribute("zone",zone); - //System.out.println("zone="+zone); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/vendors/certificate"; - } - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/DateTimeUtil.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/DateTimeUtil.java deleted file mode 100644 index 061f8eb0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/DateTimeUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vendor.service; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -import org.springframework.stereotype.Component; - - - -@Component("vendorDateTimeUtil") // For vendo -public final class DateTimeUtil { - public static String getCurrentDateTime() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentYear() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentMonth() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentDay() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } - public static String getCurrentDateTimeMysql() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/StreetVendorService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/StreetVendorService.java deleted file mode 100644 index 4991c234..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/StreetVendorService.java +++ /dev/null @@ -1,658 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vendor.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.PreparedStatement; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.stream.Collectors; - -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.dao.EmptyResultDataAccessException; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - - - -@Service -public class StreetVendorService { - - - @Autowired - @Qualifier("vendorDateTimeUtil") - private DateTimeUtil dateTimeUtil; - - - private final Environment environment; - - private String fileBaseUrl; - - private JdbcTemplate jdbcTemplate; - - - @Autowired - public void setDataSource(@Qualifier("mysqlGccStreetVendorDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - private static final int STRING_LENGTH = 15; - private static final Random RANDOM = new SecureRandom(); - - - public StreetVendorService(Environment environment) { - this.environment = environment; - this.fileBaseUrl = environment.getProperty("fileBaseUrl"); - } - - - public List> fetchCommunities() { - String query = "SELECT id,category_name " + - "FROM social_category_master " + - "WHERE is_active=1 AND is_delete=0 "; - - - return jdbcTemplate.queryForList(query); - } - - - - public List> fetchMaritalStatus() { - String query = "SELECT id,marital_status " + - "FROM marital_status_master " + - "WHERE is_active=1 AND is_delete=0 "; - - - return jdbcTemplate.queryForList(query); - } - - - - public List> fetchEducationStatus() { - String query = "SELECT id,education " + - "FROM education_master " + - "WHERE is_active=1 AND is_delete=0 "; - - - return jdbcTemplate.queryForList(query); - } - - public List> fetchvendingCategory() { - String query = "SELECT id,vending_category_name " + - "FROM vending_category_master " + - "WHERE is_active=1 AND is_delete=0 "; - - - return jdbcTemplate.queryForList(query); - } - - public List> fetchtamilvendingCategory() { - String query = "SELECT id,tamil_vending_category_name " + - "FROM tamil_vending_category_master " + - "WHERE is_active=1 AND is_delete=0 "; - - - return jdbcTemplate.queryForList(query); - } - - -// public List> fetchZones() { -// String query = "SELECT id,zone_name " + -// "FROM zone_master " + -// "WHERE is_active=1 AND is_delete=0 "; -// -// -// return jdbcTemplate.queryForList(query); -// } - -// public List> fetchWardsByZone(int zoneId) { -// String sql = "SELECT id, ward_name FROM ward_master WHERE zone_id = ? "; -// return jdbcTemplate.queryForList(sql, zoneId); -// } - - -// public String saveStreetVendorDetails(String latitude,String longitude,String zone, String ward, String landmark, String vending_district, -// int vending_pincode, int vending_category, String vending_space, boolean pm_svanidhi_loan, -// boolean bank_acc_status, String bankPassbookPath, String streetVendorPhotoPath, String name, -// String f_h_name, String mobile_number, String dob, String gender, int social_category, boolean diff_abled, -// int education_status, int marital_status, int no_of_fam_mem, boolean are_any_fam_mem_invol_str, -// String presentAddress, String present_district, int present_pincode, String rationCardPath, -// String aadharFrontPhotoPath, String aadharBackPhotoPath,String aadharNo) { -// -// -// -// String sql = "INSERT INTO vendor_details (" -// + "latitude,longitude,zone, ward, vending_address,vending_district, vending_pincode, vending_category, vending_space, pm_svanidhi_loan, " -// + "bank_acc_status, bank_passbook, street_vendor_photo, name, f_h_name, mob_no, " -// + "dob,gender,social_category, diff_abled, education_status, marital_status,no_of_fam_mem, " -// + "are_any_fam_mem_invol_str_ven,present_address, present_district, present_pincode, ration_card_photo, aadhar_front_photo, " -// + "aadhar_back_photo,aadhar_no" -// + ") VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"; -// -// KeyHolder keyHolder = new GeneratedKeyHolder(); -// -// try { -// int result = jdbcTemplate.update(connection -> { -// PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" }); -// ps.setString(1, latitude); -// ps.setString(2, longitude); -// ps.setString(3, zone); -// ps.setString(4, ward); -// ps.setString(5, landmark); -// ps.setString(6, vending_district); -// ps.setInt(7, vending_pincode); -// ps.setInt(8, vending_category); -// ps.setString(9, vending_space); -// ps.setBoolean(10, pm_svanidhi_loan); -// ps.setBoolean(11, bank_acc_status); -// ps.setString(12, bankPassbookPath); -// ps.setString(13, streetVendorPhotoPath); -// ps.setString(14, name); -// ps.setString(15, f_h_name); -// ps.setString(16, mobile_number); -// ps.setString(17, dob); -// ps.setString(18, gender); -// ps.setInt(19, social_category); -// ps.setBoolean(20, diff_abled); -// ps.setInt(21, education_status); -// ps.setInt(22, marital_status); -// ps.setInt(23, no_of_fam_mem); -// ps.setBoolean(24, are_any_fam_mem_invol_str); -// ps.setString(25, presentAddress); -// ps.setString(26, present_district); -// ps.setInt(27, present_pincode); -// ps.setString(28, rationCardPath); -// ps.setString(29, aadharFrontPhotoPath); -// ps.setString(30, aadharBackPhotoPath); -// ps.setString(31, aadharNo); -// return ps; -// }, keyHolder); -// //return keyHolder.getKey().intValue(); -// if (result > 0) { -// int generatedId = keyHolder.getKey().intValue(); -// String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); -// String refId = prefix + generatedId; -// -// String updateSql = " UPDATE vendor_details SET vendor_req_id = ? WHERE id = ? "; -// jdbcTemplate.update(updateSql,refId, generatedId); -// return refId; -// } -// //return "error"; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return "error"; -// } - - - public String saveStreetVendorDetails(String latitude,String longitude,String zone, String ward, String landmark, String vending_district, - Integer vending_pincode, Integer vending_category, String vending_space, Boolean pm_svanidhi_loan, - Boolean bank_acc_status, String bankPassbookPath, String streetVendorPhotoPath, String name, - String f_h_name, String mobile_number, String dob, String gender, Integer social_category, Boolean diff_abled, - Integer education_status, Integer marital_status, Integer no_of_fam_mem, Boolean are_any_fam_mem_invol_str, - String presentAddress, String present_district, Integer present_pincode, String rationCardPath, - String aadharFrontPhotoPath, String aadharBackPhotoPath,String aadharNo,String userId,String tamil_name,String tamil_f_h_name,String tamil_landmark, - String tamil_gender,String tamil_present_district,@RequestParam Integer tamilvending_category) { - - int isWeb=1; - String latitudeVal = (latitude != null && !latitude.trim().isEmpty()) ? latitude : null; - String longitudeVal = (longitude != null && !longitude.trim().isEmpty()) ? longitude : null; - String zoneVal = (zone != null && !zone.trim().isEmpty()) ? zone : null; - String wardVal = (ward != null && !ward.trim().isEmpty()) ? ward : null; - String dobVal = (dob != null && !dob.trim().isEmpty()) ? dob : null; - String vendingAddressVal = (landmark != null && !landmark.trim().isEmpty()) ? landmark : null; - - - - String sql = "INSERT INTO vendor_details (" - + "latitude,longitude,zone, ward, vending_address,vending_district, vending_pincode, vending_category, vending_space, pm_svanidhi_loan, " - + "bank_acc_status, bank_passbook, street_vendor_photo, name, f_h_name, mob_no, " - + "dob,gender,social_category, diff_abled, education_status, marital_status,no_of_fam_mem, " - + "are_any_fam_mem_invol_str_ven,present_address, present_district, present_pincode, ration_card_photo, aadhar_front_photo, " - + "aadhar_back_photo,aadhar_no,is_web,cby,tamil_name,tamil_f_h_name,tamil_landmark,tamil_gender,tamil_present_district,tamil_vending_category " - + ") VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - try { - int result = jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" }); - ps.setString(1, latitudeVal); - ps.setString(2, longitudeVal); - ps.setString(3, zoneVal); - ps.setString(4, wardVal); - ps.setString(5, vendingAddressVal); - ps.setString(6, vending_district); - if (vending_pincode != null) ps.setInt(7, vending_pincode); - else ps.setNull(7, java.sql.Types.INTEGER); - - if (vending_category != null) ps.setInt(8, vending_category); - else ps.setNull(8, java.sql.Types.INTEGER); - ps.setString(9, vending_space); - if (pm_svanidhi_loan != null) ps.setBoolean(10, pm_svanidhi_loan); - else ps.setNull(10, java.sql.Types.BOOLEAN); - - if (bank_acc_status != null) ps.setBoolean(11, bank_acc_status); - else ps.setNull(11, java.sql.Types.BOOLEAN); - ps.setString(12, bankPassbookPath); - ps.setString(13, streetVendorPhotoPath); - ps.setString(14, name); - ps.setString(15, f_h_name); - ps.setString(16, mobile_number); - ps.setString(17, dobVal); - ps.setString(18, gender); - if (social_category != null) ps.setInt(19, social_category); - else ps.setNull(19, java.sql.Types.INTEGER); - if (diff_abled != null) ps.setBoolean(20, diff_abled); - else ps.setNull(20, java.sql.Types.BOOLEAN); - if (education_status != null) ps.setInt(21, education_status); - else ps.setNull(21, java.sql.Types.INTEGER); - - if (marital_status != null) ps.setInt(22, marital_status); - else ps.setNull(22, java.sql.Types.INTEGER); - - if (no_of_fam_mem != null) ps.setInt(23, no_of_fam_mem); - else ps.setNull(23, java.sql.Types.INTEGER); - if (are_any_fam_mem_invol_str != null) ps.setBoolean(24, are_any_fam_mem_invol_str); - else ps.setNull(24, java.sql.Types.BOOLEAN); - ps.setString(25, presentAddress); - ps.setString(26, present_district); - if (present_pincode != null) ps.setInt(27, present_pincode); - else ps.setNull(27, java.sql.Types.INTEGER); - ps.setString(28, rationCardPath); - ps.setString(29, aadharFrontPhotoPath); - ps.setString(30, aadharBackPhotoPath); - ps.setString(31, aadharNo); - ps.setInt(32, isWeb); - ps.setString(33, userId); - ps.setString(34, tamil_name); - ps.setString(35, tamil_f_h_name); - ps.setString(36, tamil_landmark); - ps.setString(37, tamil_gender); - ps.setString(38, tamil_present_district); - if (tamilvending_category != null) ps.setInt(39, tamilvending_category); - else ps.setNull(39, java.sql.Types.INTEGER); - return ps; - }, keyHolder); - //return keyHolder.getKey().intValue(); - if (result > 0) { - int generatedId = keyHolder.getKey().intValue(); - String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); - String refId = prefix + generatedId; - - String updateSql = " UPDATE vendor_details SET vendor_req_id = ? WHERE id = ? "; - jdbcTemplate.update(updateSql,refId, generatedId); - return refId; - } - //return "error"; - } catch (Exception e) { - e.printStackTrace(); - } - return "error"; - } - - - - - public String fileUpload(MultipartFile file, String name) { - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory.mobile"); - String serviceFolderName = environment.getProperty("street_vendor_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 + "_" + 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); - */ - - Files.write(path, bytes); - - //System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - - 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 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(); - } - - - - - public boolean isMobileRegistered(String mobilenumber) { - String sql = "SELECT COUNT(*) FROM vendor_details WHERE mob_no = ?"; - Integer count = jdbcTemplate.queryForObject(sql, new Object[]{mobilenumber}, Integer.class); - return count != null && count > 0; - } - - public Integer findLatestVendorIdByMobile(String mobile) { - String sql = "SELECT id FROM vendor_details WHERE mob_no = ? ORDER BY id DESC LIMIT 1"; - - try { - return jdbcTemplate.queryForObject(sql, new Object[]{mobile}, Integer.class); - } catch (Exception e) { - return null; // mobile not registered - } - } - - - public List> getCommiteeDetailsWeb(String cby) { - String sql = "SELECT * " - + "FROM vendor_details " - + "WHERE is_web=1 AND cby=?"; - return jdbcTemplate.queryForList(sql, cby); - - } - - - public List> getwebVendorDetailsByReqId(String requestId) { - - String sql="SELECT vd.*,em.education as education_name,mm.marital_status as marital_name,scm.category_name as category_name,vcm.vending_category_name as vending_category_name, "+ - "CONCAT(vd.present_address,',',vd.present_district) as residental_address, CONCAT(vd.vending_address,',',vending_district) as business_address, "+ - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', vd.bank_passbook) AS view_bank_passbook, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', vd.ration_card_photo) AS view_ration_card_photo, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', vd.street_vendor_photo) AS view_street_vendor_photo, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', vd.aadhar_front_photo) AS view_aadhar_front_photo, " + - "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', vd.aadhar_back_photo) AS view_aadhar_back_photo " - + "FROM vendor_details vd " - + "LEFT JOIN social_category_master scm on vd.social_category = scm.id " - + "LEFT JOIN vending_category_master vcm ON vd.vending_category=vcm.id " - + "LEFT JOIN education_master em on vd.education_status = em.id " - + "LEFT JOIN marital_status_master mm on vd.marital_status = mm.id " - + "WHERE vd.vendor_req_id = ?"; - - return jdbcTemplate.queryForList(sql,requestId); - } - - - public String updateStreetVendorDetailsWeb(String latitude, String longitude, String zone, String ward, - String landmark, String vending_district, Integer vending_pincode, Integer vending_category, - String vending_space, Boolean pm_svanidhi_loan, Boolean bank_acc_status, String bankPassbookPath, - String streetVendorPhotoPath, String name, String f_h_name, String mobile_number, String dob, String gender, - Integer social_category, Boolean diff_abled, Integer education_status, Integer marital_status, - Integer no_of_fam_mem, Boolean are_any_fam_mem_invol_str, String presentAddress, String present_district, - Integer present_pincode, String rationCardPath, String aadharFrontPhotoPath, String aadharBackPhotoPath, - String aadharNo,String tamil_name,String tamil_f_h_name, String tamil_landmark,String tamil_gender,String tamil_present_district,Integer tamilvending_category, String userId, String vendor_req_id) { - - - String latitudeVal = (latitude != null && !latitude.trim().isEmpty()) ? latitude : null; - String longitudeVal = (longitude != null && !longitude.trim().isEmpty()) ? longitude : null; - String zoneVal = (zone != null && !zone.trim().isEmpty()) ? zone : null; - String wardVal = (ward != null && !ward.trim().isEmpty()) ? ward : null; - String dobVal = (dob != null && !dob.trim().isEmpty()) ? dob : null; - String vendingAddressVal = (landmark != null && !landmark.trim().isEmpty()) ? landmark : null; - - String sql="UPDATE vendor_details SET " - + "latitude =?,longitude=?,zone=?, ward=?, vending_address=?,vending_district=?, vending_pincode=?, vending_category=?, vending_space=?, pm_svanidhi_loan=?, " - + "bank_acc_status=?, bank_passbook=?, street_vendor_photo=?, name=?, f_h_name=?, mob_no=?, " - + "dob=?,gender=?,social_category=?, diff_abled=?, education_status=?, marital_status=?,no_of_fam_mem=?, " - + "are_any_fam_mem_invol_str_ven=?,present_address=?, present_district=?, present_pincode=?, ration_card_photo=?, aadhar_front_photo=?, " - + "aadhar_back_photo=?,aadhar_no=?,updated_date=NOW(),tamil_name=?,tamil_f_h_name=?,tamil_landmark=?,tamil_gender=?,tamil_present_district=?,tamil_vending_category=?,edit_by=? " - + " WHERE vendor_req_id = ? AND editable=1"; - - //AND is_web=1 - try { - int rows=jdbcTemplate.update(sql, latitudeVal, longitudeVal, zoneVal, wardVal, vendingAddressVal, vending_district, - vending_pincode, vending_category, vending_space, pm_svanidhi_loan, bank_acc_status, bankPassbookPath, - streetVendorPhotoPath, name, f_h_name, mobile_number, dobVal, gender, social_category, diff_abled, - education_status, marital_status, no_of_fam_mem, are_any_fam_mem_invol_str, presentAddress, - present_district, present_pincode, rationCardPath, aadharFrontPhotoPath, aadharBackPhotoPath, aadharNo, - tamil_name,tamil_f_h_name,tamil_landmark,tamil_gender,tamil_present_district,tamilvending_category,userId, - vendor_req_id); - - if (rows==1) { - return "Success"; - } - else { - return "Error"; - } - } - catch (Exception e) { - e.printStackTrace(); - } - return "Error"; - } - - - public String logEntry(String userId, String vendor_req_id) { - String sql="INSERT INTO vendor_details_web_log (name,f_h_name,gender,dob,social_category,diff_abled,mob_no,aadhar_no,present_address,present_district,present_pincode,vending_address,vending_district,vending_pincode,vending_category,vending_space,bank_acc_status,bank_passbook,ration_card_photo,street_vendor_photo,aadhar_front_photo,aadhar_back_photo,zone,ward,pm_svanidhi_loan,vendor_req_id,education_status,marital_status,no_of_fam_mem,are_any_fam_mem_invol_str_ven,latitude,longitude,tamil_name,tamil_f_h_name,tamil_landmark,tamil_gender,tamil_present_district,tamil_vending_category,cby) " - + " SELECT name,f_h_name,gender,dob,social_category,diff_abled,mob_no,aadhar_no,present_address,present_district,present_pincode,vending_address,vending_district,vending_pincode,vending_category,vending_space,bank_acc_status,bank_passbook,ration_card_photo,street_vendor_photo,aadhar_front_photo,aadhar_back_photo,zone,ward,pm_svanidhi_loan,vendor_req_id,education_status,marital_status,no_of_fam_mem,are_any_fam_mem_invol_str_ven,latitude,longitude,tamil_name,tamil_f_h_name,tamil_landmark,tamil_gender,tamil_present_district,tamil_vending_category,? FROM vendor_details WHERE vendor_req_id=?"; - - try { - jdbcTemplate.update(sql, userId,vendor_req_id); - return "success"; - - } catch (DataAccessException e) { - e.printStackTrace(); - return "failure"; - - } - } - - public String getloginUserZone(int userId) { - String query = "select zone from web_login where gcc_user_id = ?"; - try { - // Use queryForObject to return a single value - return jdbcTemplate.queryForObject(query, String.class, userId); - } catch (EmptyResultDataAccessException e) { - // Log the issue and handle the case when no result is found - System.out.println("No zone found for user ID: " + userId); - return null; // Or return a default value if required - } - } - - - public List> vendingDetailsbyZoneWeb(String zone) { - String sql = "SELECT * " - + "FROM vendor_details " - + "WHERE zone=?"; - return jdbcTemplate.queryForList(sql, zone); - } - - public List> getvedingcommitteelist(String date, String zones) { - - // Convert "01,02,03" → ["01","02","03"] (trim spaces safely) - List zoneList = Arrays.stream(zones.split(",")) - .map(String::trim) - .collect(Collectors.toList()); - - // Create ?,?,? placeholders - String zonePlaceholders = String.join(",", Collections.nCopies(zoneList.size(), "?")); - - String sql = "SELECT vd.id, vd.vendor_req_id, vd.name, vd.mob_no, " + - "CONCAT_WS(', ', vd.vending_address, vd.vending_district, vd.vending_pincode) AS vending_address, " + - "vd.zone, vd.ward, CONCAT_WS('- ', vd.zone, vd.ward) AS zoneward " + - "FROM vendor_details vd " + - "JOIN vendor_approval_level_3 va3 ON vd.id = va3.vdid " + - "WHERE va3.status='Approved' " + - "AND DATE(va3.cdate) <= STR_TO_DATE(?, '%d-%m-%Y') " + - "AND vd.zone IN (" + zonePlaceholders + ") " - + " ORDER BY vd.zone,vd.ward"; - - List params = new ArrayList<>(); - params.add(date); - params.addAll(zoneList); - - try { - return jdbcTemplate.queryForList(sql, params.toArray()); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - - - public List> vendorDetailsById(String requestId) { - - String sql = "SELECT vd.id,vd.vendor_req_id, vd.name, vd.mob_no, vd.dob, vd.gender, vd.diff_abled, vd.f_h_name, scm.category_name, " + - "CONCAT_WS(', ', vd.present_address, vd.present_district, vd.present_pincode) AS residental_address, " + - "CONCAT_WS(', ', vd.vending_address, vd.vending_district, vd.vending_pincode) AS business_address, vd.bank_acc_status, " + - "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.bank_passbook),'') as bank_passbook, " + - "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.ration_card_photo),'') as ration_card_photo, " + - "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.street_vendor_photo),'') as street_vendor_photo, " + - "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.aadhar_front_photo),'') as aadhar_front_photo, " + - "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.aadhar_back_photo),'') as aadhar_back_photo, " + - "vcm.vending_category_name, vd.vending_space, vd.pm_svanidhi_loan, vd.zone, vd.ward, " + - "ifnull(vtym.vending_type_name,'N/A') as vendor_type,ifnull(vstym.vending_sub_type_name,'N/A') as vendor_sub_type, ifnull(va1.vendor_id_card,'N/A') as vendor_id_card, ifnull(va1.vending_nature,'N/A') as vending_nature, " + - "ifnull(vtm.vending_time,'N/A') as vending_time, ifnull(tmm.transaction_mode,'N/A') as transaction_mode, ifnull(va1.swanidi_loan_amount,0) as swanidi_loan_amount, " + - "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',va1.vendor_space_photo),'') as vendor_space_photo, " + - "va1.status as LI_Status, va1.remarks as LI_Remarks, DATE_FORMAT(va1.cdate, '%d-%m-%Y %l:%i %p') as LI_Cdate, " + - "va2.status as ARO_status, ifnull(va2.remarks,'') as ARO_remarks, DATE_FORMAT(va2.cdate, '%d-%m-%Y %l:%i %p') as ARO_Inspection_date, "+ - "va3.status as EE_status, ifnull(va3.remarks,'') as EE_remarks, DATE_FORMAT(va3.cdate, '%d-%m-%Y %l:%i %p') as EE_Inspection_date "+ - "FROM vendor_details vd " + - "LEFT JOIN vendor_approval_level_3 va3 ON va3.vdid = vd.id " + - "LEFT JOIN vendor_approval_level_1 va1 on va3.vdid = va1.vdid " + - "LEFT JOIN vendor_approval_level_2 va2 on va3.vdid = va2.vdid " + - "LEFT JOIN education_master em on em.id= vd.education_status " + - "LEFT JOIN marital_status_master msm on msm.id= vd.marital_status " + - "LEFT JOIN social_category_master scm on vd.social_category = scm.id " + - "LEFT JOIN vending_category_master vcm ON vd.vending_category=vcm.id " + - "LEFT JOIN vending_time_master vtm on va1.vendor_timing_id = vtm.id " + - "LEFT JOIN transaction_mode_master tmm on va1.transaction_mode_id = tmm.id " + - "LEFT JOIN vending_type_master vtym ON va1.vendor_type = vtym.typeid " + - "LEFT JOIN vending_sub_type_master vstym ON va1.vendor_sub_type = vstym.subtypeid " + - "WHERE vd.id = ? "; - - return jdbcTemplate.queryForList(sql, requestId); - } - - - public List> getdataforreport(String zone, String ward) { - - StringBuilder sql = new StringBuilder( - "SELECT vd.id, vd.vendor_req_id, vd.zone, vd.ward, vd.name, vd.mob_no " + - "FROM vendor_details vd " + - "JOIN vendor_approval_level_3 va3 ON va3.vdid = vd.id " + - "WHERE vd.isactive = 1" - ); - - List params = new ArrayList<>(); - - // Add zone if not empty - if (zone != null && !zone.trim().isEmpty()) { - sql.append(" AND vd.zone = ?"); - params.add(zone); - } - - // Add ward if not empty - if (ward != null && !ward.trim().isEmpty()) { - sql.append(" AND vd.ward = ?"); - params.add(ward); - } - - try { - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - - - public List> ViewWardDropdown(String zone) { - String sql = "SELECT ward_name " - + "FROM ward_master " - + "WHERE is_active=1 AND is_delete=0 AND zone_id=?"; - try { - return jdbcTemplate.queryForList(sql,zone); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - } - - - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/createventService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/createventService.java deleted file mode 100644 index 2b8056fc..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vendor/service/createventService.java +++ /dev/null @@ -1,729 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vendor.service; - -import java.net.HttpURLConnection; -import java.net.URL; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -public class createventService { - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlVendingCommitteDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Autowired - public StreetVendorService streetVendorService; - - // public boolean isFileExists(String originalFilename) { - // String sql = "SELECT COUNT(*) FROM create_event " + - // "WHERE file_url LIKE ?"; - // String filenamePattern = "%" + originalFilename; // Match filename at the end - // of the path - // Integer count = jdbcTemplate.queryForObject(sql, Integer.class, - // filenamePattern); - // return count != null && count > 0; - // } - - public String insertEvent(String eventName, LocalDate eventDate, String fileUrl, String cby) { - String sql = "INSERT INTO create_event (event_name, event_date, file_url,cby) VALUES (?, ?, ?,?)"; - try { - jdbcTemplate.update(sql, eventName, eventDate, fileUrl, cby); - return "success"; - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - } - return "error"; - } - - // SELECT * FROM vendingcommitte.create_event - public List> ViewDropdownEvent(String userId) { - String sql = "SELECT * FROM create_event WHERE cby=? AND isactive=1 AND isdelete=0 "; - return jdbcTemplate.queryForList(sql, userId); - } - - public List> ViewCommitteeDropdownEvent(String userId) { - String sql = "SELECT req_id,event_name,event_date,DATE_FORMAT(event_date, '%d-%m-%Y') as formated_date " - + "FROM create_event " - + "WHERE isactive=1 AND isdelete=0 AND cby=?"; - try { - return jdbcTemplate.queryForList(sql, userId); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - return Collections.emptyList(); - } - - } - - @Transactional - public ResponseEntity> saveVendorDetails(Map payload) { - - Map response = new HashMap<>(); - - int vendor_req_id = Integer.parseInt(payload.get("vendor_req_id").toString()); - String status = payload.get("status").toString(); - String remarks = payload.get("remarks") == null ? "-" : payload.get("remarks").toString(); - int event_req_id = Integer.parseInt(payload.get("event_req_id").toString()); - String vendor_req_number = payload.get("vendor_req_number").toString(); - String zone = payload.get("zone").toString(); - String ward = payload.get("ward").toString(); - String cby = payload.get("cby").toString(); - String mob_no = payload.get("mob_no").toString(); - - try { - - /* - * ============================================================ - * CHECK IF vendor is already inside vendor_postponed_list - * ============================================================ - */ - String checkPostponedSQL = "SELECT * FROM vendor_postponed_list WHERE vdid=? AND isactive=1"; - List> existingPostponed = jdbcTemplate.queryForList(checkPostponedSQL, vendor_req_id); - - /* - * ============================================================ - * BACKUP METHOD: insert into postponed_history_log - * ============================================================ - */ - if (!existingPostponed.isEmpty()) { - - String backupSQL = "INSERT INTO postponed_history_log " - + "(vdid, event_req_id, status, remarks, cby, cdate, updated_by, updated_date, isactive, isdelete) " - + "SELECT vdid, event_req_id, status, remarks, cby, cdate, updated_by, updated_date, isactive, isdelete " - + "FROM vendor_postponed_list WHERE vdid=?"; - - jdbcTemplate.update(backupSQL, vendor_req_id); - } - - /* - * ============================================================ - * CASE 1: POSTPONED - * ============================================================ - */ - if ("Postponed".equalsIgnoreCase(status)) { - - if (existingPostponed.isEmpty()) { - - // INSERT new postponed entry - String insertSQL = "INSERT INTO vendor_postponed_list " - + "(vdid, status, remarks, event_req_id, cby) VALUES (?,?,?,?,?)"; - - jdbcTemplate.update(insertSQL, vendor_req_id, status, remarks, event_req_id, cby); - - } else { - - // UPDATE postponed entry - String updateSQL = "UPDATE vendor_postponed_list " - + "SET status=?, remarks=?, event_req_id=?, updated_by=?, updated_date=NOW() " - + "WHERE vdid=?"; - - jdbcTemplate.update(updateSQL, status, remarks, event_req_id, cby, vendor_req_id); - } - - response.put("status", "success"); - response.put("message", "Details saved successfully!"); - - return ResponseEntity.ok(response); - } - - /* - * ============================================================ - * CASE 2: APPROVED / REJECTED → Insert into vendor_request_list - * ============================================================ - */ - - String insertRequestSQL = "INSERT INTO vendor_request_list " - + "(vdid, status, remarks, event_req_id, cby) VALUES (?, ?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertRequestSQL, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, vendor_req_id); - ps.setString(2, status); - ps.setString(3, remarks); - ps.setInt(4, event_req_id); - ps.setString(5, cby); - return ps; - }, keyHolder); - - int generatedId = keyHolder.getKey().intValue(); - - /* - * ============================================================ - * Assign UID only for APPROVED - * ============================================================ - */ - if ("Approved".equalsIgnoreCase(status)) { - String currentYear = java.time.Year.now().toString(); - String uid_no = zone + "_" + ward + "_" + currentYear + "_" + generatedId; - - jdbcTemplate.update("UPDATE vendor_request_list SET uid_no=? WHERE id=?", uid_no, generatedId); - } - - /* - * ============================================================ - * If POSTPONED ENTRY already exists → update it (after backup) - * ============================================================ - */ - if (!existingPostponed.isEmpty()) { - - String updSQL = "UPDATE vendor_postponed_list SET " - + "status=?, remarks=?, event_req_id=?, updated_by=?, updated_date=NOW(),isactive=0,isdelete=1 " - + "WHERE vdid=?"; - - jdbcTemplate.update(updSQL, status, remarks, event_req_id, cby, vendor_req_id); - } - - /* - * ============================================================ - * Send WhatsApp notification - * ============================================================ - */ - String result = sendWhatsappMsg(mob_no, status, vendor_req_number); - - response.put("status", "success"); - response.put("message", result.equals("200") - ? "Details submitted successfully!" - : "Details submitted, but WhatsApp msg failed."); - - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Error saving vendor details: " + e.getMessage())); - } - } - - private String sendWhatsappMsg(String mob_no, String status, String vendor_req_number) { - String urlString = ""; - - if ("Approved".equals(status)) { - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" - + mob_no - + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=You+are+recognized+as+a+roadside+vendor.+Registration+number%3A+" - + vendor_req_number + ".&isTemplate=true&footer=GCC+-+IT+Cell"; - } else { - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" - + mob_no - + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+application+is+rejected+because+your+roadside+vendor+details+are+incorrect.+%0A%0ARegistration+Number%3A+" - + vendor_req_number + "."; - } - - String res = hitURL(urlString); - return res; - } - - private String hitURL(String urlString) { - String response = ""; - try { - URL url = new URL(urlString); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = String.valueOf(responseCode); - System.out.println("Response Code for URL: " + urlString + " is " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("response=" + response); - return response; - } - - public List> getCommiteeDetails(String event_req_id) { - String sql = "SELECT * " - + "FROM vendor_request_list " - + "WHERE event_req_id=? "; - return jdbcTemplate.queryForList(sql, event_req_id); - } - - public List removeSavedVendorDetails() { - - String sql = "SELECT request_no FROM vendor_request_list"; - - return jdbcTemplate.queryForList(sql, String.class); - } - - // @Transactional - // public ResponseEntity> saveBulkVendorDetails(Map payload) { - // - // Map response = new HashMap<>(); - // - // try { - // - // String status = payload.get("status").toString(); - // String remarks = payload.get("remarks").toString(); - // int eventReqId = Integer.parseInt(payload.get("event_req_id").toString()); - // String cby = payload.get("cby").toString(); - // - // List> vendorList = - // (List>) payload.get("vendorList"); - // - // if (vendorList == null || vendorList.isEmpty()) { - // return ResponseEntity.badRequest() - // .body(Map.of("status", "Error", "message", "No vendor records provided")); - // } - // - // String insertSQL = "INSERT INTO vendor_request_list " + - // "(vdid, status, remarks, event_req_id, uid_no, cby) VALUES (?, ?, ?, ?, '', - // ?)"; - // - // try { - // jdbcTemplate.batchUpdate(insertSQL, vendorList, vendorList.size(), - // (ps, vendor) -> { - // ps.setInt(1, Integer.parseInt(vendor.get("vendor_req_id").toString())); - // ps.setString(2, status); - // ps.setString(3, remarks); - // ps.setInt(4, eventReqId); - // ps.setString(5, cby); - // } - // ); - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of("status", "Error", "message", "Batch insert failed: " + - // e.getMessage())); - // } - // - // - // - // List> insertedIds; - // try { - // insertedIds = jdbcTemplate.queryForList( - // "SELECT id, vdid FROM vendor_request_list ORDER BY id DESC LIMIT ?", - // vendorList.size()); - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of("status", "Error", "message", "Failed to fetch inserted IDs: " + - // e.getMessage())); - // } - // - // - // List updateParams = new ArrayList<>(); - // int currentYear = java.time.Year.now().getValue(); - // - // for (int i = 0; i < vendorList.size(); i++) { - // - // Map vendor = vendorList.get(i); - // Map inserted = insertedIds.get(i); - // - // int insertedId = (int) inserted.get("id"); - // String zone = vendor.get("zone").toString(); - // String ward = vendor.get("ward").toString(); - // - // // Assign UID only if Approved - // if ("Approved".equalsIgnoreCase(status)) { - // String uidNo = zone + "_" + ward + "_" + currentYear + "_" + insertedId; - // updateParams.add(new Object[]{uidNo, insertedId}); - // } - // - // // Send WhatsApp for Approved/Rejected - // try { - // if ("Approved".equalsIgnoreCase(status) || - // "Rejected".equalsIgnoreCase(status)) { - // sendWhatsappMsg( - // vendor.get("mob_no").toString(), - // status, - // vendor.get("vendor_req_number").toString() - // ); - // } - // } catch (Exception e) { - // // WhatsApp failure should NOT stop DB operation - // e.printStackTrace(); - // } - // } - // - // if (!updateParams.isEmpty()) { - // try { - // jdbcTemplate.batchUpdate("UPDATE vendor_request_list SET uid_no=? WHERE - // id=?", updateParams); - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of("status", "Error", "message", "Failed to update UID numbers: " + - // e.getMessage())); - // } - // } - // - // response.put("status", "success"); - // response.put("message", "Details submitted successfully!"); - // - // return ResponseEntity.ok(response); - // - // } catch (Exception e) { - // e.printStackTrace(); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - // .body(Map.of("status", "Error", "message", "Unexpected error: " + - // e.getMessage())); - // } - // } - - @Transactional - public ResponseEntity> saveBulkVendorDetails(Map payload) { - - Map response = new HashMap<>(); - - try { - String status = payload.get("status").toString(); - String remarks = payload.get("remarks").toString(); - int eventReqId = Integer.parseInt(payload.get("event_req_id").toString()); - String cby = payload.get("cby").toString(); - - List> vendorList = (List>) payload.get("vendorList"); - - if (vendorList == null || vendorList.isEmpty()) { - return ResponseEntity.badRequest() - .body(Map.of("status", "Error", "message", "No vendor records provided")); - } - - int currentYear = java.time.Year.now().getValue(); - - /* - * ============================================================ - * PROCESS EACH VENDOR ONE BY ONE - * ============================================================ - */ - for (Map vendor : vendorList) { - - int vendorReqId = Integer.parseInt(vendor.get("vendor_req_id").toString()); - String zone = vendor.get("zone").toString(); - String ward = vendor.get("ward").toString(); - String mob_no = vendor.get("mob_no").toString(); - String vendor_req_number = vendor.get("vendor_req_number").toString(); - - /* - * ============================================================ - * STEP 1: Check if vendor already exists in postponed list - * ============================================================ - */ - String checkSQL = "SELECT * FROM vendor_postponed_list WHERE vdid=? AND isactive=1"; - List> existingPostponed = jdbcTemplate.queryForList(checkSQL, vendorReqId); - - boolean postponedExists = !existingPostponed.isEmpty(); - - /* - * ============================================================ - * STEP 2: BACKUP OLD POSTPONED ROW → postponed_history_log - * ============================================================ - */ - if (postponedExists) { - String backupSQL = "INSERT INTO postponed_history_log " - + "(vdid, event_req_id, status, remarks, cby, cdate, updated_by, updated_date, isactive, isdelete) " - + "SELECT vdid, event_req_id, status, remarks, cby, cdate, updated_by, updated_date, isactive, isdelete " - + "FROM vendor_postponed_list WHERE vdid=?"; - - jdbcTemplate.update(backupSQL, vendorReqId); - } - - /* - * ============================================================ - * CASE 1: STATUS = POSTPONED - * ============================================================ - */ - if ("Postponed".equalsIgnoreCase(status)) { - - if (!postponedExists) { - // INSERT NEW POSTPONED ROW - String insertPostSQL = "INSERT INTO vendor_postponed_list (vdid, status, remarks, event_req_id, cby) " - + - "VALUES (?, ?, ?, ?, ?)"; - - jdbcTemplate.update(insertPostSQL, vendorReqId, status, remarks, eventReqId, cby); - - } else { - // UPDATE EXISTING POSTPONED ROW - String updatePostSQL = "UPDATE vendor_postponed_list SET status=?, remarks=?, event_req_id=?, updated_by=?, updated_date=NOW() " - + - "WHERE vdid=?"; - - jdbcTemplate.update(updatePostSQL, status, remarks, eventReqId, cby, vendorReqId); - } - - continue; // SKIP REQUEST LIST INSERTION - } - - /* - * ============================================================ - * CASE 2: APPROVED / REJECTED → INSERT INTO vendor_request_list - * ============================================================ - */ - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - String insertReqSQL = "INSERT INTO vendor_request_list (vdid, status, remarks, event_req_id, cby) " + - "VALUES (?, ?, ?, ?, ?)"; - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(insertReqSQL, Statement.RETURN_GENERATED_KEYS); - ps.setInt(1, vendorReqId); - ps.setString(2, status); - ps.setString(3, remarks); - ps.setInt(4, eventReqId); - ps.setString(5, cby); - return ps; - }, keyHolder); - - int generatedId = keyHolder.getKey().intValue(); - - /* - * ============================================================ - * UID GENERATION FOR APPROVED - * ============================================================ - */ - if ("Approved".equalsIgnoreCase(status)) { - - String uidNo = zone + "_" + ward + "_" + currentYear + "_" + generatedId; - - jdbcTemplate.update( - "UPDATE vendor_request_list SET uid_no=? WHERE id=?", - uidNo, generatedId); - } - - /* - * ============================================================ - * UPDATE POSTPONED LIST ALSO IF VENDOR EXISTS (AFTER BACKUP) - * ============================================================ - */ - if (postponedExists) { - String updatePostSQL = "UPDATE vendor_postponed_list SET status=?, remarks=?, event_req_id=?, updated_by=?, updated_date=NOW(),isactive=0,isdelete=1 " - + - "WHERE vdid=?"; - - jdbcTemplate.update(updatePostSQL, status, remarks, eventReqId, cby, vendorReqId); - } - - /* - * ============================================================ - * SEND WHATSAPP (NON-BLOCKING) - * ============================================================ - */ - try { - if ("Approved".equalsIgnoreCase(status) || "Rejected".equalsIgnoreCase(status)) { - sendWhatsappMsg(mob_no, status, vendor_req_number); - } - } catch (Exception e) { - e.printStackTrace(); // Should not stop DB save - } - } - - /* - * ============================================================ - * SUCCESS RESPONSE - * ============================================================ - */ - response.put("status", "success"); - response.put("message", "Vendor details submitted successfully!"); - - return ResponseEntity.ok(response); - - } catch (Exception e) { - e.printStackTrace(); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("status", "Error", "message", "Unexpected error: " + e.getMessage())); - } - } - - public List> getsavedids() { - String sql = "SELECT vdid FROM vendor_request_list WHERE isactive=1"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - - return Collections.emptyList(); - } - - } - - public List> getPostponedList() { - String sql = "SELECT * FROM vendor_postponed_list WHERE isactive=1 AND isdelete=0"; - try { - return jdbcTemplate.queryForList(sql); - } catch (Exception e) { - return Collections.emptyList(); - } - } - - public List> getdataforreport(String meeting, String status, String cby) { - - StringBuilder sql = new StringBuilder( - "SELECT * FROM (" + - " SELECT vdid, status, remarks, uid_no, event_req_id, cdate,cby " + - " FROM vendor_request_list " + - " UNION ALL " + - " SELECT vdid, status, remarks, NULL AS uid_no, event_req_id, cdate,cby " + - " FROM vendor_postponed_list " + - ") AS all_requests WHERE 1=1"); - - List params = new ArrayList<>(); - - try { - - // Filter by Meeting ID - if (meeting != null && !meeting.trim().isEmpty()) { - sql.append(" AND event_req_id = ?"); - params.add(Integer.parseInt(meeting)); - } - - // Filter by status (Approved / Rejected / Postponed) - if (status != null && !status.trim().isEmpty()) { - sql.append(" AND status = ?"); - params.add(status); - } - - sql.append(" AND cby = ?"); - params.add(Integer.parseInt(cby)); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public List> finalvendorDetailsById(String requestId) { - - // Base vendor details (1 row) - List> org_list = streetVendorService.vendorDetailsById(requestId); - - if (org_list.isEmpty()) { - return Collections.emptyList(); - } - - Map base = org_list.get(0); - - // Get full request history (multiple rows) - List> historyList = getvendingfinaldata(requestId); - - // Merge base vendor details into every history record - List> output = new ArrayList<>(); - - for (Map h : historyList) { - Map merged = new HashMap<>(base); - merged.putAll(h); // add status/history into same row - output.add(merged); - } - - return output; - } - - private List> getvendingfinaldata(String requestId) { - - String sql = "SELECT all_logs.vdid, " + - " all_logs.vc_status, " + - " all_logs.vc_remarks, " + - " CONCAT_WS('- ', ce.event_name, DATE_FORMAT(ce.event_date, '%d-%m-%Y')) AS event_name, " + - " DATE_FORMAT(all_logs.cdate, '%d-%m-%Y %l:%i %p') AS vc_Inspection_date " + - "FROM (" + - - " SELECT vrl.vdid, vrl.status AS vc_status, vrl.remarks AS vc_remarks, " + - " vrl.event_req_id, vrl.cdate " + - " FROM vendor_request_list vrl " + - " WHERE vrl.vdid = ? AND vrl.isactive = 1 " + - - " UNION ALL " + - - " SELECT vpl.vdid, vpl.status AS vc_status, vpl.remarks AS vc_remarks, " + - " vpl.event_req_id, vpl.cdate " + - " FROM vendor_postponed_list vpl " + - " WHERE vpl.vdid = ? AND vpl.isactive = 1 " + - - " UNION ALL " + - - " SELECT phl.vdid, phl.status AS vc_status, phl.remarks AS vc_remarks, " + - " phl.event_req_id, phl.cdate " + - " FROM postponed_history_log phl " + - " WHERE phl.vdid = ? " + - - ") AS all_logs " + - - "LEFT JOIN create_event ce ON ce.req_id = all_logs.event_req_id " + - - "ORDER BY all_logs.cdate ASC"; - - try { - return jdbcTemplate.queryForList(sql, requestId, requestId, requestId); - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } - - public Map getLatestPostponed(String vdid) { - - String sql = "SELECT status, remarks, DATE_FORMAT(cdate, '%d-%m-%Y %l:%i %p') AS date " + - "FROM vendor_postponed_list WHERE vdid = ? ORDER BY cdate DESC LIMIT 1"; - - List> list = jdbcTemplate.queryForList(sql, vdid); - - return list.isEmpty() ? null : list.get(0); - } - - public List> getPostponedHistory(String vdid) { - - String sql = "SELECT status, remarks, DATE_FORMAT(cdate, '%d-%m-%Y %l:%i %p') AS date " + - "FROM postponed_history_log WHERE vdid = ? ORDER BY cdate DESC"; - - return jdbcTemplate.queryForList(sql, vdid); - } - - public Map checkVendorInVendingTables(Integer vdid) { - - Map result = new HashMap<>(); - - // 1. Check postponed table - String sqlPostponed = "SELECT COUNT(*) FROM vendor_postponed_list WHERE vdid=? AND isactive=1"; - Integer postponed = jdbcTemplate.queryForObject(sqlPostponed, Integer.class, vdid); - if (postponed != null && postponed > 0) { - result.put("status", "POSTPONED"); - return result; - } - - // 2. Check vendor_request_list (latest status) - String sqlRequest = "SELECT status FROM vendor_request_list WHERE vdid=? AND isactive=1 ORDER BY id DESC LIMIT 1"; - - List> reqList = jdbcTemplate.queryForList(sqlRequest, vdid); - if (reqList.isEmpty()) { - result.put("status", "NO_EVENT"); - return result; - } - - String status = reqList.get(0).get("status").toString(); - result.put("status", status); - - return result; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/.DS_Store deleted file mode 100644 index 005c9d2f..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/MainController.java deleted file mode 100644 index 5fa1bb07..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/MainController.java +++ /dev/null @@ -1,38 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vtrack.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; -import java.util.List; -import java.util.Map; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.vtrack.service.VehicleService; - -@RequestMapping("/gcc/vtrack") -@Controller("vTrackController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/vtrack/"; - - @Autowired - public VehicleService vehicleService; - - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @GetMapping({"/","/index","/messagelist"}) - public String messagelist(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - List> VehicleLists=vehicleService.getAllSavedMessages(); - model.addAttribute("VehicleLists", VehicleLists); - return BasePath+"messagelist"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/VehicleApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/VehicleApiController.java deleted file mode 100644 index 047367b6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/VehicleApiController.java +++ /dev/null @@ -1,93 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vtrack.controller; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.ui.Model; -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 antlr.collections.impl.Vector; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.vtrack.service.VehicleService; - -@RestController -@RequestMapping("/gcc/api/vtrack") -public class VehicleApiController { - @Autowired - public VehicleService vehicleService; - - @GetMapping("/getTemplateDetails") - public ResponseEntity>> getTemplateDetails() { - try { - List> templateNames = vehicleService.getAllTemplateNames(); - - if (templateNames == null || templateNames.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(Collections.emptyList()); - } - - return ResponseEntity.ok(templateNames); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); - } - } - - @PostMapping("/saveMessageDetails") - public String saveMessageDetails(@RequestParam("date") String date, @RequestParam("image") MultipartFile image, - @RequestParam("templateType") String tempType) throws IOException { - - String img_path = vehicleService.fileUpload("vtrack", tempType, image); - - int result = vehicleService.saveMessageDetails(date, tempType, img_path); - - if (result > 0) { - return "success"; - } - return "Failed"; - - } - - @GetMapping({ "/sendmessage" }) - public String sendmessage( - @RequestParam(value = "msgid", required = true) String msgid, - @RequestParam(value = "datetxt", required = false) String datetxt, - @RequestParam(value = "fileurl", required = false) String fileurl) { - - String LoginUserId = LoginUserInfo.getLoginUserId(); - - return vehicleService.sendMessage(msgid, datetxt, fileurl); - } - - @PostMapping("/disablemessage") - public String disablemessage(@RequestParam(value = "msgId", required = true) String msgid) { - String status = vehicleService.disablemessage(msgid); - - if (status.equals("success")) { - return "success"; - } else { - return "Failed to update"; - } - } - - @PostMapping("/enablemessage") - public String enablemessage(@RequestParam(value = "msgId", required = true) String msgid) { - String status = vehicleService.enableMessage(msgid); - - if (status.equals("success")) { - return "success"; - } else { - return "Failed to update"; - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/package-info.java deleted file mode 100644 index 3ee13afb..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vtrack.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/package-info.java deleted file mode 100644 index 38718043..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vtrack; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java deleted file mode 100644 index c85093d2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java +++ /dev/null @@ -1,823 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vtrack.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import org.springframework.core.env.Environment; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; -import java.security.SecureRandom; -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 in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; - -@Service -public class VehicleService { - - private JdbcTemplate jdbcTemplate; - - private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - private static final int STRING_LENGTH = 15; - private static final Random RANDOM = new SecureRandom(); - - @Autowired - private Environment environment; - private String fileBaseUrl; - - @Autowired - public VehicleService(Environment environment) { - this.fileBaseUrl = environment.getProperty("fileBaseUrl"); - } - - @Autowired - public void setDataSource(@Qualifier("mysqlVehiclTrackingDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public static String generateRandomString() { - StringBuilder result = new StringBuilder(STRING_LENGTH); - for (int i = 0; i < STRING_LENGTH; i++) { - result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); - } - return result.toString(); - } - - 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); - - 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("vtrack_foldername"); - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - var date = DateTimeUtil.getCurrentDay(); - - uploadDirectory = uploadDirectory + serviceFolderName + "/" + year + "/" + month + "/" + date; - - try { - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - // Datetime string - String datetimetxt = DateTimeUtil.getCurrentDateTime(); - // File name - System.out.println(file.getOriginalFilename()); - String fileName = name + "_" + id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" - + file.getOriginalFilename(); - fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename - - String filePath = uploadDirectory + "/" + fileName; - - String filepath_txt = "/" + serviceFolderName + "/" + year + "/" + month + "/" + date + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Compress the image - // BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); - // byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% - // quality - - // Write the bytes to the file - Files.write(path, bytes); - - System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - public List> getAllTemplateNames() { - String sql = "SELECT `id`, `name` as template_name, `whatsapp_temp_name`, `whatsapp_temp_id` FROM `whatsapp_template` WHERE `isactive`=1 AND `isdelete`=0"; - return jdbcTemplate.queryForList(sql); - } - - public int saveMessageDetails(String date, String tempType, String imgPath) { - String sql = "INSERT INTO `message_list` (`msg_date`, `template_type`, `msg_img`) VALUES (?,?,?)"; - int rowsAffected = jdbcTemplate.update(sql, date, tempType, imgPath); - return rowsAffected; - } - - public List> getAllSavedMessages() { - String sql = "SELECT " - + "ml.`id` as msgid, " - + "ml.`msg_date` as msg_date , " - + "DATE_FORMAT(ml.`msg_date`, '%d-%m-%Y') AS msg_temp_event_date, " - + "DATE_FORMAT(ml.`cdate`, '%d-%m-%Y %r') AS createddate, " - + "ml.`msg_img` as msg_img, " - + "CONCAT('" + fileBaseUrl + "/gcc/files', ml.msg_img) AS msg_attachfile, " - + "wt.`name` as template_name, " - + "wt.`id` as template_id " - + "FROM `message_list` ml " - + "JOIN `whatsapp_template` wt ON ml.`template_type`=wt.`id` " - + "WHERE ml.`isactive` = 1 AND ml.`isdelete` = 0"; - return jdbcTemplate.queryForList(sql); - } - - public String sendMessage(String msgid, String datetxt, String fileurl) { - - String sql = "SELECT " - + "ml.`id` as msgid, " - + "DATE_FORMAT(ml.`msg_date`, '%d-%m-%Y') AS msg_temp_event_date, " - + "CONCAT('" + fileBaseUrl + "/gcc/files', ml.msg_img) AS msg_attachfile, " - + "wt.`id` as template_id " - + "FROM `message_list` ml " - + "JOIN `whatsapp_template` wt ON ml.`template_type`=wt.`id` " - + "WHERE ml.`isactive` = 1 AND ml.`isdelete` = 0 AND ml.`id`=?"; - // Fetch the data - List> result = jdbcTemplate.queryForList(sql, msgid); - - // Initialize variables to store the results - String tempid = ""; - String msgDate = ""; - String fileURL = ""; - String sendTo = ""; - // Check if the result list is not empty - if (!result.isEmpty()) { - Map row = result.get(0); // Get the first row (assuming id is unique) - - // Extract values from the result map and assign to variables - tempid = String.valueOf(row.get("template_id")); - msgDate = String.valueOf(row.get("msg_temp_event_date")); - fileURL = String.valueOf(row.get("msg_attachfile")); - - sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);"; - List> mobileResult = jdbcTemplate.queryForList(sql, tempid); - // Create a StringBuilder to hold the comma-separated mobile numbers - StringBuilder sendToBuilder = new StringBuilder(); - - // Iterate through the mobileResult list and build the sendTo string - for (Map mobileRow : mobileResult) { - String mobile = String.valueOf(mobileRow.get("mobile")); - - // Append the mobile number to the StringBuilder - if (sendToBuilder.length() > 0) { - sendToBuilder.append(","); - } - sendToBuilder.append(mobile); - } - - // Convert StringBuilder to String - sendTo = sendToBuilder.toString(); - - // Now you have the sendTo string with all mobile numbers - System.out.println("Mobile Numbers: " + sendTo); // For debugging, you can print this value - } - - String urlString = ""; - - String username = "2000233507"; - String password = "h2YjFNcJ"; - // String sendTo="9176617754"; //9176617754,8610011680,9360777472,9123565217 - // String msgDate=datetxt; - // String fileURL=fileurl; - - String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd"; - String from = "919445061913"; - switch (tempid) { - case "1": - - System.out.println("TempID is 1 (Vehicle March Out -> officer_test -> 1308878)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1" - + "&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AZone-wise+vehicle+march-out+details+for+Today%27s+%28" - + msgDate - + "%29+AM+shift+are+shared+above.%0A%0AFor+further+details%2C+please+click+on+the+button+below." - + "&media_url=" + fileURL - + "&isTemplate=true" - + "&footer=GCC+-+IT+Cell" - + "&buttonUrlParam=login.php%3Funame%3Dgcc.admin2024@jtrack.in%26password%3D123456"; - - // urlString - // ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template&apikey="+apikey+"&from="+from+"&to=9444173345&templateid=2784943&url="; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20vehicle%20march-out%20details"; - break; - case "2": - System.out.println("TempID is 2 (Fule Dip Details -> fuel_dip_details -> 1309072)"); - - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AYesterday%27s+%28" + msgDate - + "%29+Zone+wise+Fuel+Dip+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Fuel%20Dip%20Details"; - break; - case "3": - System.out.println("TempID is 3 (Late Marchout Details -> late_marchout_details -> 1309075)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone-wise+Late+Marchout+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Late%20Marchout%20Details"; - break; - case "4": - System.out - .println("TempID is 4 (LMV Route Deviation Details -> lmv_route_deviation_details -> 1309081)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone-wise+Compactors+LMV+Route+Deviation+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Compactors%20LMV%20Route%20%20Deviation%20Details"; - break; - case "5": - System.out - .println("TempID is 5 (HMV Route Deviation Details -> hmv_route_deviation_details -> 1309083)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone-wise+Compactors+HMV+Route+Deviation+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Compactors%20HMV%20Route%20%20Deviation%20Details"; - break; - - case "6": - System.out.println( - "TempID is 6 (C&D Waste Removal Monitoring -> c_and_d_waste_removal_monitoring -> 1335786)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+C%26D+Waste+Removal+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+C%26D+Waste+Removal+Details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20C%26D%20Waste%20Removal%20details"; - break; - - case "7": - System.out - .println("TempID is 7 (Enforcement Team Monitoring -> enforcement_team_monitoring -> 1362100)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AYesterday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Enforcement%20Team%20activity%20details"; - break; - - case "8": - System.out.println("TempID is 8 (Toilets Monitoring -> gcc_toilets_monitoring -> 1475869)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Toilets+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Toilets+Morning+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Toilets%20Morning%20inspection%20details"; - break; - - case "9": - System.out.println("TempID is 9 (Toilets Monitoring -> gcc_toilets_evening_monitoring -> 1475881)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Toilets+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Toilets+Evening+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Toilets%20Evening%20inspection%20details"; - break; - - case "10": - System.out.println("TempID is 10 (Bus Shelter Monitoring -> 1508454 - gcc_bus_shelter_monitoring)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Bus+Shelter+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Bus+Shelter+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Bus%20Shelter%20inspection%20details"; - break; - - case "11": - System.out.println("TempID is 11 (Still Catch Pit -> 1566758 - silt_catch_pit_cleaning )"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Silt+catch+Pit+Cleaning%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Silt+Catch+Pit+cleaning+details+shared+above+for+your+reference%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Silt%20Catch%20Pit%20cleaning%20details"; - break; - - case "12": - System.out.println("TempID is 12 (1590940 - tree_planting_gcc - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Tree+Planting%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+tree+planting+details+shared+above+for+your+reference%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20tree%20planting%20details"; - break; - - case "13": - System.out.println("TempID is 13 (1590940 - Chennai Schools (userd of Com Temp ) - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - // + - // "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Students%20Aadhar%20linked%20details"; - break; - - case "14": - System.out.println("TempID is 14 (1943196 - pet_wp_report - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - // + - // "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&caption=%2AGCC+PET+LICENSE+%26+VACCINATION%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Pet+license+%26+Vaccination+details+shared+above+for+your+kind+reference." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Pet%20license%20%26%20Vaccination%20details"; - break; - - case "15": - System.out.println( - "TempID is 15 (1590940 - GCC POS Penalty Monitoring Zone (userd of Com Temp ) - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+POS+Penalty+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29++POS+Penalty+Zone+wise+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=POS%20Penalty%20Zone%20wise%20details"; - - break; - - case "16": - System.out.println( - "TempID is 16 (1590940 - GCC POS Penalty Monitoring Catagory (userd of Com Temp ) - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+POS+Penalty+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29++POS+Penalty+Catagory+wise+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=POS%20Penalty%20Catagory%20wise%20details"; - break; - - case "17": - System.out.println( - "TempID is 17 (1590940 - GCC Enforcement Team Monitoring Temp (userd of Com Temp ) - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Zone%20wise%20Enforcement%20Team%20activity%20details"; - - break; - - case "21": - System.out.println("TempID is 21 (1590940 - Namma Salai - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Namma%20salai%20activity%20details"; - - break; - - case "22": - System.out.println("TempID is 22 (1590940 - Victoria Hall Booking - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Victoria%20Hall%20Booking%20Details"; - - break; - - case "23": - System.out.println("TempID is 23 (1590940 - Green Committee Report - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Green%20Committee%20Report%20Details"; - - break; - - case "24": - System.out.println("TempID is 24 (1590940 - Clean and Safe Guidelines - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Clean%20and%20Safe%20Construction%20-%20Vehicle%20Violation"; - - break; - - case "25": - System.out.println("TempID is 25 (1590940 - POS Collection Details - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=POS%20Collection%20Details"; - - break; - - case "26": - System.out.println("TempID is 26 (1590940 - Health - Tobacco seizures - IMAGE - STATIC)"); - urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid=" + username - + "&password=" + password - + "&send_to=" + sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate - + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url=" + fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey=" + apikey - + "&from=" + from - + "&to={{to}}&templateid=2784943" - + "&url=" + fileURL - + "&placeholders=Health-%20Tobacco%20seizures"; - - break; - - default: - System.out.println("TempID (" + tempid + ") is unknown"); - } - - if (!urlString.isBlank()) { - sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);"; - List> mobileResult2 = jdbcTemplate.queryForList(sql, tempid); - for (Map mobileRow2 : mobileResult2) { - String mobile = String.valueOf(mobileRow2.get("mobile")); - String finalUrl = urlString.replace("{{to}}", mobile); - String response = sendWhatsAppMessage(finalUrl); - System.out.println("WhatsApp response: " + response); - } - } - - return "success"; - } - - private String sendWhatsAppMessage(String urlString) { - String response = ""; - try { - URL url = new URL(urlString); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = String.valueOf(responseCode); - System.out.println("Response Code for URL: " + urlString + " is " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - return response; - } - - public String disablemessage(String msgid) { - String sql = "update message_list set isdelete =1, isactive = 0 where id = ?"; - - int rowsAffected = jdbcTemplate.update(sql, msgid); - - if (rowsAffected > 0) { - return "success"; - } else { - return "failed"; - } - } - - public String enableMessage(String msgid) { - String sql = "update message_list set isdelete =0, isactive = 1 where id = ?"; - - int rowsAffected = jdbcTemplate.update(sql, msgid); - - if (rowsAffected > 0) { - return "success"; - } else { - return "failed"; - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/package-info.java deleted file mode 100644 index 0e75932b..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.vtrack.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/.DS_Store deleted file mode 100644 index e75b5443..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/APIController.java deleted file mode 100644 index 184a45b0..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/APIController.java +++ /dev/null @@ -1,218 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.controller; - -import java.util.List; -import org.springframework.security.core.Authentication; - -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.beans.factory.annotation.Autowired; -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.gccoffice.ward_sabha.service.Petition; -import in.gov.chennaicorporation.gccoffice.ward_sabha.service.PetitionMaster; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/ward_sabha") -@RestController("wardSabhaRest") -public class APIController { - private PetitionMaster petitionMaster; - private Petition petition; - - @Autowired - public APIController(PetitionMaster petitionMaster,Petition petition) { - this.petitionMaster = petitionMaster; - this.petition = petition; - } - - @GetMapping(value="/getEventList") - public List getEvents() { - return petition.getEvents(); - } - - @GetMapping(value="/getCurrentEventList") - public List getCurrentEventList() { - return petition.getCurrentEventList(); - } - - @GetMapping(value="/getZoneAndWard") - public List getZoneAndWard() { - return petitionMaster.getZoneAndWard(); - } - - @GetMapping(value="/getCouncillor") - public List getCouncillor(@RequestParam("ward") String ward) { - return petitionMaster.getCouncillor(ward); - } - - @GetMapping(value="/getComplaintTypes") - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @GetMapping(value="/getOfficerList") - public List getOfficerList() { - return petitionMaster.getOfficerList(); - } - - @GetMapping(value="/getPetitionTypes") - public List getPetitionTypes() { - return petitionMaster.getPetitionTypes(); - } - - @GetMapping(value="/getPetitionList") - public List getPetitionList(@RequestParam("eventId") String eventId) { - return petition.getPetitionList(eventId); - } - - @GetMapping(value="/getUnmapPetitionList") - public List getUnmapPetitionList(@RequestParam("eventId") String eventId) { - return petition.getUnmapPetitionList(eventId); - } - - @GetMapping(value="/getPetitionDetails") - public List getPetitionDetails(@RequestParam("petitionNo") String petitionNo) { - return petition.getPetitionDetails(petitionNo); - } - - @PostMapping(value="/savePetition") - public String savePetition( - @RequestParam(value = "createdBy", required = false) String createdBy, - @RequestParam(value = "petitionType", required = false) String petitionType, - //@RequestParam(value = "petitionerName", required = false) String petitionerName, - //@RequestParam(value = "petitionerMobile", required = false) String petitionerMobile, - @RequestParam(value = "complaintType", required = false) String petitionerComplaint, - @RequestParam(value = "zone", required = false) String zone, - @RequestParam(value = "ward", required = false) String ward, - @RequestParam(value = "councillorName", required = false) String councillorName, - @RequestParam(value = "councillorMobile", required = false) String councillorMobile, - @RequestParam(value = "complaintNature", required = false) String complaintNature, - @RequestParam(value = "eventid", required = false) String eventid, - @RequestParam(value = "san_page1", required = false) MultipartFile page1, - @RequestParam(value = "san_page2", required = false) MultipartFile page2, - @RequestParam(value = "san_page3", required = false) MultipartFile page3, - @RequestParam(value = "san_page4", required = false) MultipartFile page4) { - - return petition.savePetition(petitionType, createdBy, zone, ward, councillorName, councillorMobile, petitionerComplaint, complaintNature, eventid,page1, page2, page3, page4); - } - - @PostMapping(value="/updatePetition") - public Boolean updatePetition( - @RequestParam(value = "petitionType", required = false) String petitionType, - @RequestParam(value = "petitionNo", required = false) String petitionNo, - @RequestParam(value = "createdBy", required = false) String createdBy, - @RequestParam(value = "petitionerName", required = false) String petitionerName, - @RequestParam(value = "petitionerMobile", required = false) String petitionerMobile, - @RequestParam(value = "petitionerAddress", required = false) String petitionerAddress, - @RequestParam(value = "petitionerPincode", required = false) String petitionerPincode, - @RequestParam(value = "complaintType", required = false) String petitionerComplaint, - @RequestParam(value = "complaintNature", required = false) String complaintNature) { - - return petition.updatePetition(petitionNo, petitionType, createdBy, petitionerName, petitionerMobile, petitionerAddress, petitionerPincode, petitionerComplaint, complaintNature); - } - - @PostMapping(value="/mapComplientToOfficer") - public Boolean updatePetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String mapOfficers) { - - String zerohours_mapping = mapOfficers; - - // First before Mapping need to unmaps old list - petition.unmapComplient(petitionId, petitionNo); - - if(zerohours_mapping!=null) { - String[] zerohours_mapping_parts = zerohours_mapping.split(","); - for (String values : zerohours_mapping_parts) { - String[] zerohours_mapping_val = values.split("_"); - if (zerohours_mapping_val.length > 0) { - String complientId = zerohours_mapping_val[0]; - String offcierId = zerohours_mapping_val[1]; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - } - } - } - return true; - } - - @PostMapping(value="/mapPetitionToOfficer") - public Boolean mapPetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String offidto) { - - String zerohours_mapping = offidto; - - // First before Mapping need to unmaps old list - //petition.unmapComplient(petitionId, petitionNo); - System.out.println("zerohours_mapping: "+zerohours_mapping); - if(zerohours_mapping!=null) { - - String complientId = "0"; - String offcierId = zerohours_mapping; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - - } - return true; - } - - @GetMapping(value="/unmapPetition") - public String getComplaintMappingDetails( - @RequestParam("mapid") String mapid) { - return petition.unmapPetition(mapid); - } - - @GetMapping(value="/getComplaintMappingDetails") - public List getComplaintMappingDetails( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("complaintTypeId") String complaintTypeId) { - return petition.getComplaintMappingDetails(petitionNo,petitionId,complaintTypeId); - } - - @GetMapping(value="/getPetitionMappingDetails2") - public List getComplaintMappingDetails2( - @RequestParam("petitionId") String petitionId) { - return petition.getPetitionMappingDetails2(petitionId); - } - - @GetMapping(value="/getComplaintList") - public List getComplaintList(@RequestParam("eventId") String eventId,@RequestParam("loginId") String loginId) { - return petition.getComplaintList(eventId,loginId); - } - - @GetMapping(value="/getComplaintListByPetitionId") - public List getComplaintListByPetitionId(@RequestParam("petitionId") String petitionId) { - return petition.getComplaintListByPetitionId(petitionId); - } - - @GetMapping(value="/getComplaintDetails") - public List getComplaintDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintDetails(mapId); - } - - @GetMapping(value="/getComplaintActionDetails") - public List getComplaintActionDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintActionDetails(mapId); - } - - @PostMapping(value="/saveComplanitStatus") - public String saveComplanitStatus( - @RequestParam("createdBy") String createdBy, - @RequestParam("mapId") String mapId, - @RequestParam("complaintStatus") String complaintStatus, - @RequestParam("complaintActionText") String complaintActionText, - @RequestParam("action_san_page1") MultipartFile actionPage1, - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo) { - - return petition.saveComplanitStatus(createdBy, mapId, complaintStatus, complaintActionText, actionPage1, petitionId, petitionNo); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/MainController.java deleted file mode 100644 index ff27e247..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/MainController.java +++ /dev/null @@ -1,138 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.controller; - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/ward_sabha") -@Controller("WardSabhaController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/ward_sabha/"; - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"index"; - } - - @GetMapping({"/new_event"}) - public String newEvent(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_event"; - } - - @GetMapping({"/new_petition"}) - public String newPetition(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_petition"; - } - - @GetMapping("/petition-ack/{petitionNo}") - public String petitionAck(Model model,@PathVariable("petitionNo") String petitionNo) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_ack"; - } - - @GetMapping("/petition-list") - public String petitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_list"; - } - - @GetMapping("/unmapped-petition-list") - public String unMappedPetitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_not_mapped_list"; - } - - @GetMapping("/update-petition") - public String petitionUpadte(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/view-petition") - public String petitionView(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view"; - } - - @GetMapping("/view-petition-modal") - public String petitionViewModal(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - //System.out.println(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view_modal_page"; - } - - @GetMapping("/search-petition") - public String petitionSearch(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - //model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/complaint-list") - public String complaintList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"complaint_list"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/package-info.java deleted file mode 100644 index 1e3a3298..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/ComplaintType.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/ComplaintType.java deleted file mode 100644 index 927d8073..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/ComplaintType.java +++ /dev/null @@ -1,21 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.data; - -import java.util.Map; - -public class ComplaintType { - private int complaintTypeId; - private String complaintType; - - public ComplaintType(Map map) { - this.complaintTypeId = (int) map.get("complaint_typeid"); - this.complaintType = (String) map.get("complaint_type"); - } - - public int getComplaintTypeId() { - return complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/package-info.java deleted file mode 100644 index 8263f028..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/package-info.java deleted file mode 100644 index 1440aeb5..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ -/** - * - */ -package in.gov.chennaicorporation.gccoffice.ward_sabha; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/Petition.java deleted file mode 100644 index 6ff2cde6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/Petition.java +++ /dev/null @@ -1,782 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.transaction.annotation.Transactional; -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.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.ward_sabha.data.ComplaintType; -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.GetMappingUserDetails; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -@Service("wardsabhaPetition") -public class Petition { - private JdbcTemplate jdbcTemplate; - private final Environment environment; - private PetitionMaster petitionMaster; - private GetMappingUserDetails getMappingUserDetails; - - @Autowired - public Petition(Environment environment,PetitionMaster petitionMaster,GetMappingUserDetails getMappingUserDetails) { - this.environment = environment; - this.petitionMaster = petitionMaster; - this.getMappingUserDetails = getMappingUserDetails; - } - - - @Autowired - public void setDataSource(@Qualifier("mysqlWardSabhaDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getEvents(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `event_master` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY date(`date`) DESC"; - //System.out.println(SqlQuery); - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional(readOnly = true) - public List> getCurrentEventList(){ - String SqlQuery = ""; - - //SqlQuery = "SELECT * FROM event_master WHERE date(`date`)= date(NOW())"; - SqlQuery = "SELECT * FROM event_master WHERE `isactive`=1 AND `isdelete`=0 ORDER BY date(`date`) DESC"; - //System.out.println(SqlQuery); - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional(readOnly = true) - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - return complaintTypeMaps.stream() - .map(ComplaintType::new) - .collect(Collectors.toList()); - } - - @Transactional(readOnly = true) - // Method to map complaint type IDs to their respective complaint types - public static String mapComplaintTypes(List complaintTypes, String complaint) { - String[] complaintIds = complaint.split(","); - StringBuilder complaintTxtBuilder = new StringBuilder(); - - for (String complaintId : complaintIds) { - int id = Integer.parseInt(complaintId); - for (ComplaintType type : complaintTypes) { - if (type.getComplaintTypeId() == id) { - if (complaintTxtBuilder.length() > 0) { - complaintTxtBuilder.append(","); - } - complaintTxtBuilder.append(type.getComplaintType()); - break; - } - } - } - - return complaintTxtBuilder.toString(); - } - - @Transactional(readOnly = true) - public List> getPetitionList(String eventid) { - try { - //String sqlQuery = "SELECT * FROM petition WHERE (`isactive`=1 AND `isdelete`=0)"; - String sqlQuery = "SELECT p.* , pt.name petition_type_name FROM petition p, petition_master.petition_types pt " - + "WHERE (p.`isactive`=1 AND p.`isdelete`=0) AND `eventid`='"+eventid+"' AND p.petition_type = pt.petition_type_id "; - List> result = jdbcTemplate.queryForList(sqlQuery); - //Base64Util.encodeBase64(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getUnmapPetitionList(String eventid) { - try { - String sqlQuery = "SELECT " - + " p.* " - + "FROM " - + " `petition` p " - + "WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) AND `eventid`='"+eventid+"' "; - //+ " AND NOT EXISTS (" - //+ " SELECT 1 " - //+ " FROM `petition_mapping` pm " - //+ " WHERE (p.`petition_id` = pm.`petition_id`) AND (pm.`isactive` = 1 AND pm.`isdelete` = 0 ) " - //+ " )"; - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - - @Transactional(readOnly = true) - public List> getPetitionDetails(String petitionNo) { - try { - String sqlQuery = "SELECT * FROM petition WHERE petition_no = ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - //System.out.println("SELECT * FROM petition WHERE petition_no = '"+petitionNo+"' AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"); - List> result = jdbcTemplate.queryForList(sqlQuery, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String savePetition( - String petitionType, - String createdBy, - String zone, - String ward, - String petitionerName, - String petitionerMobile, - String petitionerComplaint, - String complaintNature, - String eventid, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition` " - + "(`petition_type`, `created_by`, `petitioner_name`, `petitioner_mobile`, " - + "`petitioner_complaint`, `petitioner_complaint_txt`, `eventid`, `zone`, `ward`,`complaint_nature`) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - try { - // Complaint Type List - //List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - //List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - //String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - String petitionerComplaint_txt=""; - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, "1"); - ps.setString(2, createdBy); - ps.setString(3, petitionerName); - ps.setString(4, petitionerMobile); - ps.setString(5, petitionerComplaint); - ps.setString(6, petitionerComplaint_txt); - ps.setString(7, eventid); - ps.setString(8, zone); - ps.setString(9, ward); - ps.setString(10, complaintNature); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - - // Get the value of mp_ackno from application.properties - String ackno = environment.getProperty("zh_ackno"); - String ackno_prefix = environment.getProperty("zh_ackno_prefix"); - - // Convert ackno to int if needed - int acknoInt = Integer.parseInt(ackno); - - // Calculate the petition number - int petitionNo = (int) (lastInsertId + acknoInt); - - // Construct the petition number string - String petitionNoString = ackno_prefix + petitionNo; - - // Update the petition number in the database - updatePetitionNumber(lastInsertId, petitionNoString); - - // Add Petition Scan File in the database - addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return petitionNoString; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionNumber(int petitionId,String petitionNoString) { - String sqlQuery = "UPDATE `petition` SET `petition_no`='"+petitionNoString+"' WHERE `petition_id`='"+petitionId+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String addPetitionFile(String createdBy, - int petitionId, - String petitionNoString, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - String fileName=""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - case 2: - file = page2; - fileName = "Scan2"; - break; - case 3: - file = page3; - fileName = "Scan3"; - break; - case 4: - file = page4; - fileName = "Scan4"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("zh_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = petitionId + "_" + fileName + "_" + petitionNoString + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"','"+petitionNoString+"','"+petitionId+"')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - @Transactional - public boolean updatePetition( - String petitionNo, - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerAddress, - String petitionerPincode, - String petitionerComplaint, - String complaintNature) { - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - /* - String sqlQuery = "UPDATE `petition` SET " - //+ "`petition_type`='"+petitionType+"', " - + "`created_by`='"+createdBy+"', `petitioner_name`='"+petitionerName+"', `petitioner_mobile`='"+petitionerMobile+"', " - //+ "`petitioner_address`='"+petitionerAddress+"', `petitioner_pincode`='"+petitionerPincode+"'," - + "`petitioner_complaint`='"+petitionerComplaint+"', `petitioner_complaint_txt`='"+petitionerComplaint_txt+"', `complaint_nature`='"+complaintNature+"' " - + "WHERE (`petition_no`='"+petitionNo+"') LIMIT 1"; - System.out.println(sqlQuery); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(sqlQuery); - */ - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type` = ?, `created_by` = ?, `petitioner_name` = ?, `petitioner_mobile` = ?, " - + "`petitioner_address` = ?, `petitioner_pincode` = ?, `petitioner_complaint` = ?, " - + "`petitioner_complaint_txt` = ?, `complaint_nature` = ? " - + "WHERE `petition_no` = ? LIMIT 1"; - - int rowsUpdated = jdbcTemplate.update(sqlQuery, - petitionType, - createdBy, - petitionerName, - petitionerMobile, - petitionerAddress, - petitionerPincode, - petitionerComplaint, - petitionerComplaint_txt, // Safely includes single quotes - complaintNature, - petitionNo - ); - - // Add Petition Scan File in the database - // addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return true; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return false; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionStatus(String petitionId,String petitionNo) { - String status_value = "close"; - List> petitionMappingDetails = getPetitionMappingDetails(petitionNo, petitionId); - - for (Map mapping : petitionMappingDetails) { - // Access values from the map using keys - Object status = mapping.get("status"); - // Check if status is "close" - if (!"close".equals(status)) { - status_value = "partial"; - } - } - - String sqlQuery = "UPDATE `petition` SET `status`='"+status_value+"' WHERE `petition_no`='"+petitionNo+"' AND `petition_id`='"+petitionId+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails(String petitionNo, String petitionId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails2(String petitionId) { - try { - String sqlQuery = "SELECT pm.mapid,pm.petition_no,pm.petition_id,pm.status,om.* FROM zerohours_petition.petition_mapping as pm,petition_master.officer_master_zh as om WHERE (pm.`petition_id`= ?) AND (pm.`isactive`=1 AND pm.`isdelete`=0) AND pm.off_id=om.off_id"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId); - System.out.println(sqlQuery + petitionId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public boolean unmapComplient(String petitionId, String petitionNo) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `petition_id`='"+petitionId+"' AND `petition_no`='"+petitionNo+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String unmapPetition(String mapid) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `mapid`='"+mapid+"'"; - jdbcTemplate.update(sqlQuery); - return "success"; - } - - @Transactional - public boolean mapComplientToOfficer( - String createdBy, String petitionId, String petitionNo, String complaintId, String officerId) { - String sqlQuery = "INSERT INTO `petition_mapping`" - + "(`created_by`, `off_id`, `petition_no`, `complaint_typeid`, `petition_id`) " - + "VALUES (?, ?, ?, ?, ?)"; - jdbcTemplate.update(sqlQuery, createdBy, officerId, petitionNo, complaintId, petitionId); - return true; - } - - @Transactional - public boolean updateMapComplientStatus(String mapId,String status) { - String sqlQuery = "UPDATE `petition_mapping` SET `status`=? WHERE `mapid`=? LIMIT 1"; - jdbcTemplate.update(sqlQuery, status, mapId); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getComplaintMappingDetails(String petitionNo, String petitionId, String complaintTypeId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND `complaint_typeid`= ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo,complaintTypeId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintList(String eventId, String loginId) { - String sqlQuery = ""; - try { - sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm` " - + " FROM " - + " `petition` p, `petition_mapping` pm, `petition_master`.`officer_master_zh` om" - + " WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - //+ " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " AND p.eventid='"+eventId+"' "; - - String officerMaster = getMappingUserDetails.getOfficerMaster(loginId); - - //if (officerMaster != null && !officerMaster.isEmpty() && loginId!='256') { - if (!loginId.equals("256") && !loginId.equals("1")) { - sqlQuery = sqlQuery + " AND (pm.off_id IN("+officerMaster+"))"; - } - - System.out.println(sqlQuery + loginId); - - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - //System.out.println(petitionNo + " : "+petitionNoEncoded + " : "+Base64Util.encodeBase64(petitionNo)); - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintListByPetitionId(String petitionId) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, p.`status` petition_status, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status` complaint_status, pm.`cdate` mappedOn, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `zerohours_petition`.`petition` p,`zerohours_petition`.`petition_mapping` pm, `petition_master`.`officer_master_zh` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`petition_id` = '"+petitionId+"' AND p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintDetails(String mapid) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm` " - + " FROM " - + " `petition` p,`petition_mapping` pm, `petition_master`.`officer_master_zh` om" - + " WHERE " - + " pm.`mapid`='"+mapid+"' " - + " AND (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - //+ " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - //System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintActionDetails(String mapId) { - try { - String sqlQuery = "SELECT * FROM `petition_action_taken` WHERE (`mapid`= ? AND `isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, mapId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String saveComplanitStatus( - String createdBy, - String mapId, - String complaintStatus, - String complaintActionText, - MultipartFile actionPage1, - String petitionId, - String petitionNo) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String selectQuery ="Select solmapid,count(`solmapid`) as total FROM `petition_action_taken` WHERE mapid=?"; - List> result = jdbcTemplate.queryForList(selectQuery, mapId); - int total = (result.isEmpty()) ? 0 : ((Number) result.get(0).get("total")).intValue(); - - String sqlQuery; - boolean isUpdate = total > 0; // If total > 0, we will update, otherwise insert - System.out.println("selectQuery: "+selectQuery); - System.out.println("isUpdate: "+isUpdate +" mapId: "+mapId); - if (isUpdate) { - lastInsertId = (int) result.get(0).get("solmapid"); - // Update existing record - sqlQuery = "UPDATE `petition_action_taken` SET `created_by` = ?, `off_id` = ?,`mapid`=?, `status` = ?, `comments` = ? WHERE `mapid` = '"+mapId+"'"; - } else { - // Insert new record - sqlQuery = "INSERT INTO `petition_action_taken` " - + "(`created_by`, `off_id`, `mapid`, `status`, `comments`) " - + "VALUES (?, ?, ?, ?, ?)"; - } - - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - int rowsAffected = jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, createdBy); - ps.setString(3, mapId); - ps.setString(4, complaintStatus); - ps.setString(5, complaintActionText); - return ps; - }, keyHolder); - - if (rowsAffected > 0) { - if (!isUpdate) { - Number key = keyHolder.getKey(); - if (key != null) { - lastInsertId = key.intValue(); - // Continue with further processing - } else { - - // Handle the case when the key is null - System.out.println("Insertion succeeded but no key was generated."); - return String.valueOf(rowsAffected); // Or some other appropriate response - } - } - } else { - System.out.println("Insertion failed, no rows affected."); - return "error"; - } - - // Further logic to update status and add files - if (lastInsertId > 0) { - updateMapComplientStatus(mapId, "close"); - updatePetitionStatus(petitionId, petitionNo); - addActionFile(mapId, lastInsertId, actionPage1); - return String.valueOf(lastInsertId); - } - - } catch (DataAccessException e) { - e.printStackTrace(); - return "error"; - } - return ""; - } - - @Transactional - public String addActionFile( String mapId, int solmapid, - MultipartFile page1) { - - MultipartFile file = page1; - String fileName = "Scan1_"+solmapid; - - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("zh_foldername"); - String serviceActionFolderName = environment.getProperty("zh_action_Foldername"); - - uploadDirectory = uploadDirectory + serviceFolderName +"/"+ serviceActionFolderName; - - // File name - fileName = mapId + "_" + fileName + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "UPDATE `petition_action_taken` SET " - + "`file_name`='"+fileName+"', " - + "`file_size`='"+fileSize+"', " - + "`file_type`='"+fileType+"' " - + "WHERE `solmapid`='"+solmapid+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - return "success"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/PetitionMaster.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/PetitionMaster.java deleted file mode 100644 index 18f567c2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/PetitionMaster.java +++ /dev/null @@ -1,90 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("wardsabhaPetitionMaster") -public class PetitionMaster { - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPetitionMasterDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getZoneAndWard(){ - String SqlQuery = ""; - - SqlQuery = "SELECT " - + " CAST(zone AS UNSIGNED) AS zone, " - + " GROUP_CONCAT(CAST(divid AS UNSIGNED) ORDER BY CAST(divid AS UNSIGNED) ASC) AS wards " - + "FROM " - + " councillor " - + "GROUP BY " - + " CAST(zone AS UNSIGNED) " - + "ORDER BY " - + " CAST(zone AS UNSIGNED) ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getCouncillor(String ward){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM councillor WHERE `divid`='"+ward+"' LIMIT 1"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getComplaintType(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `complaint_types` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getOfficerList(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `officer_master_zh` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getPetitionTypes(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `petition_types` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby` ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/package-info.java deleted file mode 100644 index 5d910b48..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_sabha.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/.DS_Store deleted file mode 100644 index c763e4c7..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/APIController.java deleted file mode 100644 index 52949351..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/APIController.java +++ /dev/null @@ -1,201 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.controller; - -import org.springframework.http.MediaType; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.text.DecimalFormat; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.springframework.security.core.Authentication; - -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.ui.Model; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.ward_shaba.service.Petition; - -@RequestMapping("gcc/api/ward_shaba") -@RestController("WardShabaRest") // Mayor Petition Rest -public class APIController { - - private Petition petition; - - @Autowired - public APIController(Petition petition) { - this.petition = petition; - } - - @PostMapping("/saveevent") - public ResponseEntity> saveMinutes( - @RequestParam("minutesDate") String minutesDate, - @RequestParam("minutesName") String minutesName, - @RequestParam("ward") String ward, - @RequestParam(value = "attachment", required = false) MultipartFile attachment) { - - try { - // Save file if present and get the file path - String attachmentPath = attachment != null && !attachment.isEmpty() - ? petition.saveFile(attachment, "minutes") - : ""; // Empty if no file uploaded - - // Save event details - Map result = petition.saveMinutes(minutesDate, minutesName, attachmentPath,ward); - - if (result.containsKey("minutesId")) { - return ResponseEntity.ok(result); - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("message", "Failed to save event")); - } - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Map.of("message", "Error: " + e.getMessage())); - } - } - - @GetMapping("/getAllEvents") - public ResponseEntity>> getAllEvents(@RequestParam("ward") String ward) { - List> events = petition.getAllEvents(ward); - return ResponseEntity.ok(events); - } - - @PostMapping(value = "/savePetition", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> savePetition(@RequestParam(value = "zone", required = false) String zone, - @RequestParam(value = "ward", required = false) String ward, - @RequestParam(value = "complaintNature", required = false) String complaintNature, - @RequestParam(value = "eventid", required = false) String minutesid) { - - System.out.println("Received Data - Zone: " + zone + ", Ward: " + ward + ", Complaint: " + complaintNature - + ", Event ID: " + minutesid); - - try { - Map result = petition.savePetition(zone, ward, complaintNature, minutesid); - - // Extract minutes_no and minutes_id from the result - Integer minutesId = (Integer) result.get("minutes_id"); - String minutesNo = (String) result.get("minutes_no"); - - if (minutesId != null && minutesId > 0 && minutesNo != null) { - return ResponseEntity.ok(result); // ✅ Send JSON response - } else { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.singletonMap("error", "Failed to save minutes")); - } - } catch (IllegalArgumentException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(Collections.singletonMap("error", e.getMessage())); - } - } - - @GetMapping("/getMinutesNames") - public ResponseEntity>> getMinutesNames(@RequestParam("ward") String ward) { - List> minutesList = petition.getAllMinutesNames(ward); - return ResponseEntity.ok(minutesList); - } - - @GetMapping("/getMinutesDetails") - public ResponseEntity getMinutesDetails( - @RequestParam("minutesId") int minutesId, - @RequestParam("ward") String ward) { - System.out.println("Fetching details for minutesId: " + minutesId); - - List> detailsList = petition.getMinutesDetailsById(minutesId,ward); - - if (detailsList == null || detailsList.isEmpty()) { - System.out.println("No details found for minutesId: " + minutesId); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No data found"); - } - - System.out.println("Data found: " + detailsList); - return ResponseEntity.ok(detailsList); - } - - @PostMapping("/saveComplaintUpdate") - public ResponseEntity saveMinutes1(@RequestParam("minutesNo") String minutesNo, - @RequestParam("replyMessage") String replyMessage, - @RequestParam(value = "document", required = false) MultipartFile document) { - - try { - System.out.println("minutesNo = " + minutesNo); - System.out.println("replyMessage = " + replyMessage); - System.out.println("document = " + document); - String documentPath = petition.saveFile(document, "minutes"); - petition.saveUpdateMinutes1(minutesNo, replyMessage, documentPath); - return ResponseEntity.ok("Minutes details saved successfully."); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage()); - } - } - - @GetMapping("/get-file-size") - public @ResponseBody FileSizeResponse getFileSize(@RequestParam String filePath) { - try { - // Convert to absolute path - // String filepath1=""+filePath; - File file = new File(filePath); - Path path = file.toPath(); - - // Debug log - System.out.println("Checking file size for: " + path.toString()); - - if (!Files.exists(path)) { - System.out.println("File does not exist: " + path); - return new FileSizeResponse(-1, "File not found"); - } - - float size = Files.size(path); - String readableSize = formatFileSize(size); - return new FileSizeResponse(size, readableSize); - } catch (IOException e) { - e.printStackTrace(); - return new FileSizeResponse(-1, "Error reading file"); - } - } - - // Method to format file size in KB, MB, GB - private String formatFileSize(float size) { - if (size <= 0) - return "N/A"; - String[] units = { "B", "KB", "MB", "GB", "TB" }; - int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); - return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; - } - - // Response DTO - public static class FileSizeResponse { - private float size; - private String readableSize; - - public FileSizeResponse(float size, String readableSize) { - this.size = size; - this.readableSize = readableSize; - } - - public float getSize() { - return size; - } - - public String getReadableSize() { - return readableSize; - } - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/MainController.java deleted file mode 100644 index 1c262dc2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/MainController.java +++ /dev/null @@ -1,130 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.controller; - -import java.util.List; -import java.util.Map; - - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.ward_shaba.service.Petition; - -@RequestMapping("/gcc/ward_shaba") -@Controller("WardShabaController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/ward_shaba/"; - private Petition petition; - - @Autowired - public MainController(RestTemplate restTemplate,Petition petition) { - this.restTemplate = restTemplate; - this.petition = petition; - } - - @GetMapping({ "", "/", "/index", "/dashboard" }) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - return BasePath + "index"; - } - - @GetMapping({ "/event_creation" }) - public String eventcreation(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - - List> wardList = petition.getUserWard(LoginUserId); - String wardtxt = "0"; - // Ensure the list is not empty to avoid IndexOutOfBoundsException - if (!wardList.isEmpty()) { - // Get the first map (the first result) - Map wardMap = wardList.get(0); - - // Extract the 'ward' value from the map - wardtxt = (String) wardMap.get("ward"); - - // Print the ward value - System.out.println("User Ward Text: " + wardtxt); - } else { - System.out.println("No ward found for the user."); - } - - model.addAttribute("LoginUserId", LoginUserId); - model.addAttribute("myWard", wardtxt); - return BasePath + "eventcreation"; - } - - @GetMapping("/new_minutes") - public String newPetition(@RequestParam(required = false) String event, - @RequestParam(value = "eventid", required = false) String eventid, Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - - List> wardList = petition.getUserWard(LoginUserId); - String wardtxt = "0"; - // Ensure the list is not empty to avoid IndexOutOfBoundsException - if (!wardList.isEmpty()) { - // Get the first map (the first result) - Map wardMap = wardList.get(0); - - // Extract the 'ward' value from the map - wardtxt = (String) wardMap.get("ward"); - - // Print the ward value - System.out.println("User Ward Text: " + wardtxt); - } else { - System.out.println("No ward found for the user."); - } - - model.addAttribute("LoginUserId", LoginUserId); - model.addAttribute("myWard", wardtxt); - if (event != null) { - model.addAttribute("eventName", event); - model.addAttribute("eventId", eventid); - } - - return BasePath + "new_minutes"; - } - - @GetMapping("/minutes-list") - public String petitionList( - @RequestParam(required = false) String event, - @RequestParam(value = "eventid", required = false) String eventid, - Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - - List> wardList = petition.getUserWard(LoginUserId); - String wardtxt = "0"; - // Ensure the list is not empty to avoid IndexOutOfBoundsException - if (!wardList.isEmpty()) { - // Get the first map (the first result) - Map wardMap = wardList.get(0); - - // Extract the 'ward' value from the map - wardtxt = (String) wardMap.get("ward"); - - // Print the ward value - System.out.println("User Ward Text: " + wardtxt); - } else { - System.out.println("No ward found for the user."); - } - - model.addAttribute("LoginUserId", LoginUserId); - model.addAttribute("myWard", wardtxt); - - if (event != null) { - model.addAttribute("eventName", event); - model.addAttribute("eventId", eventid); - } - return BasePath + "minutes_list"; - } - -} \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/package-info.java deleted file mode 100644 index eed40c0e..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/ComplaintType.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/ComplaintType.java deleted file mode 100644 index 64b88812..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/ComplaintType.java +++ /dev/null @@ -1,21 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.data; - -import java.util.Map; - -public class ComplaintType { - private int complaintTypeId; - private String complaintType; - - public ComplaintType(Map map) { - this.complaintTypeId = (int) map.get("complaint_typeid"); - this.complaintType = (String) map.get("complaint_type"); - } - - public int getComplaintTypeId() { - return complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/package-info.java deleted file mode 100644 index e7ec8072..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/package-info.java deleted file mode 100644 index d460f5a6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ -/** - * - */ -package in.gov.chennaicorporation.gccoffice.ward_shaba; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/Petition.java deleted file mode 100644 index bc2af252..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/Petition.java +++ /dev/null @@ -1,309 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.transaction.annotation.Transactional; -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.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.com_petition.data.ComplaintType; -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.GetMappingUserDetails; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; - -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -@Service("wardSabhaPetition") -public class Petition { - private JdbcTemplate jdbcTemplate; - private final Environment environment; -// private PetitionMaster petitionMaster; - private GetMappingUserDetails getMappingUserDetails; - - @Autowired - public Petition(Environment environment, - GetMappingUserDetails getMappingUserDetails) { - this.environment = environment; -// this.petitionMaster = petitionMaster; - this.getMappingUserDetails = getMappingUserDetails; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlWardShabaDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - public Map savePetition(String zone, String ward, String complaintNature, String minutesid) - throws DataAccessException { - final int eventid; // Declare as final - - if (minutesid != null && !minutesid.trim().isEmpty()) { - try { - eventid = Integer.parseInt(minutesid); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid event ID: " + minutesid); - } - } else { - eventid = 0; // Assign default value - } - - // Format current date as yyyy/MM/dd - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); - String currentDate = sdf.format(new Date()); - - // Get the latest number for today's minutes_no - String latestNoQuery = "SELECT COALESCE(MAX(CAST(SUBSTRING_INDEX(minutes_no, '/', -1) AS UNSIGNED)), 0) FROM minutes_list WHERE minutes_no LIKE ?"; - Integer lastNumber = jdbcTemplate.queryForObject(latestNoQuery, new Object[] { currentDate + "/%" }, - Integer.class); - - int nextNumber = (lastNumber != null) ? lastNumber + 1 : 1; - String minutesNo = currentDate + "/" + nextNumber; // Example: 2024/07/30/1 - System.out.println("minutes-no:" + minutesNo); - // Insert into DB - String sqlQuery = "INSERT INTO minutes_list (zone, ward, minutes_details, minutes_id, minutes_no) VALUES (?, ?, ?, ?, ?)"; - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, zone); - ps.setString(2, ward); - ps.setString(3, complaintNature); - ps.setInt(4, eventid); // Now eventid is final - ps.setString(5, minutesNo); - return ps; - }, keyHolder); - - // Get the inserted ID - int generatedId = keyHolder.getKey().intValue(); - - // Prepare response - Map response = new HashMap<>(); - response.put("minutes_id", generatedId); - response.put("minutes_no", minutesNo); - return response; - } - - @Transactional - public boolean updatePetitionNumber(int petitionId, String petitionNoString) { - String sqlQuery = "UPDATE `petition` SET `petition_no`='" + petitionNoString + "' WHERE `petition_id`='" - + petitionId + "'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String addPetitionFile(String createdBy, int petitionId, String petitionNoString, MultipartFile page1, - MultipartFile page2, MultipartFile page3, MultipartFile page4) { - - String fileName = ""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - case 2: - file = page2; - fileName = "Scan2"; - break; - case 3: - file = page3; - fileName = "Scan3"; - break; - case 4: - file = page4; - fileName = "Scan4"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("zh_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = petitionId + "_" + fileName + "_" + petitionNoString + "_" + file.getOriginalFilename(); - - // File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('" + createdBy + "','" + fileName + "','" + fileSize + "','" + fileType + "','" - + petitionNoString + "','" + petitionId + "')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - public Map saveMinutes(String minutesDate, String minutesName, String attachmentPath, String ward) { - String sql = "INSERT INTO ward_minutes (minutes_date, minutes_name, is_active, is_delete,minutes_img, ward) VALUES (?, ?, 1, 0,?,?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, minutesDate); - ps.setString(2, minutesName); - ps.setString(3, attachmentPath); - ps.setString(4, ward); - return ps; - }, keyHolder); - - // Prepare response data - Map response = new HashMap<>(); - - if (keyHolder.getKey() != null) { - response.put("minutesId", keyHolder.getKey().intValue()); - response.put("minutesDate", minutesDate); - response.put("minutesName", minutesName); - response.put("ward", ward); - response.put("message", "Event saved successfully!"); - } - - return response; - } - - public List> getAllMinutesNames(String ward) { - String query = "SELECT minutes_id, minutes_name FROM ward_minutes WHERE is_active = 1 AND is_delete = 0 AND `ward`=?"; - return jdbcTemplate.queryForList(query,ward); - } - - public List> getUserWard(String userid) { - String query = "SELECT `ward` FROM `gcc_apps`.`user_zone_ward_list` WHERE `isactive` = 1 AND `appusers_userid` = ? LIMIT 1"; - return jdbcTemplate.queryForList(query,userid); - } - - public List> getMinutesDetailsById(int minutesId, String ward) { - /*String query = "SELECT ml.minutes_id,ml.ref_img,ml.minutes_no, ml.minutes_details, DATE_FORMAT(ml.created_date, '%d-%m-%Y') AS created_date, " - + "ml.remarks, wm.minutes_name,wm.minutes_img " + "FROM minutes_list ml " - + "LEFT JOIN ward_minutes wm ON ml.minutes_id = wm.minutes_id " + "WHERE ml.minutes_id = ?";*/ - String query ="SELECT ml.minutes_id,ml.ref_img,ml.minutes_no, ml.minutes_details, DATE_FORMAT(ml.created_date, '%d-%m-%Y') AS created_date, " - + "ml.remarks, wm.minutes_name,wm.minutes_img FROM ward_minutes wm " - + "LEFT JOIN minutes_list ml ON wm.minutes_id = ml.minutes_id WHERE wm.minutes_id = ? AND wm.ward=?"; - - return jdbcTemplate.queryForList(query, minutesId, ward); - } - - // Method to save file and return path - public String saveFile(MultipartFile file, String fileCategory) throws IOException { - if (file == null || file.isEmpty()) { - return ""; // Return empty if no file uploaded - } - - // Define upload directory - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolder = environment.getProperty("minutes_files"); - - var year =DateTimeUtil.getCurrentYear(); - var month =DateTimeUtil.getCurrentMonth(); - var date =DateTimeUtil.getCurrentDay(); - - uploadDirectory = uploadDirectory + serviceFolder + "/" + year + "/" + month; - - // String fullUploadPath = uploadDirectory + "/" + serviceFolder + "/" + year + - // "/" + month; - - // Create directory if it does not exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String fileName = fileCategory + "minutes_file" + file.getOriginalFilename(); - // Construct the file path - String filepath = uploadDirectory + "/" + fileName; - String filepath_txt = "/" + serviceFolder + "/" + year + "/" + month + "/" + fileName; - - Path path = Paths.get(filepath); - - // Ensure the directory exists - Files.createDirectories(path.getParent()); - - // Write the file to the specified path - Files.write(path, file.getBytes()); - - // Save file to disk - Files.write(Paths.get(filepath), file.getBytes()); - - return filepath_txt; // Return the relative path to be stored in DB - } - - public void saveUpdateMinutes1(String minutesNo, String replyMessage, String documentPath) { - String sql = "UPDATE minutes_list SET remarks = ?, ref_img = ? WHERE minutes_no = ?"; - jdbcTemplate.update(sql, replyMessage, documentPath, minutesNo); - } - - public List> getAllEvents(String ward) { - String sql = "SELECT CASE WHEN COUNT(ml.minutes_id) > 0 THEN COUNT(ml.minutes_id) ELSE 0 " - + " END AS minutes_count, wm.minutes_id, wm.minutes_date, wm.minutes_name, wm.minutes_img " - + " FROM ward_minutes wm " + " LEFT JOIN minutes_list ml ON wm.minutes_id = ml.minutes_id " - + " WHERE wm.is_active = 1 AND wm.is_delete = 0 AND wm.`ward`=?" - + " GROUP BY wm.minutes_id, wm.minutes_date, wm.minutes_name, wm.minutes_img"; - - List> events = jdbcTemplate.queryForList(sql,ward); - - // Ensure correct image path formatting - events.forEach(event -> { - if (event.get("minutes_img") != null) { - String imagePath = event.get("minutes_img").toString(); - // Remove extra slashes - imagePath = imagePath.replaceAll("/{2,}", "/"); - event.put("minutes_img", imagePath); - } - }); - - return events; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/package-info.java deleted file mode 100644 index 4c9bbcc3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.ward_shaba.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/works/.DS_Store deleted file mode 100644 index b7c592d2..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/works/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/APIContoller.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/APIContoller.java deleted file mode 100644 index 906b2d52..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/APIContoller.java +++ /dev/null @@ -1,904 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works.controller; - -import in.gov.chennaicorporation.gccoffice.works.service.ERPEstimateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.works.service.EstimateService; - -import java.io.IOException; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.*; -import java.util.stream.Collectors; - -@RestController -@RequestMapping("/gcc/works/api/estimates") - -public class APIContoller { - - @Autowired - private EstimateService estimateService; - - @Autowired - private ERPEstimateService erpEstimateService; - - // to save ERP works - /*@PostMapping(value = "/save", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity saveEstimate(@RequestParam("estno") String estimateNo, - @RequestParam("estdate") String estimateDate, - @RequestParam("zone") String zone, - @RequestParam("ward") String ward, - @RequestParam("projectname") String projectName, - @RequestParam("location") String location, - @RequestParam("department") String department, - @RequestParam("contractorname") String contractorName, - @RequestParam("contractorperiod") String contractorPeriod, - @RequestParam("fundsource") String fundSource, - @RequestParam("scheme") String scheme, - @RequestParam("category") String category, - @RequestParam("subcategory") String subCategory, - @RequestParam("estamount") String estAmount, - @RequestParam("techsanctiondate") String techSancDate, - @RequestParam("adminsanctiondate") String adminSancDate, - @RequestParam("tendercalldate") String tenderCallDate, - @RequestParam("tenderfinalizeddate") String tenderFinDate, - @RequestParam("loadate") String loaDate, - @RequestParam("agreementdate") String agreementDate, - @RequestParam("workorderdate") String workOrderDate, - @RequestParam("workcommenceddate") String workCommDate, - @RequestParam("adminsanctionfile") MultipartFile adminSanctionFile, - @RequestParam("loafile") MultipartFile loaFile, - @RequestParam("agreementfile") MultipartFile agreementFile, - @RequestParam("workorderfile") MultipartFile workOrderFile, - @RequestParam("iconicProject") Integer iconicProjectInt) { - try { - String adminSanFilePath = estimateService.saveFile(adminSanctionFile, "admin"); - String loaFilePath = estimateService.saveFile(loaFile, "loa"); - String agreementFilePath = estimateService.saveFile(agreementFile, "agreement"); - String workOrderFilePath = estimateService.saveFile(workOrderFile, "workorder"); - - Boolean iconicProject = (iconicProjectInt != null && iconicProjectInt == 1); - - // Convert date formats - String newestDate = convertDateFormat(estimateDate); - String newTechSancDate = convertDateFormat(techSancDate); - String newAdminSancDate = convertDateFormat(adminSancDate); - String newTenderCallDate = convertDateFormat(tenderCallDate); - String newTenderFinDate = convertDateFormat(tenderFinDate); - String newLoaDate = convertDateFormat(loaDate); - String newAgreementDate = convertDateFormat(agreementDate); - String newWorkOrderDate = convertDateFormat(workOrderDate); - String newWorkCommDate = convertDateFormat(workCommDate); - - // Call saveEstimate method and pass the Iconic Project field - int result = estimateService.saveEstimate(estimateNo, newestDate, zone, ward, projectName, iconicProject, location, - department, contractorName, contractorPeriod, fundSource, scheme, category, subCategory, estAmount, - newTechSancDate, newAdminSancDate, adminSanFilePath, newTenderCallDate, newTenderFinDate, newLoaDate, loaFilePath, - newAgreementDate, agreementFilePath, newWorkOrderDate, workOrderFilePath, newWorkCommDate); - - if (result > 0) { - return ResponseEntity.ok("Estimate saved successfully"); - } else { - return ResponseEntity.status(500).body("Failed to save estimate"); - } - } catch (Exception e) { - return ResponseEntity.status(500).body("Error saving estimate: " + e.getMessage()); - } - }*/ - - // Handle the form submission - - // To save ERP details in erp_works table - @PostMapping(value = "/saveERPForm", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity saveERPEstimate(@RequestParam("erpestno") String estimateNo, - @RequestParam("erpestdate") String estimateDate, - @RequestParam("erpzone") String zone, - @RequestParam("erpward") String ward, - @RequestParam("erpprojectname") String projectName, - @RequestParam("erplocation") String location, - @RequestParam("erpdepartment") String department, - @RequestParam(value = "iconicProject", required = false, defaultValue = "0") int iconicProject, // ✅ Receive int directly - @RequestParam("erpcontractorname") String contractorName, - @RequestParam("erpcontractorperiod") String contractorPeriod, - @RequestParam("erpfundsource") String fundSource, - @RequestParam("erpscheme") String scheme, - @RequestParam("erpcategory") String category, - @RequestParam("erpsubcategory") String subCategory, - @RequestParam("erpestamount") String estAmount, - @RequestParam("erptechsanctiondate") String techSancDate, - @RequestParam("erpadminsanctiondate") String adminSancDate, - @RequestParam("erptendercalldate") String tenderCallDate, - @RequestParam("erptenderfinalizeddate") String tenderFinDate, - @RequestParam("erploadate") String loaDate, - @RequestParam("erpagreementdate") String agreementDate, - @RequestParam("erpworkorderdate") String workOrderDate, - @RequestParam("erpworkcommenceddate") String workCommDate, - @RequestParam("erploafile") MultipartFile loaFile, - @RequestParam("erpagreementfile") MultipartFile agreementFile, - @RequestParam("erpworkorderfile") MultipartFile workOrderFile, - @RequestParam("erpadminsanctionfile") MultipartFile adminSanFile) { - try { - String adminSanFilePath = estimateService.saveFile(adminSanFile, "admin","erp"); - String loaFilePath = estimateService.saveFile(loaFile, "loa","erp"); - String agreementFilePath = estimateService.saveFile(agreementFile, "agreement","erp"); - String workOrderFilePath = estimateService.saveFile(workOrderFile, "workorder","erp"); - - // Debugging: Check what value is received from frontend - System.out.println("Received Iconic Project Value: " + iconicProject); - - // Convert date formats - String newestDate = convertDateFormat(estimateDate); - String newTechSancDate = convertDateFormat(techSancDate); - String newAdminSancDate = convertDateFormat(adminSancDate); - String newTenderCallDate = convertDateFormat(tenderCallDate); - String newTenderFinDate = convertDateFormat(tenderFinDate); - String newLoaDate = convertDateFormat(loaDate); - String newAgreementDate = convertDateFormat(agreementDate); - String newWorkOrderDate = convertDateFormat(workOrderDate); - String newWorkCommDate = convertDateFormat(workCommDate); - - // Call saveEstimate method and pass Iconic Project as int - int result = estimateService.saveERPEstimate(estimateNo, newestDate, zone, ward, projectName, iconicProject, location, - department, contractorName, contractorPeriod, fundSource, scheme, category, - subCategory, estAmount, newTechSancDate, newAdminSancDate, adminSanFilePath, - newTenderCallDate, newTenderFinDate, newLoaDate, loaFilePath, newAgreementDate, - agreementFilePath, newWorkOrderDate, workOrderFilePath, newWorkCommDate); - - if (result > 0) { - return ResponseEntity.ok("Estimate saved successfully"); - } else { - return ResponseEntity.status(500).body("Failed to save estimate"); - } - } catch (Exception e) { - return ResponseEntity.status(500).body("Error saving estimate: " + e.getMessage()); - } - } - - public static String convertDateFormat(String dateStr) { - try { - DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - - LocalDate date = LocalDate.parse(dateStr, oldFormat); - return date.format(newFormat); - } catch (DateTimeParseException e) { - System.err.println("Invalid date format: " + dateStr); - return null; - } - } - - @GetMapping("/fetchERPdetails") - public ResponseEntity> getERPEstimateDetails(@RequestParam String estimateNo) { - - if (estimateNo == null || estimateNo.isEmpty()) { - return ResponseEntity.badRequest().body(Map.of("error", "Estimate number cannot be empty")); - } - - Map details = estimateService.getERPEstimateDetails(estimateNo); - - System.out.println("iconic....."+details.get("iconic_project")); - details.put("status", "NonErp"); - - return ResponseEntity.ok(details); - } - - @GetMapping("/fetchnonerpdetails") - public ResponseEntity> getNonERPEstimateDetails(@RequestParam String estimateNo) { - - if (estimateNo == null || estimateNo.isEmpty()) { - return ResponseEntity.badRequest().body(Map.of("error", "Estimate number cannot be empty")); - } - - Map details = estimateService.getNonERPEstimateDetails(estimateNo); - - details.put("status", "NonErp"); - - System.out.println("iconic....."+details.get("iconic_project")); - - return ResponseEntity.ok( details); - } - - - @GetMapping("/getSchemeList") - public List> getSchemeList() { - return estimateService.getSchemeList(); - } - - @GetMapping("/getCategoryList") - public List> getCategoryList() { - return estimateService.getCategoryList(); - } - - @GetMapping("/getSubCategoryList") - public List> getSubCategoryList() { - return estimateService.getSubCategoryList(); - } - - @GetMapping("/getDepartmentList") - public List> getDepartmentList() { - return estimateService.getDepartmentList(); - } - - @GetMapping("/getSourceofFundList") - public List> getSourceofFundList() { - return estimateService.getSourceofFundList(); - } - - @PostMapping(value = "/updateEstimate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity updateEstimate(@RequestParam("estno") String estimateNo, - @RequestParam("estdate") String estimateDate, @RequestParam("zone") String zone, - @RequestParam("ward") String ward, @RequestParam("projectname") String projectName, - @RequestParam("location") String location, @RequestParam("department") String department, - @RequestParam(value = "nonErpIconicProject", required = false, defaultValue = "0") Integer iconicProject, - @RequestParam("contractorname") String contractorName, - @RequestParam("contractorperiod") String contractorPeriod, @RequestParam("fundsource") String fundSource, - @RequestParam("scheme") String scheme, @RequestParam("category") String category, - @RequestParam("subcategory") String subCategory, @RequestParam("estamount") String estAmount, - @RequestParam("techsanctiondate") String techSancDate, - @RequestParam("adminsanctiondate") String adminSancDate, - @RequestParam("tendercalldate") String tenderCallDate, - @RequestParam("tenderfinalizeddate") String tenderFinDate, @RequestParam("loadate") String loaDate, - @RequestParam("agreementdate") String agreementDate, @RequestParam("workorderdate") String workOrderDate, - @RequestParam("workcommenceddate") String workCommDate, @RequestParam("loafile") MultipartFile loaFile, - @RequestParam("agreementfile") MultipartFile agreementFile, - @RequestParam("workorderfile") MultipartFile workOrderFile, - @RequestParam("adminsanctionfile") MultipartFile adminSanFile, - @RequestParam(value = "reason", required = false) String reason, - @RequestParam(value = "remarks", required = false) String remarks, - @RequestParam(value = "projecttype", required = false) String projecttype, - @RequestParam(value = "govtfund", required = false) String govtfund, - @RequestParam(value = "specialcat", required = false) String specialcat, - @RequestParam(value = "filenumber", required = false) String filenumber) { - try { - - // ✅ Check if it is a Non-ERP estimate - boolean isNonERP = estimateNo.startsWith("M"); - - // ✅ Ensure iconic_project is updated only for Non-ERP estimates - if (!isNonERP) { - iconicProject = null; // Don't update for ERP - } - - System.out.println("adminsacfile:" + adminSanFile); - System.out.println("loa:" + loaFile); - System.out.println("agreementfile:" + agreementFile); - System.out.println("workfile : " + workOrderFile); - System.out.println("iconicProject..."+iconicProject); - - // Create a mutable HashMap to store parameters - Map updatedDetails = new HashMap<>(); - updatedDetails.put("estimate_no", estimateNo); - - // Directly convert estimateDate here - updatedDetails.put("estimate_date", convertDateFormat(estimateDate)); - updatedDetails.put("zone", zone); - updatedDetails.put("ward", ward); - updatedDetails.put("project_name", projectName); - updatedDetails.put("location", location); - updatedDetails.put("iconic_project", iconicProject); - updatedDetails.put("department", department); - updatedDetails.put("contractor_name", contractorName); - updatedDetails.put("contractor_period", contractorPeriod); - updatedDetails.put("fund_source", fundSource); - updatedDetails.put("scheme", scheme); - updatedDetails.put("category", category); - updatedDetails.put("sub_category", subCategory); - updatedDetails.put("est_amount", estAmount); - updatedDetails.put("tech_sanc_date", convertDateFormat(techSancDate)); - updatedDetails.put("admin_sanc_date", convertDateFormat(adminSancDate)); - updatedDetails.put("tender_call_date", convertDateFormat(tenderCallDate)); - updatedDetails.put("tender_fin_date", convertDateFormat(tenderFinDate)); - updatedDetails.put("loa_date", convertDateFormat(loaDate)); - updatedDetails.put("agreement_date", convertDateFormat(agreementDate)); - updatedDetails.put("work_order_date", convertDateFormat(workOrderDate)); - updatedDetails.put("work_comm_date", convertDateFormat(workCommDate)); - updatedDetails.put("reason", reason); - updatedDetails.put("remarks", remarks); - updatedDetails.put("projecttype", projecttype); - updatedDetails.put("govtfund", govtfund); - updatedDetails.put("specialcat", specialcat); - updatedDetails.put("filenumber", filenumber); - - // ✅ Only update iconic_project for Non-ERP - if (isNonERP) { - updatedDetails.put("iconic_project", iconicProject); - } - - String SanFilePath = estimateService.saveFile(adminSanFile, "sanction","nonerp"); - String loaFilePath = estimateService.saveFile(loaFile, "loa","nonerp"); - String agreementFilePath = estimateService.saveFile(agreementFile, "agreement","nonerp"); - String workOrderFilePath = estimateService.saveFile(workOrderFile, "workorder","nonerp"); - - // Call the service layer to update the estimate details - int isUpdated = estimateService.updateNonERPEstimateDetails(updatedDetails, SanFilePath, loaFilePath, - agreementFilePath, workOrderFilePath); - - if (isUpdated > 0) { - return ResponseEntity.ok("Estimate details updated successfully."); - } else { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update estimate."); - } - } catch (Exception e) { - e.printStackTrace(); // Log the error - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error updating estimate: " + e.getMessage()); - } - } - - // to update ERP works Detail from erp_works table - @PostMapping(value = "/updateERPEstimate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity updateEstimatelist(@RequestParam("erpestno") String estimateNo, - @RequestParam("erpestdate") String estimateDate, @RequestParam("erpzone") String zone, - @RequestParam("erpward") String ward, @RequestParam("erpprojectname") String projectName, - @RequestParam("erplocation") String location, @RequestParam("erpdepartment") String department, - @RequestParam(value = "iconicProject", required = false, defaultValue = "No") String iconicProjectStr, - @RequestParam("erpcontractorname") String contractorName, - @RequestParam("erpcontractorperiod") String contractorPeriod, @RequestParam("erpfundsource") String fundSource, - @RequestParam("erpscheme") String scheme, @RequestParam("erpcategory") String category, - @RequestParam("erpsubcategory") String subCategory, @RequestParam("erpestamount") String estAmount, - @RequestParam("erptechsanctiondate") String techSancDate, - @RequestParam("erpadminsanctiondate") String adminSancDate, - @RequestParam("erptendercalldate") String tenderCallDate, - @RequestParam("erptenderfinalizeddate") String tenderFinDate, @RequestParam("erploadate") String loaDate, - @RequestParam("erpagreementdate") String agreementDate, @RequestParam("erpworkorderdate") String workOrderDate, - @RequestParam("erpworkcommenceddate") String workCommDate, @RequestParam("erploafile") MultipartFile loaFile, - @RequestParam("erpagreementfile") MultipartFile agreementFile, - @RequestParam("erpworkorderfile") MultipartFile workOrderFile, - @RequestParam("erpadminsanctionfile") MultipartFile adminSanFile) { - try { - System.out.println("controller called"); - boolean iconicProject = "Yes".equalsIgnoreCase(iconicProjectStr); - System.out.println("adminsacfile:" + adminSanFile); - System.out.println("loa:" + loaFile); - System.out.println("agreementfile:" + agreementFile); - System.out.println("workfile : " + workOrderFile); - - - // Create a mutable HashMap to store parameters - Map updatedDetails = new HashMap<>(); - - updatedDetails.put("estimate_no", estimateNo); - - // Directly convert estimateDate here - updatedDetails.put("estimate_date", convertDateFormat(estimateDate)); - updatedDetails.put("zone", zone); - updatedDetails.put("ward", ward); - updatedDetails.put("project_name", projectName); - updatedDetails.put("location", location); - updatedDetails.put("iconic_project", iconicProject); - updatedDetails.put("department", department); - updatedDetails.put("contractor_name", contractorName); - updatedDetails.put("contractor_period", contractorPeriod); - updatedDetails.put("fund_source", fundSource); - updatedDetails.put("scheme", scheme); - updatedDetails.put("category", category); - updatedDetails.put("sub_category", subCategory); - updatedDetails.put("est_amount", estAmount); - updatedDetails.put("tech_sanc_date", convertDateFormat(techSancDate)); - updatedDetails.put("admin_sanc_date", convertDateFormat(adminSancDate)); - updatedDetails.put("tender_call_date", convertDateFormat(tenderCallDate)); - updatedDetails.put("tender_fin_date", convertDateFormat(tenderFinDate)); - updatedDetails.put("loa_date", convertDateFormat(loaDate)); - updatedDetails.put("agreement_date", convertDateFormat(agreementDate)); - updatedDetails.put("work_order_date", convertDateFormat(workOrderDate)); - updatedDetails.put("work_comm_date", convertDateFormat(workCommDate)); - - String SanFilePath = estimateService.saveFile(adminSanFile, "sanction","erp"); - String loaFilePath = estimateService.saveFile(loaFile, "loa","erp"); - String agreementFilePath = estimateService.saveFile(agreementFile, "agreement","erp"); - String workOrderFilePath = estimateService.saveFile(workOrderFile, "workorder","erp"); - - // Call the service layer to update the estimate details - int isUpdated = estimateService.updateEstimateDetails(updatedDetails, SanFilePath, loaFilePath, - agreementFilePath, workOrderFilePath); - - if (isUpdated > 0) { - return ResponseEntity.ok("Estimate details updated successfully."); - } else { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to update estimate."); - } - } catch (Exception e) { - e.printStackTrace(); // Log the error - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error updating estimate: " + e.getMessage()); - } - } - - @GetMapping("/getFilteredWorks") - @ResponseBody - public List> getFilteredWorks( - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam(required = false) String department, - @RequestParam(required = false) String fundsource, - @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, - @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, - @RequestParam(required = false) String filterType, - @RequestParam(required = false) String estno) { - System.out.println("estno: " + estno); - - return estimateService.getFilteredWorksList(zone, ward, department, fundsource, fromDate, toDate, filterType, estno); - } - - - //ak - @GetMapping("/getFilteredERpWorksList") - @ResponseBody - public List> getFilteredERpWorksList( - @RequestParam(required = false) String loginId, - @RequestParam(required = false) String finYear, - @RequestParam(required = false) String oValue) { - //System.out.println("estno: " + estno); - //System.out.println("check"); - - // Fetch all filtered works - List> filteredWorks = erpEstimateService.getFilteredERpWorksList(loginId,finYear,oValue); - - return filteredWorks; - } - - @GetMapping("/getFilteredERpWorksListByLogin") - @ResponseBody - public List> getFilteredERpWorksListByLogin( - @RequestParam(required = false) String loginId, - @RequestParam(required = false) String finYear, - @RequestParam(required = false) String oValue) { - //System.out.println("estno: " + estno); - //System.out.println("check"); - - // Fetch all filtered works - List> filteredWorks = erpEstimateService.getFilteredERpWorksListByLogin(loginId,finYear,oValue); - - return filteredWorks; - } - - @GetMapping("/getFilteredNonERpWorksListByLogin") - @ResponseBody - public List> getFilteredNonERpWorksListByLogin( - @RequestParam(required = false) String loginId, - @RequestParam(required = false) String zone, - @RequestParam(required = false) String ward, - @RequestParam(required = false) String department, - @RequestParam(required = false) String fundsource, - @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, - @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, - @RequestParam(required = false) String filterType, - @RequestParam(required = false) String estno) { - // Fetch all filtered works - List> filteredWorks = estimateService.getAllNonERPWorks(loginId); - - return filteredWorks; - } - - /*@GetMapping("/fetchdetailsWorklist") - public ResponseEntity> fetchdetailsWorklist(@RequestParam String estimateNo) { - System.out.println("abs_est_number"); - - if (estimateNo == null || estimateNo.isEmpty()) { - return ResponseEntity.badRequest().body(Map.of("error", "Estimate number cannot be empty")); - } - - Map response = new HashMap<>(); - Map details = new HashMap<>(); - details = estimateService.getEstimateDetails(estimateNo); - - - if (estimateNo.startsWith("M")) { - if (details == null) { - details = new HashMap<>(); - } - // fetch from local DB - details.put("status", "NonErp"); - } else { - response.put("status", "Erp"); - Map erpWorksDetails = erpEstimateService.getERPWorksDetailslist(estimateNo); // fetch from ERP - - if (erpWorksDetails != null && !erpWorksDetails.isEmpty()) { - - response.put("estimate_no", erpWorksDetails.getOrDefault("abs_est_number", "")); - response.put("estimate_date", erpWorksDetails.getOrDefault("asdate", "")); - response.put("zone", erpWorksDetails.getOrDefault("zone", "")); - - response.put("ward", erpWorksDetails.getOrDefault("wardname", "")); - response.put("department", erpWorksDetails.getOrDefault("zonename", "")); - - - response.put("project_name", erpWorksDetails.getOrDefault("nameofwork", "")); - response.put("location", erpWorksDetails.getOrDefault("location", "")); - response.put("contractor_period", erpWorksDetails.getOrDefault("agreementperiod", "")); - response.put("scheme", erpWorksDetails.getOrDefault("schemename", "")); - response.put("category", erpWorksDetails.getOrDefault("workcategory", "")); - response.put("sub_category", erpWorksDetails.getOrDefault("typeofwork", "")); - response.put("est_amount", erpWorksDetails.getOrDefault("valueofwork", "")); - } - - if (details != null && !details.isEmpty()) { - response.put("tech_sanc_date", details.get("tech_sanc_date")); - response.put("admin_sanc_date", details.get("admin_sanc_date")); - response.put("tender_fin_date", details.get("tender_fin_date")); - response.put("tender_call_date", details.get("tender_call_date")); - response.put("loa_date", details.get("loa_date")); - response.put("agreement_date", details.get("agreement_date")); - response.put("work_order_date", details.get("work_order_date")); - response.put("work_comm_date", details.get("work_comm_date")); - response.put("adm_san_file", details.get("adm_san_file")); - response.put("loa_file", details.get("loa_file")); - response.put("agreement_file", details.get("agreement_file")); - response.put("work_order_file", details.get("work_order_file")); - } - } - - - if(!details.isEmpty()){ - System.out.println("status2: "+details.get("status")); - } else{ - System.out.println("status1: "+response.get("status")); - } - - - return ResponseEntity.ok(!details.isEmpty() ? details : response); - }*/ - - - @GetMapping("/getERPWorksDetailsList") - public ResponseEntity> getERPWorksDetailsList(@RequestParam("estimateNo") String estimateNo) { - - System.out.println("ERP estNo: " + estimateNo); - - Map erpWorksDetails = erpEstimateService.getERPWorksDetails(estimateNo); // Fetch details from ERP - - if (erpWorksDetails.isEmpty()) { - return ResponseEntity.ok(Collections.singletonMap("message", "No Data Found")); - } - - System.out.println("erpWorksDetails.. "+erpWorksDetails); - return ResponseEntity.ok(erpWorksDetails); - } - - - //show the model details by using estimate number - - @GetMapping("/getestimatedetails") - public List> getEmployeedetailsbyCode( - @RequestParam String estimateCode) { - - List> estimateDetails = estimateService.fetchEstimateByCode(estimateCode); - System.out.println("estimateDetails==="+estimateDetails); - return estimateDetails; - } - - //save the work details mapping - - @PostMapping("/saveworkdetails") - public ResponseEntity saveWorkDetails(@RequestBody List> workDetails) { - List> savedDetails = estimateService.saveWorkDetailsbycode(workDetails); - return ResponseEntity.ok(savedDetails); - } - - @GetMapping("/reasonlist") - public ResponseEntity>> getAllReasons() { - List> reasons = estimateService.getAllReasons(); - return ResponseEntity.ok(reasons); - } - - @GetMapping("/getestimateworkdetails") - public List> getestimateworkdetails( - @RequestParam String estimateCode) { - - List> estimateDetails = estimateService.getestimateworkdetails(estimateCode); - System.out.println("estimateDetails==="+estimateDetails); - return estimateDetails; - } - - // Newly added for dynamic questions and answers - @GetMapping("/questions") - public ResponseEntity>> getQuestionsBySubCatId(@RequestParam("subCatId") int subCatId) { - List> questions = estimateService.getQuestionsBySubCatId(subCatId); - return ResponseEntity.ok(questions); - } - - - //get the subcategory id by name - - @GetMapping("/subcategory/id") - public ResponseEntity getSubCategoryId(@RequestParam("name") String name) { - Integer subCatId = estimateService.getSubCategoryIdByName(name); - if (subCatId != null) { - return ResponseEntity.ok(Map.of("subCatId", subCatId)); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Sub-Category not found"); - } - } - - // added by sanjay - - @GetMapping("/answerIdd") - public ResponseEntity>> getAnswerByIdd(@RequestParam("answerId") int answerId) { - System.out.println("answerID.." + answerId); - - // Initialize the list properly - List> newList = new ArrayList<>(); - - Map questionDetails = estimateService.getQuestionDetailsById(answerId); - - if (questionDetails != null && questionDetails.get("id") != null) { - String quesId = questionDetails.get("id").toString(); - System.out.println("quesId: " + quesId); - - List> answerDetails = estimateService.getAnsDetailsByQId(quesId); - - newList.add(questionDetails); - if (answerDetails != null) { - newList.addAll(answerDetails); - } - } - - return ResponseEntity.ok(newList); - } - - @PostMapping("/saveErplist") - public ResponseEntity saveAnswers(@RequestBody List> answers) { - estimateService.saveAnswers(answers); - - System.out.println("answers"+answers); - - return ResponseEntity.ok("Answers saved successfully!"); - } - - @GetMapping("/fetchErpData") - public ResponseEntity>> fetchEstimateData(@RequestParam String estimateNumber) { - System.out.println("I'm in fetch controller..."); - List> savedData = estimateService.getSavedData(estimateNumber); - System.out.println("savedData..."+savedData ); - return ResponseEntity.ok(savedData); - } - - - //// Balaji - @GetMapping("/getestimateworkdetailsById") - public List> getestimateworkdetailsById( - @RequestParam String estid) { - - List> estimateDetails = estimateService.getestimateworkdetailsById(estid); - System.out.println("estid==="+estid); - return estimateDetails; - } - - @PostMapping("/saveEstimateWorkDetails") - public ResponseEntity saveAnswers( - @RequestParam(value = "loginid", required = false) String loginid, - @RequestParam(value = "estid", required = true) String estid, - @RequestParam(value = "techSanctionDate", required = false) String techSanctionDate, - @RequestParam(value = "adminSanctionDate", required = false) String adminSanctionDate, - @RequestParam(value = "tenderCallDate", required = false) String tenderCallDate, - @RequestParam(value = "tenderFinalizedDate", required = false) String tenderFinalizedDate, - @RequestParam(value = "loaDate", required = false) String loaDate, - @RequestParam(value = "agreementDate", required = false) String agreementDate, - @RequestParam(value = "workOrderDate", required = false) String workOrderDate, - @RequestParam(value = "workCommencedDate", required = false) String workCommencedDate, - @RequestParam(value = "isiconic", required = true) String isiconic, - @RequestParam(value = "admin_sanction_file", required = true) MultipartFile admin_sanction_file, - @RequestParam(value = "loa_file", required = false) MultipartFile loa_file, - @RequestParam(value = "agreement_file", required = false) MultipartFile agreement_file, - @RequestParam(value = "work_order_file", required = false) MultipartFile work_order_file, - @RequestParam(value = "projecttype", required = false) String projecttype, - @RequestParam(value = "govtfund", required = false) String govtfund, - @RequestParam(value = "specialcat", required = false) String specialcat - ) { - estimateService.saveEstimateWorkDetails(loginid, estid, isiconic, admin_sanction_file, loa_file, agreement_file, work_order_file, - techSanctionDate,adminSanctionDate,tenderCallDate,tenderFinalizedDate, - loaDate,agreementDate,workOrderDate,workCommencedDate, - projecttype,govtfund,specialcat); - return ResponseEntity.ok("success"); - } - - @PostMapping("/updateEstimateWorkDetails") - public ResponseEntity saveUpdateAnswers( - @RequestParam(value = "loginid", required = false) String loginid, - @RequestParam(value = "estid", required = true) String estid, - @RequestParam(value = "techSanctionDate", required = false) String techSanctionDate, - @RequestParam(value = "adminSanctionDate", required = false) String adminSanctionDate, - @RequestParam(value = "tenderCallDate", required = false) String tenderCallDate, - @RequestParam(value = "tenderFinalizedDate", required = false) String tenderFinalizedDate, - @RequestParam(value = "loaDate", required = false) String loaDate, - @RequestParam(value = "agreementDate", required = false) String agreementDate, - @RequestParam(value = "workOrderDate", required = false) String workOrderDate, - @RequestParam(value = "workCommencedDate", required = false) String workCommencedDate, - @RequestParam(value = "isiconic", required = true) String isiconic, - @RequestParam(value = "admin_sanction_file", required = false) MultipartFile admin_sanction_file, - @RequestParam(value = "loa_file", required = false) MultipartFile loa_file, - @RequestParam(value = "agreement_file", required = false) MultipartFile agreement_file, - @RequestParam(value = "work_order_file", required = false) MultipartFile work_order_file, - @RequestParam(value = "projecttype", required = false) String projecttype, - @RequestParam(value = "govtfund", required = false) String govtfund, - @RequestParam(value = "specialcat", required = false) String specialcat - ) { - estimateService.updateEstimateWorkDetails(loginid, estid, isiconic, admin_sanction_file, loa_file, agreement_file, work_order_file, - techSanctionDate,adminSanctionDate,tenderCallDate,tenderFinalizedDate, - loaDate,agreementDate,workOrderDate,workCommencedDate, - projecttype,govtfund,specialcat); - return ResponseEntity.ok("success"); - } - - @GetMapping("/getUserEstWorkDetailsById") - public List> getUserEstWorkDetailsById( - @RequestParam String estid) { - - List> estimateDetails = estimateService.getUserEstWorkDetailsById(estid); - System.out.println("estid==="+estid); - return estimateDetails; - } - - @GetMapping("/getUserEstWorkStageDetailsByEstid") - public List> getUserEstWorkStageDetailsByEstid( - @RequestParam String estid) { - - List> estimateDetails = estimateService.getUserEstWorkStageDetailsByEstid(estid); - System.out.println("estid==="+estid); - return estimateDetails; - } - - // to save non ERP works - @PostMapping(value = "/nonerpForm", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity submitForm( - @RequestParam("estdate") String estimateDate, - @RequestParam("zone") String zone, - @RequestParam("ward") String ward, - @RequestParam("projectname") String projectName, - @RequestParam("location") String location, - @RequestParam("department") String department, - @RequestParam("contractorname") String contractorName, - @RequestParam("contractorperiod") String contractorPeriod, - @RequestParam("fundsource") String fundSource, - @RequestParam("scheme") String scheme, - @RequestParam("category") String category, - @RequestParam("subcategory") String subCategory, - @RequestParam("estamount") String estAmount, - @RequestParam("techsanctiondate") String techSancDate, - @RequestParam("adminsanctiondate") String adminSancDate, - @RequestParam("tendercalldate") String tenderCallDate, - @RequestParam("tenderfinalizeddate") String tenderFinDate, - @RequestParam("loadate") String loaDate, - @RequestParam("agreementdate") String agreementDate, - @RequestParam("workorderdate") String workOrderDate, - @RequestParam("workcommenceddate") String workCommDate, - @RequestParam("loafile") MultipartFile loacopy, - @RequestParam("agreementfile") MultipartFile agreementcopy, - @RequestParam("workorderfile") MultipartFile workordercopy, - @RequestParam("adminsanctionfile") MultipartFile sanctioncopy, - @RequestParam("iconicProject") Integer iconicProjectInt, - @RequestParam("reason") String reason, - @RequestParam(value = "remarks", required = false) String remarks, - @RequestParam(value = "loginid", required = false) String loginid, - @RequestParam(value = "projecttype", required = false) String projecttype, - @RequestParam(value = "govtfund", required = false) String govtfund, - @RequestParam(value = "specialcat", required = false) String specialcat, - @RequestParam(value = "filenumber", required = false) String filenumber) { // ✅ Make remarks optional - - Boolean iconicProject = (iconicProjectInt != null && iconicProjectInt == 1); - Map response = new HashMap<>(); - - - // Ensure remarks is NULL when reason is not "Other" - if (!"Other".equals(reason)) { - remarks = null; - } - - try { - // ✅ Generate Estimate Number - int currentYear = LocalDate.now().getYear(); - int previousYear = currentYear - 1; - String suffixYear = String.valueOf(currentYear).substring(2); - String prefix = department.substring(0, 1); - System.out.println("prefix: " + prefix); - - int currentMonth= LocalDate.now().getMonthValue(); - if(currentMonth>3) { - previousYear = currentYear; - int suffixYearint = currentYear + 1; - suffixYear = String.valueOf(suffixYearint).substring(2); - } - - // Retrieve sequence from DB - //String sequenceStr = estimateService.getSequence(); - //int sequence = Integer.parseInt(sequenceStr) + 1; - //String estNo = "M" + prefix + "/" + previousYear + "-" + suffixYear + "/" + sequence; - //System.out.println("estNo: " + estNo); - String estNo = "M" + prefix + "/" + previousYear + "-" + suffixYear + "/"; - - // ✅ Save File Paths - String SanFilePath = estimateService.saveFile(sanctioncopy, "sanction","nonerp"); - String loaFilePath = estimateService.saveFile(loacopy, "loa","nonerp"); - String agreementFilePath = estimateService.saveFile(agreementcopy, "agreement","nonerp"); - String workOrderFilePath = estimateService.saveFile(workordercopy, "workorder","nonerp"); - - // ✅ Convert Dates - String newestDate = estimateService.convertDateFormat(estimateDate); - String newtechSancDate = estimateService.convertDateFormat(techSancDate); - String newadminSancDate = estimateService.convertDateFormat(adminSancDate); - String newtenderCallDate = estimateService.convertDateFormat(tenderCallDate); - String newtenderFinDate = estimateService.convertDateFormat(tenderFinDate); - String newloaDate = estimateService.convertDateFormat(loaDate); - String newagreementDate = estimateService.convertDateFormat(agreementDate); - String newworkOrderDate = estimateService.convertDateFormat(workOrderDate); - String newworkCommDate = estimateService.convertDateFormat(workCommDate); - - // ✅ Fix: If reason is "Insufficient Fund", set remarks to NULL - if (!"Other".equals(reason)) { - remarks = null; - } - - // ✅ Save to DB - String result = estimateService.processFormData(estNo, newestDate, zone, ward, iconicProject, projectName, location, - department, contractorName, contractorPeriod, fundSource, scheme, category, subCategory, estAmount, - newtechSancDate, newadminSancDate, SanFilePath, newtenderCallDate, newtenderFinDate, newloaDate, - loaFilePath, newagreementDate, agreementFilePath, newworkOrderDate, workOrderFilePath, newworkCommDate, reason, remarks, loginid, - projecttype, govtfund, specialcat, filenumber); - - if (!result.equals("error")) { - //estimateService.updateSequence(String.valueOf(result)); - response.put("message", "Estimate saved successfully"); - response.put("estNo", result); - return ResponseEntity.ok(response); - } else { - response.put("error", "Failed to save estimate"); - return ResponseEntity.status(500).body(response); - } - } catch (Exception e) { - response.put("error", "Error saving estimate: " + e.getMessage()); - return ResponseEntity.status(500).body(response); - } - } - //getProjectList - @GetMapping("/getProjectList") - public ResponseEntity>> getProjectList() { - List> reasons = estimateService.getProjectList(); - return ResponseEntity.ok(reasons); - } - @GetMapping("/getProjectUpdatedList") - public ResponseEntity>> getProjectUpdatedList(@RequestParam(value = "loginid", required = false) String loginid) { - List> reasons = estimateService.getProjectUpdatedList(loginid); - return ResponseEntity.ok(reasons); - } - - - @PostMapping(value = "/saveProjectStatus", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity saveProjectStatus( - @RequestParam("pid") String pid, - @RequestParam("status") String status, - @RequestParam("loginid") String loginid, - @RequestParam(value = "projectfile", required = false) MultipartFile projectfile - ) { // ✅ Make remarks optional - - Map response = new HashMap<>(); - - try { - - // ✅ Save File Paths - String file = estimateService.saveFile(projectfile, pid, "projectStatus"); - - // ✅ Save to DB - int result = estimateService.saveProjectData(pid, status, file, loginid); - - if (result>0) { - //estimateService.updateSequence(String.valueOf(result)); - response.put("message", "Project status saved successfully"); - //response.put("estNo", result); - return ResponseEntity.ok(response); - } else { - response.put("error", "Failed to save project status"); - return ResponseEntity.status(500).body(response); - } - } catch (Exception e) { - response.put("error", "Error saving project status: " + e.getMessage()); - return ResponseEntity.status(500).body(response); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/MainController.java deleted file mode 100644 index 1aa33364..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/MainController.java +++ /dev/null @@ -1,225 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works.controller; - -import java.util.*; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; -import in.gov.chennaicorporation.gccoffice.works.service.ERPEstimateService; -import in.gov.chennaicorporation.gccoffice.works.service.EstimateService; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -@RequestMapping("/gcc/works") -@Controller("worksController") -public class MainController { - private String BasePath = "modules/works/"; - - @Autowired - private EstimateService estimateService; - @Autowired - private ERPEstimateService erpestimateService; - - private Map> zoneWardMap = new HashMap<>(); - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return BasePath+"index"; - } - - @GetMapping("/erp-works-update") // not in use - public String CreateRequest(Model model) { - List zones = new ArrayList<>(zoneWardMap.keySet()); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - model.addAttribute("zones", zones); - return BasePath+"erp-works-update"; - } - - @GetMapping("/nonerp-works-add") - public String nonErpCreateRequest(Model model) { - //List zones = new ArrayList<>(); - List zones = new ArrayList<>(zoneWardMap.keySet()); - System.out.println("zones: " + zones); - - List> reasons = estimateService.getAllReasons(); - model.addAttribute("reasons", reasons); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId", LoginUserId); - - model.addAttribute("zones", zones); - return BasePath+"non-erp-works-add"; - } - - public MainController() { - zoneWardMap.put("00", generateWardList("000", "000")); - zoneWardMap.put("01", generateWardList("001", "014")); - zoneWardMap.put("02", generateWardList("015", "021")); - zoneWardMap.put("03", generateWardList("022", "033")); - zoneWardMap.put("04", generateWardList("034", "048")); - zoneWardMap.put("05", generateWardList("049", "063")); - zoneWardMap.put("06", generateWardList("064", "078")); - zoneWardMap.put("07", generateWardList("079", "093")); - zoneWardMap.put("08", generateWardList("094", "108")); - zoneWardMap.put("09", generateWardList("109", "126")); - zoneWardMap.put("10", generateWardList("127", "142")); - zoneWardMap.put("11", generateWardList("143", "155")); - zoneWardMap.put("12", generateWardList("156", "167")); - zoneWardMap.put("13", generateWardList("168", "180")); - zoneWardMap.put("14", generateWardList("181", "191")); - zoneWardMap.put("15", generateWardList("192", "200")); - } - - private List generateWardList(String startStr, String endStr) { - int start = Integer.parseInt(startStr); - int end = Integer.parseInt(endStr); - List wards = new ArrayList<>(); - for (int i = start; i <= end; i++) { - wards.add(String.format("%03d", i)); - } - return wards; - } - - @GetMapping("/wards") - @ResponseBody - public List getWards(@RequestParam String zone) { - return zoneWardMap.getOrDefault(zone, Collections.emptyList()); - } - //ak - - - @GetMapping("/erpworkslist") // To diplay updated ERP works - public String worksList(Model model) { - //List zones = new ArrayList<>(zoneWardMap.keySet()); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - //List> workDetails = estimateService.getAllERPWorks(LoginUserId); - - //model.addAttribute("workDetails", workDetails); - //model.addAttribute("zones", zones); - return BasePath+"erpworkslist"; - } - - @GetMapping("/erpworkslist_report") // To diplay updated ERP works - public String erpworkslist_report(Model model) { - //List zones = new ArrayList<>(zoneWardMap.keySet()); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - //List> workDetails = estimateService.getAllERPWorks(LoginUserId); - - //model.addAttribute("workDetails", workDetails); - //model.addAttribute("zones", zones); - return BasePath+"erpworkslist_report"; - } - - @GetMapping("/nonerpworkslist") // To display updated Non-ERP Works - public String nonerpworksList(Model model) { - List zones = new ArrayList<>(zoneWardMap.keySet()); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - List> workDetails = estimateService.getAllNonERPWorks(LoginUserId); - - model.addAttribute("workDetails", workDetails); - model.addAttribute("zones", zones); - return BasePath+"nonerpworkslist"; - } - - ////////////////////////////////////////////////////////////// - - @GetMapping("/erpWorksList") // to update ERP Works - public String erpworksList(Model model) { - List zones = new ArrayList<>(zoneWardMap.keySet()); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - //List> workDetails = erpestimateService.getAllWorks(LoginUserId); - - //model.addAttribute("workDetails", workDetails); - model.addAttribute("zones", zones); - return BasePath+"erp-works-list"; - } - - - @GetMapping("/view-works-details-modal") - public String worksViewModal(Model model,@RequestParam(value="estid", required = false) String estid) { - System.out.println("EST ID: "+estid); - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("estid",estid); - return BasePath+"works_details_view_modal_page"; - } - - @GetMapping("/update-works-details-modal") - public String worksUpdateModal(Model model,@RequestParam(value="estid", required = false) String estid) { - System.out.println("EST ID: "+estid); - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("estid",estid); - return BasePath+"works_details_update_modal_page"; - } - - @GetMapping("/user-view-works-details-modal") - public String userworksViewModal(Model model,@RequestParam(value="estid", required = false) String estid) { - System.out.println("EST ID: "+estid); - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("estid",estid); - return BasePath+"user_works_details_view_modal_page"; - } - - @GetMapping("/user-update-works-details-modal") - public String userworksUpdateModal(Model model,@RequestParam(value="estid", required = false) String estid) { - System.out.println("EST ID: "+estid); - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("estid",estid); - return BasePath+"user_works_details_update_modal_page"; - } - - @GetMapping("/update_works_stage_modal") - public String updateWorksStageModal(Model model,@RequestParam(value="estid", required = false) String estid) { - System.out.println("EST ID: "+estid); - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("estid",estid); - return BasePath+"update_works_stage_modal"; - } - - @GetMapping("/edit_stage_modal") - public String editStageModal(Model model,@RequestParam(value="estid", required = false) String estid, - @RequestParam(value="tmid", required = false) String tmid) { - System.out.println("EST ID: "+estid); - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("estid",estid); - model.addAttribute("tmid",tmid); - return BasePath+"edit_stage_modal"; - } - - @GetMapping("/update_project_status") - public String updateProjectStatus(Model model) { - List> projectList = estimateService.getProjectList(); - model.addAttribute("projects", projectList); - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - return BasePath+"project_status_update"; - } - -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/package-info.java deleted file mode 100644 index 040b9e84..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/package-info.java deleted file mode 100644 index 343a03b3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/ERPEstimateService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/ERPEstimateService.java deleted file mode 100644 index 965f334f..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/ERPEstimateService.java +++ /dev/null @@ -1,361 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.core.env.Environment; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.ArrayList; - -import javax.sql.DataSource; - -import java.time.LocalDate; -import java.util.List; -import java.util.Map; - -@Service -public class ERPEstimateService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private JdbcTemplate oraclejdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlWorksDataSource") DataSource dataSource, - @Qualifier("oracleDataSource") DataSource oracleDataSource) { - - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.oraclejdbcTemplate = new JdbcTemplate(oracleDataSource); - } - - @Autowired - private Environment environment; - - private String getUserAccess(String userid) { - String ward = "0"; - String department="0"; - - String sql = "SELECT `id`, `userid`, `zone`, `ward`, `department` FROM `works_access` WHERE `userid`=? LIMIT 1"; - System.out.println("SELECT `id`, `userid`, `zone`, `ward` FROM `works_access` WHERE `userid`="+userid+" LIMIT 1"); - List> taskresult = jdbcTemplate.queryForList(sql, userid); - if(!taskresult.isEmpty()) { - ward = ""+taskresult.get(0).get("ward"); - department = ""+taskresult.get(0).get("department"); - } - return ward+"_"+department; - } - - @Transactional - public String getDepartmentName(String ids) { - String dataarray="0"; - String sqlQuery ="SELECT GROUP_CONCAT(CONCAT(\"'\", `dept_name`, \"'\") SEPARATOR ',') AS `dept_name` FROM `department_master` WHERE `id` IN (?)"; - List> result = jdbcTemplate.queryForList(sqlQuery, ids); - if(!result.isEmpty()) { - dataarray = ""+result.get(0).get("dept_name"); - } - return dataarray; - } - - @Transactional - public String getDepartmentId(String names) { - String ids="0"; - String sqlQuery ="SELECT GROUP_CONCAT( `id` SEPARATOR ',') AS `id` FROM `department_master` WHERE `dept_name` IN (?)"; - List> result = jdbcTemplate.queryForList(sqlQuery, names); - if(!result.isEmpty()) { - ids = ""+result.get(0).get("id"); - } - return ids; - } - - public List> getAllWorks(String LoginUserId) { - - String accessData = getUserAccess(LoginUserId); - String where=""; - - // Split the string using "_" - String[] parts = accessData.split("_"); - - if(!parts[0].equals("all")) { - where =" cd.`WARD` IN ("+parts[0]+") "; - } - if(!parts[1].equals("all")) { - if(!where.equals("")) - { - where = where + "AND cd.`DEPARTMENT_NAME` IN ("+getDepartmentName(parts[1])+")"; - } - else { - where = where + "cd.`DEPARTMENT_NAME` IN ("+getDepartmentName(parts[1])+")"; - } - } - - if(!where.equals("")) { - where = " WHERE "+ where; - } - - System.out.println("where = " + where); - - String sql = "select *, wt.code as category, tw.code as subcategory, sm.name as scheme, dm.dept_name as department, fm.name as fundsourcename " + - "from works_data_erp cd " + - "left join gcc_works_status.workstype_master wt on wt.id = cd.CATEGORY " + - "left join gcc_works_status.typeofwork_master tw on tw.id = cd.SUB_CATEGORY " + - "left join gcc_works_status.scheme_master sm on sm.id = cd.SCHEME " + - "left join gcc_works_status.department_master dm on dm.id = cd.ZONE " + - "left join gcc_works_status.fundsource_master fm on fm.id = cd.FUND_SOURCE" - + where; - return jdbcTemplate.queryForList(sql); - } - - public Map getERPWorksDetails(String estNo) { // changed - String sql = "select *, wt.code as category, tw.code as subcategory, sm.name as scheme, dm.dept_name as department, fm.name as fundsourcename " + - "from works_data_erp cd " + - "left join gcc_works_status.workstype_master wt on wt.id = cd.CATEGORY " + - "left join gcc_works_status.typeofwork_master tw on tw.id = cd.SUB_CATEGORY " + - "left join gcc_works_status.scheme_master sm on sm.id = cd.SCHEME " + - "left join gcc_works_status.department_master dm on dm.id = cd.ZONE " + - "left join gcc_works_status.fundsource_master fm on fm.id = cd.FUND_SOURCE " + - "where cd.ESTIMATE_NO = ? LIMIT 1"; - return jdbcTemplate.queryForMap(sql, estNo); - } - - public Map getERPWorksDetailslist(String estimateNo) { - System.out.println(estimateNo); - String sql = "select * from works_data_erp where `ESTIMATE_NO` = ?"; - return jdbcTemplate.queryForMap(sql, estimateNo); - } - - public List> getFilteredERpWorksList( - String loginId, - String finYear, String oValue) { - StringBuilder sql = new StringBuilder("SELECT * FROM works_data_erp"); - System.out.println("hai"); - List params = new ArrayList<>(); - List conditions = new ArrayList<>(); - - // Load only status = 0 - conditions.add(" `isuserupdate` = ?"); - params.add(0); - ////////////////////// - - String accessData = getUserAccess(loginId); - String where=""; - - // Split the string using "_" - String[] parts = accessData.split("_"); - - if(!parts[0].equals("all")) { - where =" `WARD` IN ("+parts[0]+") "; - } - - if(!parts[1].equals("all")) { - if(!where.equals("")) - { - where = where + "AND `DEPARTMENT_NAME` IN ("+getDepartmentName(parts[1])+")"; - } - else { - where = where + "`DEPARTMENT_NAME` IN ("+getDepartmentName(parts[1])+")"; - } - } - - if(!where.equals("")) { - conditions.add(" " + where + " "); - } - - System.out.println("where = " + where); - - /* - * if (zone != null && !zone.isEmpty()) { conditions.add("zone = ?"); - * params.add(zone); } - */ - - if (finYear != null && !finYear.isEmpty()) { - conditions.add(" ESTIMATE_NO LIKE ? "); - params.add("%" + finYear + "%"); - } - - if (oValue != null && !oValue.isEmpty()) { - switch (oValue) { - case "max50": - conditions.add(" EST_VAL_WITH_OH <= ?"); - params.add(5000000); - break; - case "50to75": - conditions.add(" EST_VAL_WITH_OH > ? AND EST_VAL_WITH_OH <= ?"); - params.add(5000000); - params.add(7500000); - break; - case "75to99": - conditions.add(" EST_VAL_WITH_OH > ? AND EST_VAL_WITH_OH <= ?"); - params.add(7500000); - params.add(9900000); - break; - case "min1c": - conditions.add(" EST_VAL_WITH_OH >= ?"); - params.add(10000000); - break; - } - } - /* - if (fundsource != null && !fundsource.isEmpty()) { - conditions.add(" fund_source = ?"); - params.add(fundsource); - } - if (fromDate != null && toDate != null) { - conditions.add("date(asdate) between ? and ?"); - params.add(fromDate); - params.add(toDate); - } - /* - * if (toDate != null) { conditions.add("asdate <= ?"); params.add(toDate); } - */ - - /* - * if (filterType != null && filterType.equals("erpWorks")) { - * conditions.add("abs_est_number not like'M%'"); } - * - * if (filterType != null && filterType.equals("nonErpWorks")) { - * conditions.add("abs_est_number like'M%'"); } - */ - /* - if (estno != null && !estno.isEmpty()) { - conditions.add("abs_est_number = ?"); - params.add(estno); - } - */ - - // Append conditions only if there are any - if (!conditions.isEmpty()) { - sql.append(" WHERE ").append(String.join(" AND ", conditions)); - } - - //System.out.println("SELECT * FROM works_data_erp WHERE `isuserupdate` = 0 AND ESTIMATE_NO LIKE '%" + finYear + "%' AND EST_VAL_WITH_OH >= 5000000"); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - public List> getFilteredERpWorksListByLogin( - String loginId, - String finYear, String oValue) { - StringBuilder sql = new StringBuilder("SELECT ew.`estid`, ew.`estimate_no`, DATE(ew.`estimate_date`) AS `estimate_date`," - + "ew.`zone`, ew.`ward`, dm.dept_name as `department`, wm.name as `category`, " - + "trim(tm.description) as `sub_category`, ew.`project_name`, ew.`estimation_amount`, ew.`est_val_with_oh` FROM erp_works ew " - + "LEFT JOIN department_master dm ON dm.id = ew.department " - + "LEFT JOIN workstype_master wm ON wm.id = ew.category " - + "LEFT JOIN typeofwork_master tm ON tm.id = ew.sub_category"); - //System.out.println("hai"); - List params = new ArrayList<>(); - List conditions = new ArrayList<>(); - - // Load only status = 0 - //conditions.add(" `isuserupdate` = ?"); - //params.add(0); - ////////////////////// - - String accessData = getUserAccess(loginId); - - String where="ew.`nonerp`=0 "; - - // Split the string using "_" - String[] parts = accessData.split("_"); - - if(!parts[0].equals("all")) { - where = where + " AND ew.`ward` IN ("+parts[0]+") "; - } - if(!parts[1].equals("all")) { - if(!where.equals("")) - { - where = where + " AND `dm`.`dept_name` IN ("+getDepartmentName(parts[1])+")"; - } - else { - where = where + " AND`dm`.`dept_name` IN ("+getDepartmentName(parts[1])+")"; - } - } - - if(!where.equals("")) { - conditions.add(" " + where + " "); - } - - System.out.println("where = " + where); - - /* - * if (zone != null && !zone.isEmpty()) { conditions.add("zone = ?"); - * params.add(zone); } - */ - if (finYear != null && !finYear.isEmpty()) { - conditions.add(" ew.estimate_no LIKE ? "); - params.add("%" + finYear + "%"); - } - - if (oValue != null && !oValue.isEmpty()) { - switch (oValue) { - case "max50": - conditions.add(" ew.`est_val_with_oh` <= ?"); - params.add(5000000); - break; - case "50to75": - conditions.add(" ew.`est_val_with_oh` > ? AND ew.`est_val_with_oh` <= ?"); - params.add(5000000); - params.add(7500000); - break; - case "75to99": - conditions.add(" ew.`est_val_with_oh` > ? AND ew.`est_val_with_oh` <= ?"); - params.add(7500000); - params.add(9900000); - break; - case "min1c": - conditions.add(" ew.`est_val_with_oh` >= ?"); - params.add(10000000); - break; - } - } - /* - if (ward != null && !ward.isEmpty()) { - conditions.add(" wardname = ?"); - params.add(ward); - } - if (department != null && !department.isEmpty()) { - conditions.add(" zonename = ?"); - params.add(department); - } - if (fundsource != null && !fundsource.isEmpty()) { - conditions.add(" fund_source = ?"); - params.add(fundsource); - } - if (fromDate != null && toDate != null) { - conditions.add("date(asdate) between ? and ?"); - params.add(fromDate); - params.add(toDate); - } - - if (estno != null && !estno.isEmpty()) { - conditions.add("abs_est_number = ?"); - params.add(estno); - } - */ - // Append conditions only if there are any - if (!conditions.isEmpty()) { - sql.append(" WHERE ").append(String.join(" AND ", conditions)); - } - - - //System.out.println("sql: " + sql + "fromDate: " + fromDate + "toDate: " + toDate); - //System.out.println(sql.toString()); - // return jdbcTemplate.queryForList(sql.toString()+" LIMIT 100", params.toArray()); - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - public Map getNonERPWorksDetails(String estimateNo) { // changed - String sql = "select *, wt.code as category, tw.code as subcategory, sm.name as scheme, dm.dept_name as department, fm.name as fundsourcename " + - "from tbl_cmdashboard cd " + - "left join gcc_works_status.workstype_master wt on wt.id = cd.workcategory " + - "left join gcc_works_status.typeofwork_master tw on tw.id = cd.typeofwork " + - "left join gcc_works_status.scheme_master sm on sm.id = cd.schemename " + - "left join gcc_works_status.department_master dm on dm.id = cd.zonename " + - "left join gcc_works_status.fundsource_master fm on fm.id = cd.fundsource " + - "where cd.abs_est_number = ? "; - return jdbcTemplate.queryForMap(sql, estimateNo); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/EstimateService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/EstimateService.java deleted file mode 100644 index bd5d6313..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/EstimateService.java +++ /dev/null @@ -1,1693 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works.service; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; -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.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; - -import javax.sql.DataSource; - -import java.nio.file.Files; -import java.io.IOException; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ClassPathResource; - -import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; -import org.springframework.core.env.Environment; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -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.web.multipart.MultipartFile; -@Service -public class EstimateService { - @Autowired - private Environment environment; - private String fileBaseUrl; - - @Autowired - private JdbcTemplate jdbcTemplate; - - @Autowired - private JdbcTemplate oraclejdbcTemplate; - - 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("mysqlWorksDataSource") DataSource dataSource, - @Qualifier("oracleDataSource") DataSource oracleDataSource) { - - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.oraclejdbcTemplate = new JdbcTemplate(oracleDataSource); - 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(); - } - - 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(); - } - - //save file and get path - public String saveFile(MultipartFile file, String fileCat, String type_folder) throws IOException { - - String order_copy_url = ""; - type_folder = "works/"+type_folder; - // Handle file upload if a file is provided - if (file == null || file.isEmpty()) { - return order_copy_url; - } - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("gcc_works"); - var year =DateTimeUtil.getCurrentYear(); - var month =DateTimeUtil.getCurrentMonth(); - //var date =DateTimeUtil.getCurrentDay(); - - uploadDirectory = uploadDirectory + serviceFolderName + "/" + type_folder + "/" + year + "/" + month; - - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String datetimetxt = DateTimeUtil.getCurrentDateTime(); - - String fileName = fileCat + "_"+ datetimetxt +"_"+generateRandomStringForFile(10) +"_" + file.getOriginalFilename(); - // Construct the file path - String filepath = uploadDirectory + "/" + fileName; - String filepath_txt = "/" + serviceFolderName + "/" + type_folder + "/" + year + "/" + month + "/" + fileName; - - Path path = Paths.get(filepath); - - // Ensure the directory exists - Files.createDirectories(path.getParent()); - - // Write the file to the specified path - Files.write(path, file.getBytes()); - - // Set the order_copy_url to the relative file path for storing in DB - order_copy_url = filepath_txt; - - return order_copy_url; - } - -/* - public int saveEstimate(String estimateNo, String estimateDate, String zone, String ward, String projectName, - boolean iconicProject, String location, String department, String contractorName, - String contractorPeriod, String fundSource, String scheme, String category, - String subCategory, String estAmount, String techSancDate, String adminSancDate, - String admSanFile, String tenderCallDate, String tenderFinDate, String loaDate, - String loaFile, String agreementDate, String agreementFile, String workOrderDate, - String workOrderFile, String workCommDate) { - - String sql = "INSERT INTO gcc_wroks_status.erp_works (estimate_no, estimate_date, zone, ward, project_name, location, " + - "department, contractor_name, contractor_period, fund_source, scheme, category, sub_category, " + - "estimatio_amount, technical_sanction_date, admin_sanction_date, admin_sanction_file, tender_called_date, " + - "tender_finalized_date, loa_date, " + - "loa_file, agreement_date, agreement_file, work_order_date, work_order_file, work_commenced_date,isiconic) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, estimateNo, estimateDate, zone, ward, projectName, location, department, - contractorName, contractorPeriod, fundSource, scheme, category, subCategory, estAmount, techSancDate, - adminSancDate, admSanFile, tenderCallDate, tenderFinDate, loaDate, loaFile, agreementDate, agreementFile, - workOrderDate, workOrderFile, workCommDate, iconicProject); - } -*/ - public String processFormData( - String estimateNo, String estimateDate, String zone, String ward, Boolean iconicProject, - String projectName, String location, String department, String contractorName, - String contractorPeriod, String fundSource, String scheme, String category, - String subCategory, String estAmount, String techSancDate, String adminSancDate, - String sanFilePath, String tenderCallDate, String tenderFinDate, String loaDate, - String loaFilePath, String agreementDate, String agreementFilePath, - String workOrderDate, String workOrderFilePath, String workCommDate, - String reason, String remarks, String loginid, - String projecttype, String govtfund, String specialcat, String filenumber) { - - // 🔍 Validate mandatory fields - if (estimateNo == null || estimateNo.isEmpty() || estimateDate == null || estimateDate.isEmpty() - || projectName == null || projectName.isEmpty()) { - throw new IllegalArgumentException("Mandatory fields are missing!"); - } - - if ("Other".equals(reason)) { - // ✅ Store "Other" in reason and the entered value in remarks - if (remarks == null || remarks.trim().isEmpty()) { - throw new IllegalArgumentException("Remarks cannot be empty when reason is 'Other'"); - } - } else { - // ✅ If a predefined reason is selected, store it in reason and make remarks NULL - remarks = null; - } - - String remarks_txt = remarks; - - // ✅ SQL Query - String sqlQuery = "INSERT INTO gcc_works_status.non_erp_works (estimate_no, estimate_date, zone, ward, isiconic, project_name, location, " + - "department, contractor_name, contractor_period, fund_source, scheme, category, sub_category, " + - "estimation_amount, technical_sanction_date, admin_sanction_date, admin_sanction_file, tender_called_date, tender_finalized_date, " + - "loa_date, loa_file, agreement_date, agreement_file, work_order_date, work_order_file, work_commenced_date, reason, remarks," - + "project_type, govt_funded_project, special_category, filenumber) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "?, ?, ?, ?)"; - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - int affectedRows = jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"estid"}); - ps.setString(1, estimateNo); - ps.setString(2, estimateDate); - ps.setString(3, zone); - ps.setString(4, ward); - ps.setInt(5, (iconicProject != null && iconicProject) ? 1 : 0); // ✅ Convert Boolean to INT - ps.setString(6, projectName); - ps.setString(7, location); - ps.setString(8, department); - ps.setString(9, contractorName); - ps.setString(10, contractorPeriod); - ps.setString(11, fundSource); - ps.setString(12, scheme); - ps.setString(13, category); - ps.setString(14, subCategory); - ps.setString(15, estAmount); - ps.setString(16, techSancDate); - ps.setString(17, adminSancDate); - ps.setString(18, sanFilePath); - ps.setString(19, tenderCallDate); - ps.setString(20, tenderFinDate); - ps.setString(21, loaDate); - ps.setString(22, loaFilePath); - ps.setString(23, agreementDate); - ps.setString(24, agreementFilePath); - ps.setString(25, workOrderDate); - ps.setString(26, workOrderFilePath); - ps.setString(27, workCommDate); - ps.setString(28, reason); - ps.setString(29, remarks_txt); - ps.setString(30, projecttype); - ps.setString(31, govtfund); - ps.setString(32, specialcat); - ps.setString(33, filenumber); - return ps; - }, keyHolder); - - String estNo = "error"; - - if(affectedRows>0) { - int lastInsertId = (int) keyHolder.getKey().longValue(); - int currentYear = LocalDate.now().getYear(); - int previousYear = currentYear - 1; - String suffixYear = String.valueOf(currentYear).substring(2); - String prefix = department.substring(0, 1); - - estNo = "M" + prefix + "/" + previousYear + "-" + suffixYear + "/" + lastInsertId; - // Update the petition number in the database - updateESTno(lastInsertId, estNo); - - // ✅ Construct SQL Query with Actual Values (For Logging) - String formattedSql = String.format( - "INSERT INTO gcc_works_status.non_erp_works (estimate_no, estimate_date, zone, ward, isiconic, project_name, location, " + - "department, contractor_name, contractor_period, fund_source, scheme, category, sub_category, " + - "estimation_amount, technical_sanction_date, admin_sanction_date, admin_sanction_file, tender_called_date, tender_finalized_date, " + - "loa_date, loa_file, agreement_date, agreement_file, work_order_date, work_order_file, work_commenced_date, reason, remarks) " + - "VALUES ('%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', " + - "'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", - estimateNo, estimateDate, zone, ward, (iconicProject != null && iconicProject) ? 1 : 0, projectName, location, department, - contractorName, contractorPeriod, fundSource, scheme, category, subCategory, estAmount, techSancDate, adminSancDate, sanFilePath, - tenderCallDate, tenderFinDate, loaDate, loaFilePath, agreementDate, agreementFilePath, workOrderDate, workOrderFilePath, - workCommDate, reason, remarks_txt - ); - - addNonERPLog(""+lastInsertId,loginid, formattedSql); - } - // ✅ Return the generated ID - return estNo; - } - - @Transactional - public boolean updateESTno(int estid ,String estNo) { - String sqlQuery = "UPDATE `non_erp_works` SET `estimate_no`='"+estNo+"' WHERE `estid`='"+estid+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public boolean addNonERPLog(String id,String loginid, String query) { - String sqlQuery = "INSERT INTO `non_erp_logs`(`estid`, `updateby`, `query`) VALUES (?,?,?)"; - jdbcTemplate.update(sqlQuery,id,loginid,query); - return true; - } - - // Method to process the form data - public int processFormData(String zone, String ward, String projectname, String estimatenumber, - String estimatedate, String location, String sourceoffund, String schemename, - String category, String subcategory, String estimateamount, String department, - String loacopy, String agreementcopy, String workordercopy, - String sanctioncopy, String adminsandate, String worksdesc) throws DataAccessException, IOException { - - // Prepare SQL Insert Query - String sql = "INSERT INTO works_update (zone, ward, project_name, estimate_no, estimate_date, location, " + - "fund_source, scheme, category, sub_category, est_amount, department, loa_file, agreement_file, " + - "work_order_file, adm_san_file, admin_sanc_date, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, zone, ward, projectname, estimatenumber, estimatedate, location, sourceoffund, - schemename, category, subcategory, estimateamount, department, loacopy, agreementcopy, - workordercopy, sanctioncopy, adminsandate, worksdesc); - } - - private String getUserAccess(String userid) { - String ward = "0"; - String department="0"; - - String sql = "SELECT `id`, `userid`, `zone`, `ward`, `department` FROM `works_access` WHERE `userid`=? LIMIT 1"; - System.out.println("SELECT `id`, `userid`, `zone`, `ward` FROM `works_access` WHERE `userid`="+userid+" LIMIT 1"); - List> taskresult = jdbcTemplate.queryForList(sql, userid); - if(!taskresult.isEmpty()) { - ward = ""+taskresult.get(0).get("ward"); - department = ""+taskresult.get(0).get("department"); - } - return ward+"_"+department; - } - - public List> getAllERPWorks(String loginId) { - - String accessData = getUserAccess(loginId); - String where="ew.`nonerp`=0 "; - - // Split the string using "_" - String[] parts = accessData.split("_"); - - if(!parts[0].equals("all")) { - where =" AND ew.`ward` IN ("+parts[0]+") "; - } - if(!parts[1].equals("all")) { - if(!where.equals("")) - { - where = where + " AND ew.`department` IN ("+parts[1]+")"; - } - else { - where = where + " AND ew.`department` IN ("+parts[1]+")"; - } - } - - if(!where.equals("")) { - where = " WHERE "+ where; - } - - String sql = "SELECT ew.estid, ew.estimate_no, ew.estimate_date, ew.zone, ew.ward, ew.project_name, ew.location, " + - " dm.dept_name, ew.contractor_name, ew.contractor_period, fm.name as fund_source, sm.name as scheme, " + - " wm.name as category, tm.description as sub_category FROM gcc_works_status.erp_works ew " + - " left join gcc_works_status.department_master dm on dm.id = ew.department " + - " left join gcc_works_status.workstype_master wm on wm.id = ew.category " + - " left join gcc_works_status.typeofwork_master tm on tm.id = ew.sub_category " + - " left join gcc_works_status.fundsource_master fm on fm.id = ew.fund_Source " + - " left join gcc_works_status.scheme_master sm on sm.id = ew.scheme" - + " "+where; - return jdbcTemplate.queryForList(sql); - } - - - public Map getEstimateDetails(String estimateNo) { - String sql = "SELECT estimate_no,estimate_date,zone,ward, project_name, location, department, contractor_name, contractor_period, fund_source, scheme, category, " + - "sub_category,est_amount, tech_sanc_date, admin_sanc_date, tender_call_date, tender_fin_date, loa_date, agreement_date, work_order_date, work_comm_date, " + - "adm_san_file, loa_file, agreement_file, work_order_file, iconic_project, reason, remarks FROM works_update WHERE estimate_no = ?"; // Replace with your actual query - - // Fetch the details from the database as a Map - List> details = jdbcTemplate.queryForList(sql, estimateNo); - - if (details.isEmpty()) { - return new HashMap<>(); // Return an empty map instead of throwing an error - } - - return details.get(0); // Return the result map - } - - public List> getSchemeList() { - String sql = "SELECT * FROM gcc_works_status.scheme_master WHERE isactive=1 order by NAME asc"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql); - - return result; // Return the result map - } - - public List> getCategoryList() { - String sql = "SELECT * FROM gcc_works_status.workstype_master order by NAME asc"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql); - - return result; // Return the result map - } - - public List> getSubCategoryList() { - String sql = "SELECT * FROM gcc_works_status.typeofwork_master order by DESCRIPTION asc"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql); - - return result; // Return the result map - } - - public List> getDepartmentList() { - String sql = "SELECT * FROM gcc_works_status.department_master WHERE isactive=1 order by DEPT_NAME asc"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql); - - return result; // Return the result map - } - - public List> getSourceofFundList() { - String sql = "SELECT * FROM gcc_works_status.fundsource_master WHERE isactive=1 order by NAME asc"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql); - - return result; // Return the result map - } - - public int updateEstimateDetails(Map updatedDetails, String sanFilePath, String loaFilePath, - String agreementFilePath, String workOrderFilePath) throws IOException { - - // ✅ Base SQL query - StringBuilder sql = new StringBuilder("UPDATE gcc_works_status.erp_works SET " - + "estimate_date = ?, zone = ?, ward = ?, project_name = ?, location = ?, " - + "isiconic = ?, department = ?, contractor_name = ?, contractor_period = ?, " - + "fund_source = ?, scheme = ?, category = ?, sub_category = ?, estimation_amount = ?, " - + "technical_sanction_date = ?, admin_sanction_date = ?, tender_called_date = ?, tender_finalized_date = ?, " - + "loa_date = ?, agreement_date = ?, work_order_date = ?, work_commenced_date = ? "); - - // ✅ Dynamically append file updates if new files are provided - List params = new ArrayList<>(Arrays.asList( - updatedDetails.get("estimate_date"), - updatedDetails.get("zone"), - updatedDetails.get("ward"), - updatedDetails.get("project_name"), - updatedDetails.get("location"), - updatedDetails.get("iconic_project"), // ✅ Ensure iconic_project is updated - updatedDetails.get("department"), - updatedDetails.get("contractor_name"), - updatedDetails.get("contractor_period"), - updatedDetails.get("fund_source"), - updatedDetails.get("scheme"), - updatedDetails.get("category"), - updatedDetails.get("sub_category"), - updatedDetails.get("est_amount"), - updatedDetails.get("tech_sanc_date"), - updatedDetails.get("admin_sanc_date"), - updatedDetails.get("tender_call_date"), - updatedDetails.get("tender_fin_date"), - updatedDetails.get("loa_date"), - updatedDetails.get("agreement_date"), - updatedDetails.get("work_order_date"), - updatedDetails.get("work_comm_date") - )); - - if (!sanFilePath.isEmpty()) { - sql.append(", admin_sanction_file = ?"); - params.add(sanFilePath); - } - if (!loaFilePath.isEmpty()) { - sql.append(", loa_file = ?"); - params.add(loaFilePath); - } - if (!agreementFilePath.isEmpty()) { - sql.append(", agreement_file = ?"); - params.add(agreementFilePath); - } - if (!workOrderFilePath.isEmpty()) { - sql.append(", work_order_file = ?"); - params.add(workOrderFilePath); - } - - if (updatedDetails.get("reason") != null && !updatedDetails.get("reason").toString().isEmpty()) { - sql.append(", reason = ?"); - params.add(updatedDetails.get("reason")); - } - - if (updatedDetails.get("remarks") != null && !updatedDetails.get("remarks").toString().isEmpty()) { - sql.append(", remarks = ?"); - params.add(updatedDetails.get("remarks")); - } - - // ✅ Only update iconic_project if it's a Non-ERP estimate - if (updatedDetails.containsKey("iconic_project")) { - sql.append(", isiconic = ?"); - params.add(updatedDetails.get("iconic_project")); - } - - // ✅ Add WHERE clause - sql.append(" WHERE estimate_no = ?"); - params.add(updatedDetails.get("estimate_no")); - - // ✅ Execute update - return jdbcTemplate.update(sql.toString(), params.toArray()); - } - - public String getSequence() { - String sql = "select sequence from gcc_works_status.nonerp_sequence"; - return jdbcTemplate.queryForObject(sql, String.class); - } - - public int updateSequence(String seq) { - String sql = "update gcc_works_status.nonerp_sequence set sequence = ? where id = 1"; - return jdbcTemplate.update(sql, seq); - } - - public List> getFilteredWorksList(String zone, String ward, String department, String fundsource, - LocalDate fromDate, LocalDate toDate, String filterType, String estno) { - - StringBuilder sql = new StringBuilder("SELECT * FROM works_update"); - List params = new ArrayList<>(); - List conditions = new ArrayList<>(); - - if (zone != null && !zone.isEmpty()) { - conditions.add("zone = ?"); - params.add(zone); - } - if (ward != null && !ward.isEmpty()) { - conditions.add("ward = ?"); - params.add(ward); - } - if (department != null && !department.isEmpty()) { - conditions.add("department = ?"); - params.add(department); - } - if (fundsource != null && !fundsource.isEmpty()) { - conditions.add("fund_source = ?"); - params.add(fundsource); - } - if (fromDate != null) { - conditions.add("estimate_date >= ?"); - params.add(fromDate); - } - if (toDate != null) { - conditions.add("estimate_date <= ?"); - params.add(toDate); - } - - if (filterType != null && filterType.equals("erpWorks")) { - conditions.add("estimate_no not like'M%'"); - } - - if (filterType != null && filterType.equals("nonErpWorks")) { - conditions.add("estimate_no like'M%'"); - } - - if (estno != null && !estno.isEmpty()) { - conditions.add("estimate_no = ?"); - params.add(estno); - } - - // Append conditions only if there are any - if (!conditions.isEmpty()) { - sql.append(" WHERE ").append(String.join(" AND ", conditions)); - } - - System.out.println("sql: " + sql); - - return jdbcTemplate.queryForList(sql.toString(), params.toArray()); - } - - //model service - - public List> fetchEstimateByCode(String estimateCode) { - String query = "SELECT * FROM gcc_works_status.erp_works WHERE estimate_no=?"; - return jdbcTemplate.queryForList(query, estimateCode); - } - - - // save details service - @Transactional - public List> saveWorkDetailsbycode(List> workDetails) { - String sql = "INSERT INTO works_details (estimate_number, category, sub_category, road_name, road_type, work_type_1, work_type_2, work_type_3, length, width, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - for (Map work : workDetails) { - jdbcTemplate.update(sql, - work.get("estimate_number"), - work.get("category"), - work.get("sub_category"), - work.get("road_name"), - work.get("road_type"), - work.get("work_type_1"), - work.get("work_type_2"), - work.get("work_type_3"), - work.get("length"), - work.get("width"), - work.get("remarks") - ); - } - - return workDetails; - } - - public List getAllWorksDetails() { - String sql = "SELECT distinct estimate_no FROM gcc_works_status.erp_works"; - return jdbcTemplate.queryForList(sql, String.class); - } - - public List> getAllReasons() { - String sql = "SELECT id, reasons FROM gcc_works_status.reason_master"; - return jdbcTemplate.queryForList(sql); - } - - public String convertDateFormat(String date) { - if (date == null || date.isEmpty() || date.equals("_--_")) { - return null; // Return null for empty or invalid date values - } - - try { - SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MM-yyyy"); - SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd"); - - Date parsedDate = inputFormat.parse(date); - return outputFormat.format(parsedDate); - } catch (Exception e) { - System.err.println("Date conversion error for: " + date + " - " + e.getMessage()); - return null; // Return null to avoid inserting invalid dates - } - } - - public int saveERPEstimate(String estimateNo, String estimateDate, String zone, String ward, String projectName, - int iconicProject, String location, String department, String contractorName, - String contractorPeriod, String fundSource, String scheme, String category, - String subCategory, String estAmount, String techSancDate, String adminSancDate, - String admSanFile, String tenderCallDate, String tenderFinDate, String loaDate, - String loaFile, String agreementDate, String agreementFile, String workOrderDate, - String workOrderFile, String workCommDate) { - - String sql = "INSERT INTO gcc_works_status.erp_works (estimate_no, estimate_date, zone, ward, project_name, location, " + - "department, contractor_name, contractor_period, fund_source, scheme, category, sub_category, " + - "estimation_amount, technical_sanction_date, admin_sanction_date, admin_sanction_file, tender_called_date, tender_finalized_date, loa_date, " + - "loa_file, agreement_date, agreement_file, work_order_date, work_order_file, work_commenced_date, isiconic) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, estimateNo, estimateDate, zone, ward, projectName, location, department, - contractorName, contractorPeriod, fundSource, scheme, category, subCategory, estAmount, - techSancDate, adminSancDate, admSanFile, tenderCallDate, tenderFinDate, loaDate, loaFile, - agreementDate, agreementFile, workOrderDate, workOrderFile, workCommDate, iconicProject); - } - - public List> getestimateworkdetails(String estNo) { - String sql = "SELECT * FROM works_details where estimate_number =?"; - return jdbcTemplate.queryForList(sql, estNo); - } - - public List> getQuestionsBySubCatId(int subCatId) { - String sql = "SELECT qm.id, qm.question_name, qm.input_type_id, qm.sub_cat_id, qm.field_order, " + - "im.name AS input_type_name, am.id AS answer_id, am.answer_name, am.haschild AS a_haschild, " + - " eg.code AS sub_cat_code, eg.id AS sub_cat_id " + - "FROM gcc_works_status.question_master qm " + - "LEFT JOIN gcc_works_status.input_type_master im ON qm.input_type_id = im.id " + - "LEFT JOIN gcc_works_status.ans_master am ON am.ques_id = qm.id " + - "JOIN gcc_works_status.typeofwork_master eg ON eg.id = qm.sub_cat_id " + - "WHERE qm.sub_cat_id = ? AND qm.isactive=1 and qm.field_order !=0 order by qm.field_order "; - - return jdbcTemplate.queryForList(sql, subCatId); - } - - - - public Integer getSubCategoryIdByName(String subCategoryName) { - String sql = "SELECT id FROM egw_typeofwork WHERE code = ?"; - - return jdbcTemplate.queryForObject(sql, Integer.class, subCategoryName); - - } - - // save answer method - - - public void saveAnswers(List> answers) { - if (answers == null || answers.isEmpty()) { - System.err.println("No answers provided."); - return; - } - - // Extract estimate number - String estimateNumber = (String) answers.get(0).getOrDefault("estimateNumber", ""); - - if (estimateNumber == null || estimateNumber.isEmpty()) { - System.err.println("Estimate number is missing."); - return; - } - - try { - // Get estid using estimate number - String query = "SELECT estid FROM gcc_works_status.erp_works WHERE estimate_no = ?"; - Integer estid = jdbcTemplate.queryForObject(query, Integer.class, estimateNumber); - System.out.println("estid: " + estid); - - if (estid == null) { - System.err.println("Estimate ID not found for estimate number: " + estimateNumber); - return; - } - - // SQL for inserting data - String sql = "INSERT INTO gcc_works_status.erp_works_task (estid, estimate_no, sub_cat_id, question_id, answer_text, ans_id) " + - "VALUES (?, ?, ?, ?, ?, ?)"; - - // Insert answers - for (Map answer : answers) { - try { - Integer questionId = convertToInteger(answer.get("questionId")); - String answerText = (String) answer.getOrDefault("answerText", ""); - Integer answerId = convertToInteger(answer.get("answerId")); - Integer subCatId = convertToInteger(answer.get("subCatId")); - - jdbcTemplate.update(sql, estid, estimateNumber, subCatId, questionId, answerText, answerId); - } catch (Exception e) { - System.err.println("Error saving answer for questionId: " + answer.get("questionId") + " - " + e.getMessage()); - } - } - - System.out.println("Answers saved successfully."); - } catch (Exception e) { - System.err.println("Error fetching estid for estimate number: " + estimateNumber + " - " + e.getMessage()); - } - } - - private Integer convertToInteger(Object value) { - if (value == null) { - return null; - } - if (value instanceof Number) { - return ((Number) value).intValue(); - } - if (value instanceof String) { - try { - return Integer.parseInt((String) value); - } catch (NumberFormatException e) { - System.err.println("Invalid integer value: " + value); - return null; - } - } - System.err.println("Unsupported data type: " + value.getClass().getName()); - return null; - } - - - public Map getQuestionDetailsById(int answerId) { - - String sql = "SELECT qm.id, qm.question_name, qm.haschild, qm.input_type_id, qm.sub_cat_id, qm.field_order, " - + "im.name AS input_type_name " - + "FROM gcc_works_status.question_master qm " - + "LEFT JOIN gcc_works_status.input_type_master im ON qm.input_type_id = im.id " - + "LEFT JOIN gcc_works_status.ans_master am ON am.id = qm.haschild " - + "WHERE am.id = ? AND am.haschild = 1 AND qm.isactive=1" ; - - System.out.println("sql..1"+sql); - - return jdbcTemplate.queryForMap(sql, answerId); - } - - public List> getAnsDetailsByQId(String quesId) { - - String sql = "select im.name ,qm.input_type_id,qm.id as QId,am.answer_name,am.id as AId, am.haschild " - + " from ans_master am " - + " Left join gcc_works_status.question_master qm ON am.ques_id=qm.id " - + " Left join gcc_works_status.input_type_master im on qm.input_type_id=im.id " - + " where qm.id =? and qm.isactive=1" ; - - System.out.println("sql..2"+sql); - - return jdbcTemplate.queryForList(sql, quesId); - } - - // fetch the saved data - - - public List> getSavedData(String estimateNumber) { - - String sql = "SELECT ewt.*, qm.question_name, am.answer_name, im.name, qm.field_order, " - + " CASE WHEN ewt.ans_id = am.id THEN 1 ELSE 0 END AS is_saved_answer " - + " FROM gcc_works_status.erp_works_task ewt " - + " LEFT JOIN gcc_works_status.question_master qm ON qm.id = ewt.question_id " - + " LEFT JOIN gcc_works_status.ans_master am ON am.ques_id = qm.id " - + " LEFT JOIN gcc_works_status.input_type_master im ON im.id = qm.input_type_id " - + " WHERE ewt.estimate_no = ? group by ewt.id,am.answer_name,am.id order by qm.field_order "; - - - return jdbcTemplate.queryForList(sql, estimateNumber); - } - - - /* public List> getSavedData(String estimateNumber) { - - String sql = "SELECT DISTINCT wt.*, qm.question_name, am.answer_name, im.name, qm.field_order, " - + " CASE WHEN wt.ans_id = am.id THEN 1 ELSE 0 END AS is_saved_answer " - + " FROM works_task wt " - + " LEFT JOIN question_master qm ON qm.id = wt.question_id " - + " LEFT JOIN ans_master am ON am.ques_id = qm.id " - + " LEFT JOIN input_type_master im ON im.id = qm.input_type_id " - + " WHERE wt.estimate_no = ? group by wt.id,am.answer_name,am.id,wt.group_id order by qm.field_order"; - - return jdbcTemplate.queryForList(sql, estimateNumber); - }*/ - - public List> getAllNonERPWorks(String loginId) { - String accessData = getUserAccess(loginId); - String where=""; - - // Split the string using "_" - String[] parts = accessData.split("_"); - - if(!parts[0].equals("all")) { - where =" new.`ward` IN ("+parts[0]+") "; - } - if(!parts[1].equals("all")) { - if(!where.equals("")) - { - where = where + "AND new.`department` IN ("+parts[1]+")"; - } - else { - where = where + "new.`department` IN ("+parts[1]+")"; - } - } - - if(!where.equals("")) { - where = " WHERE "+ where; - } - - String sql = "SELECT new.estid, new.estimate_no, new.estimate_date, new.zone, new.ward, new.project_name, new.location, new.filenumber, new.estimation_amount, " + - " dm.dept_name, new.contractor_name, new.contractor_period, fm.name as fund_source, sm.name as scheme, " + - " wm.name as category, tm.description as sub_category FROM gcc_works_status.non_erp_works new " + - " left join gcc_works_status.department_master dm on dm.id = new.department " + - " left join gcc_works_status.workstype_master wm on wm.id = new.category " + - " left join gcc_works_status.typeofwork_master tm on tm.id = new.sub_category " + - " left join gcc_works_status.fundsource_master fm on fm.id = new.fund_Source " + - " left join gcc_works_status.scheme_master sm on sm.id = new.scheme" - + " "+ where; - return jdbcTemplate.queryForList(sql); - } - - - public Map getERPEstimateDetails(String estimateNo) { - - String sql = "select ew.estimate_no, ew.estimate_date, ew.zone, ew.ward, ew.project_name, ew.location, ew.department, ew.contractor_name, " + - "ew.contractor_period, ew.estimation_amount as est_amount, ew.technical_sanction_date as tech_sanc_date, ew.admin_sanction_date as admin_sanc_date," + - "ew.tender_called_date as tender_call_date, ew.tender_called_date as tender_fin_date, ew.loa_date, ew.agreement_date, ew.work_order_date, " + - "ew.work_commenced_date as work_comm_date, ew.admin_sanction_file as adm_san_file, ew.loa_file, ew.agreement_file, ew.work_order_file, " + - "ew.isiconic as iconic_project, dm.dept_name, ew.fund_source as fundsource, fm.name as fund_source, " + - "ew.scheme as schemeid, sm.name as scheme, ew.category as categoryid, wm.name as category, ew.sub_category as subcategoryid, " + - "tm.description as sub_category " + - "from gcc_works_status.erp_works ew " + - " left join gcc_works_status.department_master dm on dm.id = ew.department " + - " left join gcc_works_status.workstype_master wm on wm.id = ew.category " + - " left join gcc_works_status.typeofwork_master tm on tm.id = ew.sub_category " + - " left join gcc_works_status.fundsource_master fm on fm.id = ew.fund_Source " + - " left join gcc_works_status.scheme_master sm on sm.id = ew.scheme where ew.estimate_no = ? LIMIT 100"; - - // Fetch the details from the database as a Map - List> details = jdbcTemplate.queryForList(sql, estimateNo); - - if (details.isEmpty()) { - return new HashMap<>(); // Return an empty map instead of throwing an error - } - - return details.get(0); // Return the result map - } - - public Map getNonERPEstimateDetails(String estimateNo) { - - String sql = "select ew.estimate_no, ew.estimate_date, ew.zone, ew.ward, ew.project_name, ew.location, ew.department, ew.contractor_name, " + - "ew.contractor_period, ew.estimation_amount as est_amount, ew.technical_sanction_date as tech_sanc_date, ew.admin_sanction_date as admin_sanc_date," + - "ew.tender_called_date as tender_call_date, ew.tender_called_date as tender_fin_date, ew.loa_date, ew.agreement_date, ew.work_order_date, " + - "ew.work_commenced_date as work_comm_date, ew.admin_sanction_file as adm_san_file, ew.loa_file, ew.agreement_file, ew.work_order_file, " + - "ew.isiconic as iconic_project, dm.dept_name, ew.fund_source as fundsource, fm.name as fund_source, " + - "ew.scheme as schemeid, sm.name as scheme, ew.category as categoryid, wm.name as category, ew.sub_category as subcategoryid, ew.reason, ew.remarks, " + - "tm.description as sub_category, ew.`project_type`, ew.`govt_funded_project`, ew.`special_category`, ew.`filenumber` " + - "from gcc_works_status.non_erp_works ew " + - " left join gcc_works_status.department_master dm on dm.id = ew.department " + - " left join gcc_works_status.workstype_master wm on wm.id = ew.category " + - " left join gcc_works_status.typeofwork_master tm on tm.id = ew.sub_category " + - " left join gcc_works_status.fundsource_master fm on fm.id = ew.fund_Source " + - " left join gcc_works_status.scheme_master sm on sm.id = ew.scheme where ew.estimate_no = ? "; - - // Fetch the details from the database as a Map - List> details = jdbcTemplate.queryForList(sql, estimateNo); - - if (details.isEmpty()) { - return new HashMap<>(); // Return an empty map instead of throwing an error - } - - return details.get(0); // Return the result map - } - - public int updateNonERPEstimateDetails(Map updatedDetails, String sanFilePath, String loaFilePath, - String agreementFilePath, String workOrderFilePath) throws IOException { - - // ✅ Base SQL query - StringBuilder sql = new StringBuilder("UPDATE gcc_works_status.non_erp_works SET " - + "estimate_date = ?, zone = ?, ward = ?, project_name = ?, location = ?, " - + "isiconic = ?, department = ?, contractor_name = ?, contractor_period = ?, " - + "fund_source = ?, scheme = ?, category = ?, sub_category = ?, estimation_amount = ?, " - + "technical_sanction_date = ?, admin_sanction_date = ?, tender_called_date = ?, tender_finalized_date = ?, " - + "loa_date = ?, agreement_date = ?, work_order_date = ?, work_commenced_date = ?, " - + "project_type=?, govt_funded_project=?, special_category=?, filenumber=? "); - - // ✅ Dynamically append file updates if new files are provided - List params = new ArrayList<>(Arrays.asList( - updatedDetails.get("estimate_date"), - updatedDetails.get("zone"), - updatedDetails.get("ward"), - updatedDetails.get("project_name"), - updatedDetails.get("location"), - updatedDetails.get("iconic_project"), // ✅ Ensure iconic_project is updated - updatedDetails.get("department"), - updatedDetails.get("contractor_name"), - updatedDetails.get("contractor_period"), - updatedDetails.get("fund_source"), - updatedDetails.get("scheme"), - updatedDetails.get("category"), - updatedDetails.get("sub_category"), - updatedDetails.get("est_amount"), - updatedDetails.get("tech_sanc_date"), - updatedDetails.get("admin_sanc_date"), - updatedDetails.get("tender_call_date"), - updatedDetails.get("tender_fin_date"), - updatedDetails.get("loa_date"), - updatedDetails.get("agreement_date"), - updatedDetails.get("work_order_date"), - updatedDetails.get("work_comm_date"), - updatedDetails.get("projecttype"), - updatedDetails.get("govtfund"), - updatedDetails.get("specialcat"), - updatedDetails.get("filenumber") - )); - - if (!sanFilePath.isEmpty()) { - sql.append(", admin_sanction_file = ?"); - params.add(sanFilePath); - } - if (!loaFilePath.isEmpty()) { - sql.append(", loa_file = ?"); - params.add(loaFilePath); - } - if (!agreementFilePath.isEmpty()) { - sql.append(", agreement_file = ?"); - params.add(agreementFilePath); - } - if (!workOrderFilePath.isEmpty()) { - sql.append(", work_order_file = ?"); - params.add(workOrderFilePath); - } - - if (updatedDetails.get("reason") != null && !updatedDetails.get("reason").toString().isEmpty()) { - sql.append(", reason = ?"); - params.add(updatedDetails.get("reason")); - } - - if (updatedDetails.get("remarks") != null && !updatedDetails.get("remarks").toString().isEmpty()) { - sql.append(", remarks = ?"); - params.add(updatedDetails.get("remarks")); - } - - // ✅ Only update iconic_project if it's a Non-ERP estimate - if (updatedDetails.containsKey("iconic_project")) { - sql.append(", isiconic = ?"); - params.add(updatedDetails.get("iconic_project")); - } - - // ✅ Add WHERE clause - sql.append(" WHERE estimate_no = ?"); - params.add(updatedDetails.get("estimate_no")); - - // ✅ Execute update - return jdbcTemplate.update(sql.toString(), params.toArray()); - } - - ///// Balaji - - public List> getestimateworkdetailsById(String estid) { - String sql = "SELECT * FROM works_data_erp where `id`=? LIMIT 1"; - return jdbcTemplate.queryForList(sql, estid); - } - - public int saveEstimateWorkDetails( - String loginid, - String estid, - String isiconic, - MultipartFile admin_sanction_file, - MultipartFile loa_file, - MultipartFile agreement_file, - MultipartFile work_order_file, - String techSanctionDate, - String adminSanctionDate, - String tenderCallDate, - String tenderFinalizedDate, - String loaDate, - String agreementDate, - String workOrderDate, - String workCommencedDate, - String projecttype, - String govtfund, - String specialcat - ) { - // Fetch the estimate details - List> estimateDetails = getestimateworkdetailsById(estid); - - if (estimateDetails.isEmpty()) { - System.out.println("No records found for ID: " + estid); - return 0; - } - - try { - // File Upload and save URL - String admin_sanction_file_url = saveFile(admin_sanction_file, "admin_sanction", "erp"); - String loa_file_url = saveFile(loa_file, "loa", "erp"); - String agreement_file_url = saveFile(agreement_file, "agreement", "erp"); - String work_order_file_url = saveFile(work_order_file, "work_order", "erp"); - - // Extract the first record - Map data = estimateDetails.get(0); - - // Call saveEstimate with the extracted values - return saveEstimate( - String.valueOf(data.get("ESTIMATE_NO")), - String.valueOf(data.get("ESTIMATE_DATE")), - String.valueOf(data.get("ZONE")), - String.valueOf(data.get("WARD")), - String.valueOf(data.get("PROJECT_NAME")), - isiconic, - String.valueOf(data.get("LOCATION")), - String.valueOf(data.get("DEPARTMENT_NAME")), - String.valueOf(data.get("CONTRACTOR_NAME")), - String.valueOf(data.get("CONTRACTOR_PERIOD")), - String.valueOf(data.get("FUND_SOURCE")), - String.valueOf(data.get("SCHEME")), - String.valueOf(data.get("CATEGORY")), - String.valueOf(data.get("SUB_CATEGORY")), - String.valueOf(data.get("ESTIMATION_AMOUNT")), - techSanctionDate, - //String.valueOf(data.get("TECHNICAL_SANCTION_DATE")), - adminSanctionDate, - //String.valueOf(data.get("ADMIN_SANCTION_DATE")), - admin_sanction_file_url, - tenderCallDate, - //String.valueOf(data.get("TENDER_CALLED_DATE")), - tenderFinalizedDate, - //String.valueOf(data.get("TENDER_FINALIZED_DATE")), - loaDate, - //String.valueOf(data.get("LOA_DATE")), - loa_file_url, - agreementDate, - //String.valueOf(data.get("AGREEMENT_DATE")), - agreement_file_url, - workOrderDate, - //String.valueOf(data.get("WORK_ORDER_DATE")), - work_order_file_url, - workCommencedDate, - //String.valueOf(data.get("WORK_COMMENCED_DATE")), - String.valueOf(data.get("id")), - loginid, - projecttype, - govtfund, - specialcat, - String.valueOf(data.get("EST_VAL_WITH_OH")) - ); - } catch (IOException e) { - e.printStackTrace(); // Log the exception - System.out.println("Error uploading files: " + e.getMessage()); - return 0; - } - } - - public int saveEstimate(String estimateNo, String estimateDate, String zone, String ward, String projectName, - String iconicProject, String location, String department, String contractorName, - String contractorPeriod, String fundSource, String scheme, String category, - String subCategory, String estAmount, String techSancDate, String adminSancDate, - String admSanFile, String tenderCallDate, String tenderFinDate, String loaDate, - String loaFile, String agreementDate, String agreementFile, String workOrderDate, - String workOrderFile, String workCommDate, String works_data_erp_id, String loginid, - String projecttype,String govtfund,String specialcat, String estAmountWithOH) { - - String departmentId = getDepartmentId(department); - String categoryId = getCategoryId(category); - String subCategoryId = getSubCategoryId(subCategory); - String fundSourceId = getFundSourceId(fundSource); - String schemeId = getSchemeId(scheme); - - techSancDate = normalizeDate(techSancDate); - agreementDate = normalizeDate(agreementDate); - adminSancDate = normalizeDate(adminSancDate); - tenderCallDate = normalizeDate(tenderCallDate); - tenderFinDate = normalizeDate(tenderFinDate); - loaDate = normalizeDate(loaDate); - workOrderDate = normalizeDate(workOrderDate); - workCommDate = normalizeDate(workCommDate); - - String sql = "INSERT INTO `gcc_works_status`.`erp_works` (estimate_no, estimate_date, zone, ward, project_name, location, " + - "department, contractor_name, contractor_period, fund_source, scheme, category, sub_category, " + - "estimation_amount, technical_sanction_date, admin_sanction_date, admin_sanction_file, tender_called_date, " + - "tender_finalized_date, loa_date, " + - "loa_file, agreement_date, agreement_file, work_order_date, work_order_file, work_commenced_date,isiconic,works_data_erp_id, " + - "project_type, govt_funded_project, special_category, est_val_with_oh) " + - "VALUES " - + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + " ?, ?, ?, ?, ?, ?, ?, ?, " - + " ?, ?, ?, ?)"; - - int result = jdbcTemplate.update(sql, - estimateNo, estimateDate, zone, ward, projectName, - location, departmentId, contractorName, contractorPeriod, fundSourceId, - schemeId, categoryId, subCategoryId, estAmount, techSancDate, - adminSancDate, admSanFile, tenderCallDate, tenderFinDate, loaDate, - loaFile, agreementDate, agreementFile, workOrderDate, workOrderFile, - workCommDate, iconicProject, works_data_erp_id, - projecttype, govtfund, specialcat, estAmountWithOH); - - updateWorksDataErpStatus(works_data_erp_id); - - runSqlScript(); - - String logsql = "INSERT INTO `gcc_works_status`.`erp_works` (estimate_no, estimate_date, zone, ward, project_name, location, " + - "department, contractor_name, contractor_period, fund_source, scheme, category, sub_category, " + - "estimation_amount, technical_sanction_date, admin_sanction_date, admin_sanction_file, tender_called_date, " + - "tender_finalized_date, loa_date, " + - "loa_file, agreement_date, agreement_file, work_order_date, work_order_file, work_commenced_date,isiconic,works_data_erp_id," + - "project_type, govt_funded_project, special_category, est_val_with_oh) " + - "VALUES ('" + estimateNo + "', '" + estimateDate + "', '" + zone + "', '" + ward + "', '" + projectName + "', '" + - location + "', '" + departmentId + "', '" + contractorName + "', '" + contractorPeriod + "', '" + fundSourceId + "', '" + - schemeId + "', '" + categoryId + "', '" + subCategoryId + "', '" + estAmount + "', '" + techSancDate + "', '" + - adminSancDate + "', '" + admSanFile + "', '" + tenderCallDate + "', '" + tenderFinDate + "', '" + loaDate + "', '" + - loaFile + "', '" + agreementDate + "', '" + agreementFile + "', '" + workOrderDate + "', '" + workOrderFile + "', '" + - workCommDate + "', '" + iconicProject + "', '" + works_data_erp_id + "','" + - projecttype + "', '" + govtfund + "', '" + specialcat + "', '"+ estAmountWithOH +"')"; - - addERPLog(works_data_erp_id,loginid,logsql); - - return result; - } - @Transactional - public void runSqlScript() { - // 1. Update zone and ward - jdbcTemplate.execute("UPDATE `erp_works` " - + "SET " - + " `zone` = LPAD(`zone`, 2, '0'), " - + " `ward` = LPAD(`ward`, 3, '0')"); - - // 2. Insert into erp_works_task - jdbcTemplate.execute("INSERT INTO `erp_works_task` (`estid`, `estimate_no`, `sub_cat_id`, `question_id`, `ans_id`, `remarks`) " - + " SELECT DISTINCT " - + " estid, " - + " estimate_no, " - + " sub_category, " - + " 1 AS question_id, " - + " project_name AS ans_id, " - + " NULL AS remarks " - + " FROM `erp_works` ew " - + " WHERE NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_task ews " - + " WHERE ews.estid = ew.estid " - + " )"); - - // 3. Insert stages for '4RBT' - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + "SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + "FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE (project_name LIKE \"%BM%\" " - + " OR project_name LIKE \"%BC%\" " - + " OR project_name LIKE \"%BT%\" " - + " OR project_name LIKE \"%B.T%\") " - + " AND sub_category = 4 " - + " AND category IN (8, 9, 14, 15) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + ") ew " - + "CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '4RBT' " - + ") twtm"); - - // Add similar jdbcTemplate.execute("..."); for each SQL block in your script - - // 4. Insert stages for '4FBT' - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + "SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + "FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE (project_name LIKE \"%BM%\" " - + " OR project_name LIKE \"%BC%\" " - + " OR project_name LIKE \"%BT%\" " - + " OR project_name LIKE \"%B.T%\") " - + " AND sub_category = 4 " - + " AND category IN (1,4,7,11) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + ") ew " - + "CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '4FBT' " - + ") twtm"); - - // 5. Insert stages for '4RCC' - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + "SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + "FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE ( " - + " project_name LIKE \"%CC%\" OR " - + " project_name LIKE \"%concrete%\" OR " - + " project_name LIKE \"%Interlocking%\" OR " - + " project_name LIKE \"%Inter locking%\" OR " - + " project_name LIKE \"%ILP%\" OR " - + " project_name LIKE \"%ILB%\" OR " - + " project_name LIKE \"%inlet%Chamber%\" ) " - + " AND sub_category = 4 " - + " AND category IN (8, 9, 14, 15) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + ") ew " - + "CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '4RCC' " - + ") twtm"); - - // 6. Insert stages for '4FCC' - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + "SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + "FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE ( " - + " project_name LIKE \"%CC%\" OR " - + " project_name LIKE \"%concrete%\" OR " - + " project_name LIKE \"%Interlocking%\" OR " - + " project_name LIKE \"%Inter locking%\" OR " - + " project_name LIKE \"%ILP%\" OR " - + " project_name LIKE \"%ILB%\" OR " - + " project_name LIKE \"%inlet%Chamber%\" ) " - + " AND sub_category = 4 " - + " AND category IN (1,4,7,11) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + ") ew " - + "CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '4FCC' " - + ") twtm"); - - // 7. Insert stages for '0SS' where sub_category = 4 - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + " SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + " FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE sub_category = 4 " - + " AND category IN (7,8,9,14,15) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + " ) ew " - + " CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '0SS' " - + " ) twtm"); - - // 8. Insert stages for '0SS' where sub_category <> 4 - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + " SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + " FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE sub_category <> 4 " - + " AND category IN (2,3,5,6,8,9,10,11,12,13,14,15) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + " ) ew " - + " CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '0SS' " - + " ) twtm"); - - // 9. Insert stages for sub_category = 15 and category IN (8,10,15) - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + " SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + " FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE sub_category =15 " - + " AND category IN (8,10,15) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + " ) ew " - + " CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '0SS' " - + " ) twtm"); - - // 10. Insert stages for sub_category = 15 and category = 7 (code = 15NB) - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + " SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + " FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE sub_category = 15 " - + " AND category IN (7) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + " ) ew " - + " CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '15NB' " - + " ) twtm"); - - // 11. Insert stages for sub_category = 7 and category = 7 (code = 7SWD) - jdbcTemplate.execute("INSERT INTO `erp_works_stages` (`estid`, `code`, `stagename`, `orderby`, `remarks`) " - + " SELECT " - + " ew.estid, " - + " twtm.code, " - + " twtm.taskname, " - + " twtm.orderby, " - + " twtm.remarks " - + " FROM ( " - + " SELECT DISTINCT estid " - + " FROM `erp_works` ew " - + " WHERE sub_category = 7 " - + " AND category IN (7) " - + " AND NOT EXISTS ( " - + " SELECT 1 " - + " FROM erp_works_stages ews " - + " WHERE ews.estid = ew.estid " - + " ) " - + " ) ew " - + " CROSS JOIN ( " - + " SELECT * " - + " FROM typeofwork_task_master " - + " WHERE code = '7SWD' " - + " ) twtm"); - } - - /*public void runSqlScript() { - try { - // Load SQL content from classpath safely - Resource resource = new ClassPathResource("work_sync.sql"); - - try (InputStream inputStream = resource.getInputStream(); - Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) { - - scanner.useDelimiter("\\A"); - String sql = scanner.hasNext() ? scanner.next() : ""; - - // Execute the SQL - jdbcTemplate.execute(sql); - } - } catch (Exception e) { - e.printStackTrace(); // or log with Logger - } - }*/ - - @Transactional - public boolean addERPLog(String id,String loginid, String query) { - String sqlQuery = "INSERT INTO `erp_logs`(`estid`, `updateby`, `query`) VALUES (?,?,?)"; - jdbcTemplate.update(sqlQuery,id,loginid,query); - return true; - } - - @Transactional - public boolean updateWorksDataErpStatus(String id) { - String sqlQuery = "UPDATE `works_data_erp` SET `isuserupdate`=1 WHERE `id`=?"; - jdbcTemplate.update(sqlQuery,id); - return true; - } - - public int updateEstimateWorkDetails( - String loginid, - String estid, - String isiconic, - MultipartFile admin_sanction_file, - MultipartFile loa_file, - MultipartFile agreement_file, - MultipartFile work_order_file, - String techSanctionDate, - String adminSanctionDate, - String tenderCallDate, - String tenderFinalizedDate, - String loaDate, - String agreementDate, - String workOrderDate, - String workCommencedDate, - String projecttype, - String govtfund, - String specialcat - ) { - // Fetch the estimate details - //List> estimateDetails = getestimateworkdetailsById(estid); -/* - if (estimateDetails.isEmpty()) { - System.out.println("No records found for ID: " + estid); - return 0; - } - */ - try { - // File Upload and save URL - String admin_sanction_file_url = saveFile(admin_sanction_file, "admin_sanction", "erp"); - String loa_file_url = saveFile(loa_file, "loa", "erp"); - String agreement_file_url = saveFile(agreement_file, "agreement", "erp"); - String work_order_file_url = saveFile(work_order_file, "work_order", "erp"); - - // Extract the first record - //Map data = estimateDetails.get(0); - - // Call saveEstimate with the extracted values - return updateEstimate( - estid, - isiconic, - techSanctionDate, - //String.valueOf(data.get("TECHNICAL_SANCTION_DATE")), - adminSanctionDate, - //String.valueOf(data.get("ADMIN_SANCTION_DATE")), - admin_sanction_file_url, - tenderCallDate, - //String.valueOf(data.get("TENDER_CALLED_DATE")), - tenderFinalizedDate, - //String.valueOf(data.get("TENDER_FINALIZED_DATE")), - loaDate, - //String.valueOf(data.get("LOA_DATE")), - loa_file_url, - agreementDate, - //String.valueOf(data.get("AGREEMENT_DATE")), - agreement_file_url, - workOrderDate, - //String.valueOf(data.get("WORK_ORDER_DATE")), - work_order_file_url, - workCommencedDate, - //String.valueOf(data.get("WORK_COMMENCED_DATE")), - loginid, - projecttype, - govtfund, - specialcat - ); - } catch (IOException e) { - e.printStackTrace(); // Log the exception - System.out.println("Error uploading files: " + e.getMessage()); - return 0; - } - } - - private String normalizeDate(String date) { - return (date == null || date.isBlank()) ? null : date; - } - - public int updateEstimate(String estid, - String iconicProject, String techSancDate, String adminSancDate, - String admSanFile, String tenderCallDate, String tenderFinDate, String loaDate, - String loaFile, String agreementDate, String agreementFile, String workOrderDate, - String workOrderFile, String workCommDate, String loginid, - String projecttype, String govtfund, String specialcat) { - - // Normalize blank date fields to null - techSancDate = normalizeDate(techSancDate); - agreementDate = normalizeDate(agreementDate); - adminSancDate = normalizeDate(adminSancDate); - tenderCallDate = normalizeDate(tenderCallDate); - tenderFinDate = normalizeDate(tenderFinDate); - loaDate = normalizeDate(loaDate); - workOrderDate = normalizeDate(workOrderDate); - workCommDate = normalizeDate(workCommDate); - - // Dynamically build file update portion of SQL - StringBuilder fileQuery = new StringBuilder(); - List params = new ArrayList<>(); - - // Base SQL - String sql = "UPDATE `gcc_works_status`.`erp_works` SET " - + "technical_sanction_date=?, admin_sanction_date=?, tender_called_date=?, " - + "tender_finalized_date=?, loa_date=?, agreement_date=?, work_order_date=?, work_commenced_date=?, " - + "isiconic=?, project_type=?, govt_funded_project=?, special_category=?"; - - // Add base parameters - Collections.addAll(params, techSancDate, adminSancDate, tenderCallDate, tenderFinDate, - loaDate, agreementDate, workOrderDate, workCommDate, - iconicProject, projecttype, govtfund, specialcat); - - // Add file fields conditionally - if (admSanFile != null && !admSanFile.isBlank()) { - fileQuery.append(", admin_sanction_file=?"); - params.add(admSanFile); - } - if (loaFile != null && !loaFile.isBlank()) { - fileQuery.append(", loa_file=?"); - params.add(loaFile); - } - if (agreementFile != null && !agreementFile.isBlank()) { - fileQuery.append(", agreement_file=?"); - params.add(agreementFile); - } - if (workOrderFile != null && !workOrderFile.isBlank()) { - fileQuery.append(", work_order_file=?"); - params.add(workOrderFile); - } - - // Complete SQL and add estid - sql += fileQuery.toString() + " WHERE estid=? LIMIT 1"; - params.add(estid); - - // Execute update - int result = jdbcTemplate.update(sql, params.toArray()); - - String logsql =""; - // Log the update - addERPLog(estid, loginid, logsql); - - return result; - } - - public List> getUserEstWorkDetailsById(String estid) { - String sql = "SELECT ew.`estid`, ew.`estimate_no`, ew.`estimate_date`, ew.`zone`, ew.`ward`, " - + "ew.`project_name`, ew.`location`, ew.`contractor_name`, ew.`contractor_period`, " - + "fm.`name` AS `fund_source`, sm.`name` AS `scheme`, " - + "ew.`estimation_amount`, ew.`est_val_with_oh`, ew.`technical_sanction_date`, ew.`admin_sanction_date`, " - + " ew.`tender_called_date`, ew.`tender_finalized_date`, ew.`loa_date`, " - + "ew.`agreement_date`, ew.`work_order_date`, " - + " CONCAT('" + fileBaseUrl + "/gcc/files', ew.`admin_sanction_file`) AS admin_sanction_file, " - + " CONCAT('" + fileBaseUrl + "/gcc/files', ew.`agreement_file`) AS agreement_file, " - + " CONCAT('" + fileBaseUrl + "/gcc/files', ew.`loa_file`) AS loa_file, " - + " CONCAT('" + fileBaseUrl + "/gcc/files', ew.`work_order_file`) AS work_order_file, " - + "ew.`work_commenced_date`, ew.`update_status`, ew.`isiconic`, " - + "ew.`works_data_erp_id`, ew.`percentage`, ew.`project_type`, ew.`govt_funded_project`, ew.`special_category`, " - + "dm.dept_name as `department`, wm.name as `category`, " - + "trim(tm.description) as `sub_category` " - + "FROM erp_works ew " - + "LEFT JOIN department_master dm ON dm.id = ew.department " - + "LEFT JOIN workstype_master wm ON wm.id = ew.category " - + "LEFT JOIN typeofwork_master tm ON tm.id = ew.sub_category " - + "LEFT JOIN scheme_master sm ON sm.id = ew.scheme " - + "LEFT JOIN fundsource_master fm ON fm.id = ew.fund_source " - + "WHERE ew.`estid`=? AND ew.`isactive`=1 AND ew.`isdelete`=0 LIMIT 1"; - return jdbcTemplate.queryForList(sql, estid); - } - - public List> getUserEstWorkStageDetailsByEstid(String estid) { - String sql = "SELECT * FROM `erp_works_stages` WHERE `estid`=? AND `isactive`=1 AND `isdelete`=0"; - return jdbcTemplate.queryForList(sql, estid); - } - - @Transactional - public String getDepartmentId(String name) { - String id="0"; - String sqlQuery ="SELECT `id` FROM `department_master` WHERE `dept_name`=?"; - List> result = jdbcTemplate.queryForList(sqlQuery, name); - if(!result.isEmpty()) { - id = ""+result.get(0).get("id"); - } - return id; - } - - @Transactional - public String getCategoryId(String name) { - String id="0"; - String sqlQuery ="SELECT `id` FROM `workstype_master` WHERE `name`=?"; - List> result = jdbcTemplate.queryForList(sqlQuery, name); - if(!result.isEmpty()) { - id = ""+result.get(0).get("id"); - } - return id; - } - - @Transactional - public String getSubCategoryId(String name) { - String id="0"; - String sqlQuery ="SELECT `id` FROM `typeofwork_master` WHERE `description`=?"; - List> result = jdbcTemplate.queryForList(sqlQuery, name); - if(!result.isEmpty()) { - id = ""+result.get(0).get("id"); - } - return id; - } - - @Transactional - public String getFundSourceId(String name) { - String id="0"; - String sqlQuery ="SELECT `id` FROM `fundsource_master` WHERE `name`=?"; - List> result = jdbcTemplate.queryForList(sqlQuery, name); - if(!result.isEmpty()) { - id = ""+result.get(0).get("id"); - } - return id; - } - - @Transactional - public String getSchemeId(String name) { - String id="0"; - String sqlQuery ="SELECT `id` FROM `scheme_master` WHERE `name`=?"; - List> result = jdbcTemplate.queryForList(sqlQuery, name); - if(!result.isEmpty()) { - id = ""+result.get(0).get("id"); - } - return id; - } - - public List> getProjectList() { - String sql = "SELECT id as pid, name FROM `project_list` WHERE isactive=1 order by name asc"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql); - - return result; // Return the result map - } - - public List> getProjectUpdatedList(String loginid) { - String sql = "SELECT " - + " pl.type, " - + " pl.department, " - + " pl.name, " - + " pfd.feedback AS status, " - + " pfd.file, " - + " pfd.cdate AS lastupdatedate " - + "FROM " - + " project_feedback_data pfd " - + "LEFT JOIN " - + " project_list pl ON pfd.pid = pl.id AND pl.isactive = 1 " - + "INNER JOIN ( " - + " SELECT " - + " pid, MAX(cdate) AS max_cdate " - + " FROM " - + " project_feedback_data " - + " WHERE " - + " isactive = 1 AND inby = ? " - + " GROUP BY " - + " pid " - + ") latest ON latest.pid = pfd.pid AND latest.max_cdate = pfd.cdate " - + "WHERE " - + " pfd.isactive = 1 AND pfd.inby = ? ORDER BY pl.name"; - // Fetch the details from the database as a Map - List> result = jdbcTemplate.queryForList(sql,loginid, loginid); - - return result; // Return the result map - } - - // Method to process the form data - public int saveProjectData(String pid, String feedback, String file, String inby) throws DataAccessException, IOException { - - // Prepare SQL Insert Query - String sql = "INSERT INTO project_feedback_data (pid, feedback, file, inby) VALUES (?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, pid, feedback, file, inby); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/package-info.java deleted file mode 100644 index a24f4547..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.works.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/.DS_Store deleted file mode 100644 index e75b5443..00000000 Binary files a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/.DS_Store and /dev/null differ diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/APIController.java deleted file mode 100644 index ec0afaed..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/APIController.java +++ /dev/null @@ -1,233 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.controller; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.springframework.security.core.Authentication; - -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -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.gccoffice.zerohours_petition.service.Petition; -import in.gov.chennaicorporation.gccoffice.zerohours_petition.service.PetitionMaster; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("gcc/api/zerohours_petition") -@RestController("zeroRest") // Mayor Petition Rest -public class APIController { - private PetitionMaster petitionMaster; - private Petition petition; - - @Autowired - public APIController(PetitionMaster petitionMaster,Petition petition) { - this.petitionMaster = petitionMaster; - this.petition = petition; - } - - @GetMapping(value="/getEventList") - public List getEvents() { - return petition.getEvents(); - } - - @GetMapping(value="/getCurrentEventList") - public List getCurrentEventList() { - return petition.getCurrentEventList(); - } - - @GetMapping(value="/getZoneAndWard") - public List getZoneAndWard() { - return petitionMaster.getZoneAndWard(); - } - - @GetMapping(value="/getCouncillor") - public List getCouncillor(@RequestParam("ward") String ward) { - return petitionMaster.getCouncillor(ward); - } - - @GetMapping(value="/getComplaintTypes") - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @GetMapping(value="/getOfficerList") - public List getOfficerList() { - return petitionMaster.getOfficerList(); - } - - @GetMapping(value="/getPetitionTypes") - public List getPetitionTypes() { - return petitionMaster.getPetitionTypes(); - } - - @GetMapping(value="/getPetitionList") - public List getPetitionList(@RequestParam("eventId") String eventId) { - return petition.getPetitionList(eventId); - } - - @GetMapping(value="/getUnmapPetitionList") - public List getUnmapPetitionList(@RequestParam("eventId") String eventId) { - return petition.getUnmapPetitionList(eventId); - } - - @GetMapping(value="/getPetitionDetails") - public List getPetitionDetails(@RequestParam("petitionNo") String petitionNo) { - return petition.getPetitionDetails(petitionNo); - } - - @PostMapping(value="/savePetition") - public String savePetition( - @RequestParam(value = "createdBy", required = false) String createdBy, - @RequestParam(value = "petitionType", required = false) String petitionType, - //@RequestParam(value = "petitionerName", required = false) String petitionerName, - //@RequestParam(value = "petitionerMobile", required = false) String petitionerMobile, - @RequestParam(value = "complaintType", required = false) String petitionerComplaint, - @RequestParam(value = "zone", required = false) String zone, - @RequestParam(value = "ward", required = false) String ward, - @RequestParam(value = "councillorName", required = false) String councillorName, - @RequestParam(value = "councillorMobile", required = false) String councillorMobile, - @RequestParam(value = "complaintNature", required = false) String complaintNature, - @RequestParam(value = "eventid", required = false) String eventid, - @RequestParam(value = "san_page1", required = false) MultipartFile page1, - @RequestParam(value = "san_page2", required = false) MultipartFile page2, - @RequestParam(value = "san_page3", required = false) MultipartFile page3, - @RequestParam(value = "san_page4", required = false) MultipartFile page4) { - - return petition.savePetition(petitionType, createdBy, zone, ward, councillorName, councillorMobile, petitionerComplaint, complaintNature, eventid,page1, page2, page3, page4); - } - - @PostMapping(value="/updatePetition") - public Boolean updatePetition( - @RequestParam(value = "petitionType", required = false) String petitionType, - @RequestParam(value = "petitionNo", required = false) String petitionNo, - @RequestParam(value = "createdBy", required = false) String createdBy, - @RequestParam(value = "petitionerName", required = false) String petitionerName, - @RequestParam(value = "petitionerMobile", required = false) String petitionerMobile, - @RequestParam(value = "petitionerAddress", required = false) String petitionerAddress, - @RequestParam(value = "petitionerPincode", required = false) String petitionerPincode, - @RequestParam(value = "complaintType", required = false) String petitionerComplaint, - @RequestParam(value = "complaintNature", required = false) String complaintNature) { - - return petition.updatePetition(petitionNo, petitionType, createdBy, petitionerName, petitionerMobile, petitionerAddress, petitionerPincode, petitionerComplaint, complaintNature); - } - - @PostMapping(value="/mapComplientToOfficer") - public Boolean updatePetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String mapOfficers) { - - String zerohours_mapping = mapOfficers; - - // First before Mapping need to unmaps old list - petition.unmapComplient(petitionId, petitionNo); - - if(zerohours_mapping!=null) { - String[] zerohours_mapping_parts = zerohours_mapping.split(","); - for (String values : zerohours_mapping_parts) { - String[] zerohours_mapping_val = values.split("_"); - if (zerohours_mapping_val.length > 0) { - String complientId = zerohours_mapping_val[0]; - String offcierId = zerohours_mapping_val[1]; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - } - } - } - return true; - } - - @PostMapping(value="/mapPetitionToOfficer") - public Boolean mapPetition( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("createdBy") String createdBy, - @RequestParam(value = "", required = false) String offidto) { - - String zerohours_mapping = offidto; - - // First before Mapping need to unmaps old list - //petition.unmapComplient(petitionId, petitionNo); - System.out.println("zerohours_mapping: "+zerohours_mapping); - if(zerohours_mapping!=null) { - - String complientId = "0"; - String offcierId = zerohours_mapping; - petition.mapComplientToOfficer(createdBy, petitionId, petitionNo, complientId, offcierId); - - } - return true; - } - - @GetMapping(value="/unmapPetition") - public String getComplaintMappingDetails( - @RequestParam("mapid") String mapid) { - return petition.unmapPetition(mapid); - } - - @GetMapping(value="/getComplaintMappingDetails") - public List getComplaintMappingDetails( - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo, - @RequestParam("complaintTypeId") String complaintTypeId) { - return petition.getComplaintMappingDetails(petitionNo,petitionId,complaintTypeId); - } - - @GetMapping(value="/getPetitionMappingDetails2") - public List getComplaintMappingDetails2( - @RequestParam("petitionId") String petitionId) { - return petition.getPetitionMappingDetails2(petitionId); - } - - @GetMapping(value="/getComplaintList") - public List getComplaintList(@RequestParam("eventId") String eventId,@RequestParam("loginId") String loginId) { - return petition.getComplaintList(eventId,loginId); - } - - @GetMapping(value="/getComplaintListByPetitionId") - public List getComplaintListByPetitionId(@RequestParam("petitionId") String petitionId) { - return petition.getComplaintListByPetitionId(petitionId); - } - - @GetMapping(value="/getComplaintDetails") - public List getComplaintDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintDetails(mapId); - } - - @GetMapping(value="/getComplaintActionDetails") - public List getComplaintActionDetails(@RequestParam("mapId") String mapId) { - return petition.getComplaintActionDetails(mapId); - } - - @PostMapping(value="/saveComplanitStatus") - public String saveComplanitStatus( - @RequestParam("createdBy") String createdBy, - @RequestParam("mapId") String mapId, - @RequestParam("complaintStatus") String complaintStatus, - @RequestParam("complaintActionText") String complaintActionText, - @RequestParam("action_san_page1") MultipartFile actionPage1, - @RequestParam("petitionId") String petitionId, - @RequestParam("petitionNo") String petitionNo) { - - return petition.saveComplanitStatus(createdBy, mapId, complaintStatus, complaintActionText, actionPage1, petitionId, petitionNo); - } - - @GetMapping("/getReportList") - public List> getReportList( - @RequestParam(value = "fromDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate, - - @RequestParam(value = "toDate", required = false) - @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate) { - - return petition.getReportList(fromDate, toDate); - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/MainController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/MainController.java deleted file mode 100644 index 7dceaeb2..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/MainController.java +++ /dev/null @@ -1,139 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.controller; - -import org.hibernate.hql.internal.ast.tree.RestrictableStatement; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.client.RestTemplate; - -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -@RequestMapping("/gcc/zerohours_petition") -@Controller("ZeorHoursPetitionController") -public class MainController { - private final RestTemplate restTemplate; - private String BasePath = "modules/zerohours_petition/"; - @Autowired - public MainController(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @GetMapping({"", "/", "/index", "/dashboard"}) - public String dashboard(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"index"; - } - - @GetMapping({"/new_petition"}) - public String newPetition(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"new_petition"; - } - - @GetMapping("/petition-ack/{petitionNo}") - public String petitionAck(Model model,@PathVariable("petitionNo") String petitionNo) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_ack"; - } - - @GetMapping("/petition-list") - public String petitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_list"; - } - - @GetMapping("/unmapped-petition-list") - public String unMappedPetitionList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"petition_not_mapped_list"; - } - - @GetMapping("/update-petition") - public String petitionUpadte(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/view-petition") - public String petitionView(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view"; - } - - @GetMapping("/view-petition-modal") - public String petitionViewModal(Model model,@RequestParam(value="petitionNo", required = false) String petitionNo) { - - if (petitionNo != null && !petitionNo.isEmpty()) { - // Decrypt the encrypted value - petitionNo = Base64Util.decodeBase64(petitionNo); - //System.out.println(petitionNo); - } - else { - petitionNo = null; - } - - - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_view_modal_page"; - } - - @GetMapping("/search-petition") - public String petitionSearch(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - //model.addAttribute("petitionNo",petitionNo); - return BasePath+"petition_update"; - } - - @GetMapping("/complaint-list") - public String complaintList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"complaint_list"; - } - - //report list - @GetMapping("/report/list") - public String pendingList(Model model) { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - return BasePath+"pending_list"; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/package-info.java deleted file mode 100644 index fadc59c3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/controller/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.controller; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/data/ComplaintType.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/data/ComplaintType.java deleted file mode 100644 index 44ef6e82..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/data/ComplaintType.java +++ /dev/null @@ -1,21 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.data; - -import java.util.Map; - -public class ComplaintType { - private int complaintTypeId; - private String complaintType; - - public ComplaintType(Map map) { - this.complaintTypeId = (int) map.get("complaint_typeid"); - this.complaintType = (String) map.get("complaint_type"); - } - - public int getComplaintTypeId() { - return complaintTypeId; - } - - public String getComplaintType() { - return complaintType; - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/data/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/data/package-info.java deleted file mode 100644 index f0eb6a3c..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/data/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.data; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/package-info.java deleted file mode 100644 index 9727141a..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * - */ -/** - * - */ -package in.gov.chennaicorporation.gccoffice.zerohours_petition; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/Petition.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/Petition.java deleted file mode 100644 index 1fa269aa..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/Petition.java +++ /dev/null @@ -1,836 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.PreparedStatement; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - -import org.springframework.transaction.annotation.Transactional; -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.stereotype.Service; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.multipart.MultipartFile; - -import in.gov.chennaicorporation.gccoffice.com_petition.data.ComplaintType; -import in.gov.chennaicorporation.gccoffice.service.Base64Util; -import in.gov.chennaicorporation.gccoffice.service.GetMappingUserDetails; -import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo; - -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -@Service("zeroHoursPetition") -public class Petition { - private JdbcTemplate jdbcTemplate; - private final Environment environment; - private PetitionMaster petitionMaster; - private GetMappingUserDetails getMappingUserDetails; - - @Autowired - public Petition(Environment environment,PetitionMaster petitionMaster,GetMappingUserDetails getMappingUserDetails) { - this.environment = environment; - this.petitionMaster = petitionMaster; - this.getMappingUserDetails = getMappingUserDetails; - } - - - @Autowired - public void setDataSource(@Qualifier("mysqlZeroHoursDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getEvents(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `event_master` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY date(`date`) DESC"; - //System.out.println(SqlQuery); - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional(readOnly = true) - public List> getCurrentEventList(){ - String SqlQuery = ""; - - //SqlQuery = "SELECT * FROM event_master WHERE date(`date`)= date(NOW())"; - SqlQuery = "SELECT * FROM event_master WHERE `isactive`=1 AND `isdelete`=0 ORDER BY date(`date`) DESC"; - //System.out.println(SqlQuery); - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - } - - @Transactional(readOnly = true) - public List getComplaintTypeList() { - return petitionMaster.getComplaintType(); - } - - @Transactional(readOnly = true) - public static List convertToComplaintTypes(List> complaintTypeMaps) { - return complaintTypeMaps.stream() - .map(ComplaintType::new) - .collect(Collectors.toList()); - } - - @Transactional(readOnly = true) - // Method to map complaint type IDs to their respective complaint types - public static String mapComplaintTypes(List complaintTypes, String complaint) { - String[] complaintIds = complaint.split(","); - StringBuilder complaintTxtBuilder = new StringBuilder(); - - for (String complaintId : complaintIds) { - int id = Integer.parseInt(complaintId); - for (ComplaintType type : complaintTypes) { - if (type.getComplaintTypeId() == id) { - if (complaintTxtBuilder.length() > 0) { - complaintTxtBuilder.append(","); - } - complaintTxtBuilder.append(type.getComplaintType()); - break; - } - } - } - - return complaintTxtBuilder.toString(); - } - - @Transactional(readOnly = true) - public List> getPetitionList(String eventid) { - try { - //String sqlQuery = "SELECT * FROM petition WHERE (`isactive`=1 AND `isdelete`=0)"; - String sqlQuery = "SELECT p.* , pt.name petition_type_name FROM petition p, petition_master.petition_types pt " - + "WHERE (p.`isactive`=1 AND p.`isdelete`=0) AND `eventid`='"+eventid+"' AND p.petition_type = pt.petition_type_id "; - List> result = jdbcTemplate.queryForList(sqlQuery); - //Base64Util.encodeBase64(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getUnmapPetitionList(String eventid) { - try { - String sqlQuery = "SELECT " - + " p.* " - + "FROM " - + " `petition` p " - + "WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) AND `eventid`='"+eventid+"' "; - //+ " AND NOT EXISTS (" - //+ " SELECT 1 " - //+ " FROM `petition_mapping` pm " - //+ " WHERE (p.`petition_id` = pm.`petition_id`) AND (pm.`isactive` = 1 AND pm.`isdelete` = 0 ) " - //+ " )"; - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - - @Transactional(readOnly = true) - public List> getPetitionDetails(String petitionNo) { - try { - String sqlQuery = "SELECT * FROM petition WHERE petition_no = ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - //System.out.println("SELECT * FROM petition WHERE petition_no = '"+petitionNo+"' AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"); - List> result = jdbcTemplate.queryForList(sqlQuery, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String savePetition( - String petitionType, - String createdBy, - String zone, - String ward, - String petitionerName, - String petitionerMobile, - String petitionerComplaint, - String complaintNature, - String eventid, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String sqlQuery = "INSERT INTO `petition` " - + "(`petition_type`, `created_by`, `petitioner_name`, `petitioner_mobile`, " - + "`petitioner_complaint`, `petitioner_complaint_txt`, `eventid`, `zone`, `ward`,`complaint_nature`) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - try { - // Complaint Type List - //List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - //List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - //String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - String petitionerComplaint_txt=""; - KeyHolder keyHolder = new GeneratedKeyHolder(); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, "1"); - ps.setString(2, createdBy); - ps.setString(3, petitionerName); - ps.setString(4, petitionerMobile); - ps.setString(5, petitionerComplaint); - ps.setString(6, petitionerComplaint_txt); - ps.setString(7, eventid); - ps.setString(8, zone); - ps.setString(9, ward); - ps.setString(10, complaintNature); - return ps; - }, keyHolder); - - // Get the last insert ID - lastInsertId = (int) keyHolder.getKey().longValue(); - - // Get the value of mp_ackno from application.properties - String ackno = environment.getProperty("zh_ackno"); - String ackno_prefix = environment.getProperty("zh_ackno_prefix"); - - // Convert ackno to int if needed - int acknoInt = Integer.parseInt(ackno); - - // Calculate the petition number - int petitionNo = (int) (lastInsertId + acknoInt); - - // Construct the petition number string - String petitionNoString = ackno_prefix + petitionNo; - - // Update the petition number in the database - updatePetitionNumber(lastInsertId, petitionNoString); - - // Add Petition Scan File in the database - addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return petitionNoString; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return "error"; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionNumber(int petitionId,String petitionNoString) { - String sqlQuery = "UPDATE `petition` SET `petition_no`='"+petitionNoString+"' WHERE `petition_id`='"+petitionId+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String addPetitionFile(String createdBy, - int petitionId, - String petitionNoString, - MultipartFile page1, - MultipartFile page2, - MultipartFile page3, - MultipartFile page4) { - - String fileName=""; - for (int i = 1; i <= 4; i++) { - MultipartFile file = null; - switch (i) { - case 1: - file = page1; - fileName = "Scan1"; - break; - case 2: - file = page2; - fileName = "Scan2"; - break; - case 3: - file = page3; - fileName = "Scan3"; - break; - case 4: - file = page4; - fileName = "Scan4"; - break; - } - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("zh_foldername"); - uploadDirectory = uploadDirectory + serviceFolderName; - - // File name - fileName = petitionId + "_" + fileName + "_" + petitionNoString + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "INSERT INTO `pentition_files`(`created_by`, `file_name`, `file_size`, `file_type`, `petition_no`, `petition_id`) " - + "VALUES ('"+createdBy+"','"+fileName+"','"+fileSize+"','"+fileType+"','"+petitionNoString+"','"+petitionId+"')"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - - } - return "success"; - } - - @Transactional - public boolean updatePetition( - String petitionNo, - String petitionType, - String createdBy, - String petitionerName, - String petitionerMobile, - String petitionerAddress, - String petitionerPincode, - String petitionerComplaint, - String complaintNature) { - - try { - // Complaint Type List - List complaintTypelist = getComplaintTypeList(); - // Convert the list of maps to a list of ComplaintType objects - List complaintTypes = convertToComplaintTypes(complaintTypelist); - - // Map complaint types - String petitionerComplaint_txt = mapComplaintTypes(complaintTypes, petitionerComplaint); - /* - String sqlQuery = "UPDATE `petition` SET " - //+ "`petition_type`='"+petitionType+"', " - + "`created_by`='"+createdBy+"', `petitioner_name`='"+petitionerName+"', `petitioner_mobile`='"+petitionerMobile+"', " - //+ "`petitioner_address`='"+petitionerAddress+"', `petitioner_pincode`='"+petitionerPincode+"'," - + "`petitioner_complaint`='"+petitionerComplaint+"', `petitioner_complaint_txt`='"+petitionerComplaint_txt+"', `complaint_nature`='"+complaintNature+"' " - + "WHERE (`petition_no`='"+petitionNo+"') LIMIT 1"; - System.out.println(sqlQuery); - // Use JdbcTemplate's update method to execute the query with parameters - jdbcTemplate.update(sqlQuery); - */ - String sqlQuery = "UPDATE `petition` SET " - + "`petition_type` = ?, `created_by` = ?, `petitioner_name` = ?, `petitioner_mobile` = ?, " - + "`petitioner_address` = ?, `petitioner_pincode` = ?, `petitioner_complaint` = ?, " - + "`petitioner_complaint_txt` = ?, `complaint_nature` = ? " - + "WHERE `petition_no` = ? LIMIT 1"; - - int rowsUpdated = jdbcTemplate.update(sqlQuery, - petitionType, - createdBy, - petitionerName, - petitionerMobile, - petitionerAddress, - petitionerPincode, - petitionerComplaint, - petitionerComplaint_txt, // Safely includes single quotes - complaintNature, - petitionNo - ); - - // Add Petition Scan File in the database - // addPetitionFile(createdBy,lastInsertId, petitionNoString, page1, page2, page3, page4); - - return true; // If no exception, query executed successfully - } catch (DataAccessException e) { - // Handle exception (e.g., log error) - e.printStackTrace(); - return false; // Query execution failed - } - } - - @Transactional - public boolean updatePetitionStatus(String petitionId,String petitionNo) { - String status_value = "close"; - List> petitionMappingDetails = getPetitionMappingDetails(petitionNo, petitionId); - - for (Map mapping : petitionMappingDetails) { - // Access values from the map using keys - Object status = mapping.get("status"); - // Check if status is "close" - if (!"close".equals(status)) { - status_value = "partial"; - } - } - - String sqlQuery = "UPDATE `petition` SET `status`='"+status_value+"' WHERE `petition_no`='"+petitionNo+"' AND `petition_id`='"+petitionId+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails(String petitionNo, String petitionId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getPetitionMappingDetails2(String petitionId) { - try { - String sqlQuery = "SELECT pm.mapid,pm.petition_no,pm.petition_id,pm.status,om.* FROM zerohours_petition.petition_mapping as pm,petition_master.officer_master_zh as om WHERE (pm.`petition_id`= ?) AND (pm.`isactive`=1 AND pm.`isdelete`=0) AND pm.off_id=om.off_id"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId); - System.out.println(sqlQuery + petitionId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public boolean unmapComplient(String petitionId, String petitionNo) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `petition_id`='"+petitionId+"' AND `petition_no`='"+petitionNo+"'"; - jdbcTemplate.update(sqlQuery); - return true; - } - - @Transactional - public String unmapPetition(String mapid) { - String sqlQuery = "UPDATE `petition_mapping` SET `isactive`='0',`isdelete`='1' WHERE `mapid`='"+mapid+"'"; - jdbcTemplate.update(sqlQuery); - return "success"; - } - - @Transactional - public boolean mapComplientToOfficer( - String createdBy, String petitionId, String petitionNo, String complaintId, String officerId) { - String sqlQuery = "INSERT INTO `petition_mapping`" - + "(`created_by`, `off_id`, `petition_no`, `complaint_typeid`, `petition_id`) " - + "VALUES (?, ?, ?, ?, ?)"; - jdbcTemplate.update(sqlQuery, createdBy, officerId, petitionNo, complaintId, petitionId); - return true; - } - - @Transactional - public boolean updateMapComplientStatus(String mapId,String status) { - String sqlQuery = "UPDATE `petition_mapping` SET `status`=? WHERE `mapid`=? LIMIT 1"; - jdbcTemplate.update(sqlQuery, status, mapId); - System.out.println(sqlQuery); - return true; - } - - @Transactional(readOnly = true) - public List> getComplaintMappingDetails(String petitionNo, String petitionId, String complaintTypeId) { - try { - String sqlQuery = "SELECT * FROM petition_mapping WHERE (`petition_id`= ? AND petition_no = ?) AND `complaint_typeid`= ? AND (`isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, petitionId, petitionNo,complaintTypeId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintList(String eventId, String loginId) { - String sqlQuery = ""; - try { - sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm` " - + " FROM " - + " `petition` p, `petition_mapping` pm, `petition_master`.`officer_master_zh` om" - + " WHERE " - + " (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - //+ " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " AND p.eventid='"+eventId+"' "; - - String officerMaster = getMappingUserDetails.getOfficerMaster(loginId); - - //if (officerMaster != null && !officerMaster.isEmpty() && loginId!='256') { - if (!loginId.equals("256") && !loginId.equals("1")) { - sqlQuery = sqlQuery + " AND (pm.off_id IN("+officerMaster+"))"; - } - - System.out.println(sqlQuery + loginId); - - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - //System.out.println(petitionNo + " : "+petitionNoEncoded + " : "+Base64Util.encodeBase64(petitionNo)); - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintListByPetitionId(String petitionId) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, p.`status` petition_status, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status` complaint_status, pm.`cdate` mappedOn, om.`off_nm`, ctype.`complaint_type` " - + " FROM " - + " `zerohours_petition`.`petition` p,`zerohours_petition`.`petition_mapping` pm, `petition_master`.`officer_master_zh` om, `petition_master`.`complaint_types` ctype " - + " WHERE " - + " (p.`petition_id` = '"+petitionId+"' AND p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - + " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintDetails(String mapid) { - try { - String sqlQuery = "SELECT " - + " p.`petition_id`, p.`cdate`, p.`created_by`, p.`isactive`, p.`isdelete`, p.`petition_no`, " - + " p.`petitioner_address`, p.`petitioner_complaint`, p.`petitioner_complaint_txt`, " - + " p.`petitioner_mobile`, p.`petitioner_name`, p.`complaint_nature`, p.`petitioner_pincode`, " - + " pm.`mapid`, pm.`complaint_typeid`, pm.`off_id`, pm.`status`, om.`off_nm` " - + " FROM " - + " `petition` p,`petition_mapping` pm, `petition_master`.`officer_master_zh` om" - + " WHERE " - + " pm.`mapid`='"+mapid+"' " - + " AND (p.`isactive` = 1 AND p.`isdelete` = 0) " - + " AND (pm.`isactive` = 1 AND pm.`isdelete` = 0) " - + " AND (om.`isactive` = 1 AND om.`isdelete` = 0) " - + " AND (om.`off_id` = pm.`off_id`) " - //+ " AND (ctype.`complaint_typeid` = pm.`complaint_typeid`) " - + " AND (p.`petition_id` = pm.`petition_id`)" - + " "; - //System.out.println(sqlQuery); - List> result = jdbcTemplate.queryForList(sqlQuery); - - // Iterate over the list of maps - for (Map map : result) { - // Get the value of the 'petitionNo' field from the map - String petitionNo = (String) map.get("petition_no"); - - // Encode the 'petitionNo' value using Base64Util - String petitionNoEncoded = Base64Util.encodeBase64(petitionNo); - - // Add the encoded value as 'petitionNoEncode' to the map - map.put("petitionNoEncode", petitionNoEncoded); - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional(readOnly = true) - public List> getComplaintActionDetails(String mapId) { - try { - String sqlQuery = "SELECT * FROM `petition_action_taken` WHERE (`mapid`= ? AND `isactive`=1 AND `isdelete`=0) LIMIT 1"; - List> result = jdbcTemplate.queryForList(sqlQuery, mapId); - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return null; // Return null or handle error appropriately - } - } - - @Transactional - public String saveComplanitStatus( - String createdBy, - String mapId, - String complaintStatus, - String complaintActionText, - MultipartFile actionPage1, - String petitionId, - String petitionNo) { - - //System.out.println("I am from Service Page "+petitionerName); - - //String complaintNature = ""; - int lastInsertId = 0; - String selectQuery ="Select solmapid,count(`solmapid`) as total FROM `petition_action_taken` WHERE mapid=?"; - List> result = jdbcTemplate.queryForList(selectQuery, mapId); - int total = (result.isEmpty()) ? 0 : ((Number) result.get(0).get("total")).intValue(); - - String sqlQuery; - boolean isUpdate = total > 0; // If total > 0, we will update, otherwise insert - System.out.println("selectQuery: "+selectQuery); - System.out.println("isUpdate: "+isUpdate +" mapId: "+mapId); - if (isUpdate) { - lastInsertId = (int) result.get(0).get("solmapid"); - // Update existing record - sqlQuery = "UPDATE `petition_action_taken` SET `created_by` = ?, `off_id` = ?,`mapid`=?, `status` = ?, `comments` = ? WHERE `mapid` = '"+mapId+"'"; - } else { - // Insert new record - sqlQuery = "INSERT INTO `petition_action_taken` " - + "(`created_by`, `off_id`, `mapid`, `status`, `comments`) " - + "VALUES (?, ?, ?, ?, ?)"; - } - - try { - KeyHolder keyHolder = new GeneratedKeyHolder(); - int rowsAffected = jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS); - ps.setString(1, createdBy); - ps.setString(2, createdBy); - ps.setString(3, mapId); - ps.setString(4, complaintStatus); - ps.setString(5, complaintActionText); - return ps; - }, keyHolder); - - if (rowsAffected > 0) { - if (!isUpdate) { - Number key = keyHolder.getKey(); - if (key != null) { - lastInsertId = key.intValue(); - // Continue with further processing - } else { - - // Handle the case when the key is null - System.out.println("Insertion succeeded but no key was generated."); - return String.valueOf(rowsAffected); // Or some other appropriate response - } - } - } else { - System.out.println("Insertion failed, no rows affected."); - return "error"; - } - - // Further logic to update status and add files - if (lastInsertId > 0) { - updateMapComplientStatus(mapId, "close"); - updatePetitionStatus(petitionId, petitionNo); - addActionFile(mapId, lastInsertId, actionPage1); - return String.valueOf(lastInsertId); - } - - } catch (DataAccessException e) { - e.printStackTrace(); - return "error"; - } - return ""; - } - - @Transactional - public String addActionFile( String mapId, int solmapid, - MultipartFile page1) { - - MultipartFile file = page1; - String fileName = "Scan1_"+solmapid; - - if (file != null && !file.isEmpty()) { - try { - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("zh_foldername"); - String serviceActionFolderName = environment.getProperty("zh_action_Foldername"); - - uploadDirectory = uploadDirectory + serviceFolderName +"/"+ serviceActionFolderName; - - // File name - fileName = mapId + "_" + fileName + "_" + file.getOriginalFilename(); - - //File Size - Long fileSize = file.getSize(); - - // File Type - String fileType = file.getContentType(); - - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - String filePath = uploadDirectory + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Write the bytes to the file - Files.write(path, bytes); - - // Save the file path to a database - String sqlQuery = "UPDATE `petition_action_taken` SET " - + "`file_name`='"+fileName+"', " - + "`file_size`='"+fileSize+"', " - + "`file_type`='"+fileType+"' " - + "WHERE `solmapid`='"+solmapid+"' LIMIT 1"; - jdbcTemplate.update(sqlQuery); - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } - } - return "success"; - } - - //Report List - @Transactional(readOnly = true) - public List> getReportList(Date fromDate, Date toDate) { - try { - StringBuilder sql = new StringBuilder( - "SELECT p.petition_no, p.zone, p.ward, p.petitioner_name, " + - "p.petitioner_mobile, p.complaint_nature, zh.off_nm AS officer_name, " + - "zh.off_id AS officer_id, pm.status " + - "FROM zerohours_petition.petition_mapping pm " + - "LEFT JOIN zerohours_petition.petition p " + - "ON p.petition_id = pm.petition_id " + - "LEFT JOIN petition_master.officer_master_zh zh " + - "ON zh.off_id = pm.off_id " - ); - - List params = new ArrayList<>(); - - if (fromDate != null && toDate != null) { - // Ensure toDate includes full day - Calendar cal = Calendar.getInstance(); - cal.setTime(toDate); - cal.set(Calendar.HOUR_OF_DAY, 23); - cal.set(Calendar.MINUTE, 59); - cal.set(Calendar.SECOND, 59); - cal.set(Calendar.MILLISECOND, 999); - Date toDateEnd = cal.getTime(); - - sql.append("WHERE date(pm.cdate) BETWEEN ? AND ? "); - params.add(fromDate); - params.add(toDateEnd); - } - - List> result = jdbcTemplate.queryForList( - sql.toString(), params.toArray() - ); - - for (Map map : result) { - String petitionNo = (String) map.get("petition_no"); - if (petitionNo != null) { - map.put("petitionNoEncode", Base64Util.encodeBase64(petitionNo)); - } - } - - return result; - } catch (DataAccessException e) { - e.printStackTrace(); - return Collections.emptyList(); - } - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/PetitionMaster.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/PetitionMaster.java deleted file mode 100644 index c87207a6..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/PetitionMaster.java +++ /dev/null @@ -1,90 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.service; - -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("ZeroPetitionMaster") -public class PetitionMaster { - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlPetitionMasterDataSource") DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Transactional(readOnly = true) - public List> getZoneAndWard(){ - String SqlQuery = ""; - - SqlQuery = "SELECT " - + " CAST(zone AS UNSIGNED) AS zone, " - + " GROUP_CONCAT(CAST(divid AS UNSIGNED) ORDER BY CAST(divid AS UNSIGNED) ASC) AS wards " - + "FROM " - + " councillor " - + "GROUP BY " - + " CAST(zone AS UNSIGNED) " - + "ORDER BY " - + " CAST(zone AS UNSIGNED) ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getCouncillor(String ward){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM councillor WHERE `divid`='"+ward+"' LIMIT 1"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getComplaintType(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `complaint_types` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getOfficerList(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `officer_master_zh` WHERE `isactive`=1 AND `isdelete`=0"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } - - @Transactional(readOnly = true) - public List> getPetitionTypes(){ - String SqlQuery = ""; - - SqlQuery = "SELECT * FROM `petition_types` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby` ASC"; - - List> result = jdbcTemplate.queryForList(SqlQuery); - - return result; - - } -} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/package-info.java b/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/package-info.java deleted file mode 100644 index bf7547f3..00000000 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/zerohours_petition/service/package-info.java +++ /dev/null @@ -1 +0,0 @@ -package in.gov.chennaicorporation.gccoffice.zerohours_petition.service; \ No newline at end of file diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController_PosterRemoval.java b/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController_PosterRemoval.java new file mode 100644 index 00000000..345b1c5e --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController_PosterRemoval.java @@ -0,0 +1,113 @@ +package in.gov.chennaicorporation.mobileservice.busshelters.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +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.busshelters.service.BusShelterPosterRemovalActivity; + +@RequestMapping("/gccofficialapp/api/busshelter/posterremoval/") +@RestController("busshelterPosterRemovalRest") +public class BusShelterController_PosterRemoval { + @Autowired + private JdbcTemplate jdbcBusShelterTemplate; + @Autowired + private BusShelterPosterRemovalActivity BusShelterPosterRemovalActivity; + + @GetMapping(value = "/getBusShelterList") + public List getBusShelterList(@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 BusShelterPosterRemovalActivity.getBusShelterList(formData, latitude, longitude, loginId); + } + + @GetMapping(value = "/getParentQuestionsList") + public List getParentQuestionsList( + @RequestParam(value = "loginId", required = false) String cby, + @RequestParam(value = "qtype", required = true) String qtype) { + return BusShelterPosterRemovalActivity.getParentQuestionsList(qtype); + } + + @GetMapping(value = "/getChildQuestionsList") + public List getChildQuestionsList( + @RequestParam(value = "loginId", required = false) String cby, + @RequestParam(value = "pid", required = true) String pid) { + return BusShelterPosterRemovalActivity.getChildQuestionsList(pid); + } + + @PostMapping(value = "/saveFeedback") + public List saveFeedback( + @RequestParam(value = "shelter_id", required = true) String shelter_id, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "action", required = true) String type, + @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 = false) MultipartFile filedata, + + @RequestParam(value = "file_1", required = false) MultipartFile file_1, + @RequestParam(value = "file_2", required = false) MultipartFile file_2, + @RequestParam(value = "file_3", required = false) MultipartFile file_3, + @RequestParam(value = "file_4", required = false) MultipartFile file_4, + @RequestParam(value = "file_5", required = false) MultipartFile file_5, + @RequestParam(value = "file_6", required = false) MultipartFile file_6, + @RequestParam(value = "file_7", required = false) MultipartFile file_7, + @RequestParam(value = "file_8", required = false) MultipartFile file_8, + @RequestParam(value = "file_9", required = false) MultipartFile file_9, + @RequestParam(value = "file_10", required = false) MultipartFile file_10, + @RequestParam(value = "file_11", required = false) MultipartFile file_11) { + return BusShelterPosterRemovalActivity.saveFeedback(shelter_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, + file_1, file_2, file_3, file_4, file_5, file_6, file_7, file_8, file_9, file_10, file_11, type); + } + + @GetMapping(value = "/getZoneReport") + public List getZoneReport( + @RequestParam(value = "loginId", required = true) String cby) { + return BusShelterPosterRemovalActivity.getZoneReport(cby); + } + + @GetMapping(value = "/getWardReport") + public List getWardReport( + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone) { + return BusShelterPosterRemovalActivity.getWardReport(cby, zone); + } + + @GetMapping(value = "/getCompletedReport") + public List getCompletedReport( + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "ward", required = true) String ward) { + return BusShelterPosterRemovalActivity.getCompletedReport(cby, ward); + } + + @GetMapping(value = "/getPendingReport") + public List getPendingReport( + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "ward", required = true) String ward) { + return BusShelterPosterRemovalActivity.getPendingReport(cby, ward); + } + +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java b/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java index a3f790d8..bde814f6 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java @@ -45,257 +45,257 @@ import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; @Service public class BusShelterActivity { private JdbcTemplate jdbcBusShelterTemplate; - + 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 + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired public void setDataSource(@Qualifier("mysqlBusShelterDataSource") DataSource BusShelterDataSource) { this.jdbcBusShelterTemplate = new JdbcTemplate(BusShelterDataSource); } - - @Autowired + + @Autowired public BusShelterActivity(Environment environment) { this.environment = environment; - this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + 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(); - } - + + 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(); + } + public static String generateRandomStringForFile(int String_Lenth) { - StringBuilder result = new StringBuilder(String_Lenth); - for (int i = 0; i < STRING_LENGTH; i++) { - result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); - } - return result.toString(); - } - + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + private byte[] compressImage(BufferedImage image, float quality) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); - ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); - writer.setOutput(imageOutputStream); + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); - ImageWriteParam param = writer.getDefaultWriteParam(); - if (param.canWriteCompressed()) { - param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - param.setCompressionQuality(quality); - } + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); - writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + writer.dispose(); + imageOutputStream.close(); - writer.dispose(); - imageOutputStream.close(); + return byteArrayOutputStream.toByteArray(); + } - return byteArrayOutputStream.toByteArray(); - } - public String fileUpload(String name, String id, MultipartFile file) { - + int lastInsertId = 0; // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("busshelter_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 - 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; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Compress the image - BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); - byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality - - // Write the bytes to the file - Files.write(path, bytes); - - System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("busshelter_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 + 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; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } } - + ////////////////////////////// public String getConfigValue() { - String sqlQuery = "SELECT `id`, `lat_long_radius` FROM `config` LIMIT 1"; - String value = "50"; // default fallback value - List> results = jdbcBusShelterTemplate.queryForList(sqlQuery); + String sqlQuery = "SELECT `id`, `lat_long_radius` FROM `config` LIMIT 1"; + String value = "50"; // default fallback value + List> results = jdbcBusShelterTemplate.queryForList(sqlQuery); - if (!results.isEmpty()) { - Map row = results.get(0); - value = String.valueOf(row.get("lat_long_radius")); // corrected key name - } + if (!results.isEmpty()) { + Map row = results.get(0); + value = String.valueOf(row.get("lat_long_radius")); // corrected key name + } - return value; + return value; } - - + ////////////////////////////// - - public List> getBusShelterList( - MultiValueMap formData, + + public List> getBusShelterList( + MultiValueMap formData, String latitude, String longitude, - String loginid - ) { - - String sqlWhere = ""; - String radius = getConfigValue(); - - if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() - && !longitude.isEmpty()) { - sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude - + ")) * cos(radians(bsl.latitude)) * cos(radians(bsl.longitude) - radians(" + longitude - + ")) + sin(radians(" + latitude + ")) * sin(radians(bsl.latitude)), 9))) < "+radius+")" - + " ORDER BY" + String loginid) { + + String sqlWhere = ""; + String radius = getConfigValue(); + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(bsl.latitude)) * cos(radians(bsl.longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(bsl.latitude)), 9))) < " + radius + ")" + + " ORDER BY" + " bsl.`id` DESC"; } - - String sql = "SELECT " - + " bsl.*, " - + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', bsl.image) AS photo, " - + " bf.type AS qtype, " - + " DATE_FORMAT(bf.latest_feedback_date, '%d-%m-%Y') AS latestfeedbackdate " - + "FROM " - + " bus_shelter_list bsl " - + "LEFT JOIN ( " - + " SELECT " - + " bsf.shelter_id, " - + " bsf.type, " - + " bsf.cdate AS latest_feedback_date " - + " FROM " - + " bus_shelter_feedback bsf " - + " INNER JOIN ( " - + " SELECT " - + " shelter_id, " - + " MAX(id) AS max_id " - + " FROM " - + " bus_shelter_feedback " - + " GROUP BY shelter_id " - + " ) latest ON bsf.shelter_id = latest.shelter_id AND bsf.id = latest.max_id " - + ") bf ON bsl.id = bf.shelter_id " - + "WHERE " - + " bsl.isactive = 1 " - + " AND bsl.gcc_app_updated = 0 "+sqlWhere; - System.out.println(sql); - List> result = jdbcBusShelterTemplate.queryForList(sql); - + + String sql = "SELECT " + + " bsl.*, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bsl.image) AS photo, " + + " bf.type AS qtype, " + + " DATE_FORMAT(bf.latest_feedback_date, '%d-%m-%Y') AS latestfeedbackdate " + + "FROM " + + " bus_shelter_list bsl " + + "LEFT JOIN ( " + + " SELECT " + + " bsf.shelter_id, " + + " bsf.type, " + + " bsf.cdate AS latest_feedback_date " + + " FROM " + + " bus_shelter_feedback bsf " + + " INNER JOIN ( " + + " SELECT " + + " shelter_id, " + + " MAX(id) AS max_id " + + " FROM " + + " bus_shelter_feedback " + + " GROUP BY shelter_id " + + " ) latest ON bsf.shelter_id = latest.shelter_id AND bsf.id = latest.max_id " + + ") bf ON bsl.id = bf.shelter_id " + + "WHERE " + + " bsl.isactive = 1 " + + " AND bsl.gcc_app_updated = 0 " + sqlWhere; + System.out.println(sql); + List> result = jdbcBusShelterTemplate.queryForList(sql); + Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Bus Shelter List."); - response.put("data", result); - - return Collections.singletonList(response); - } - - public List> getQuestionsList() { - String sql = "SELECT * FROM question_list WHERE isactive=1"; - List> result = jdbcBusShelterTemplate.queryForList(sql); + response.put("status", "Success"); + response.put("message", "Bus Shelter List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getQuestionsList() { + String sql = "SELECT * FROM question_list WHERE isactive=1"; + List> result = jdbcBusShelterTemplate.queryForList(sql); Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Bus Shelter Question List."); - response.put("data", result); - - return Collections.singletonList(response); - } - + response.put("status", "Success"); + response.put("message", "Bus Shelter Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + public List> getParentQuestionsList(String qtype) { - //String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=0 AND `qtype` LIKE ?"; - String sql = "SELECT ql.id AS question_id, ql.q_english, ql.q_tamil, " - + "ql.isactive, ql.img_required, ql.pid, ql.qtype, ql.feedbacktype, " - + "CASE WHEN ql.feedbacktype = 'select' THEN JSON_ARRAYAGG" - + "( JSON_OBJECT( 'option_id', qov.id, 'english_name', qov.english_name, 'tamil_name', " - + "qov.tamil_name, 'value', qov.value, 'isactive', qov.isactive, 'isdelete', qov.isdelete ) ) " - + "ELSE NULL END AS options FROM question_list ql " - + "LEFT JOIN q_option_value qov ON qov.qid = ql.id " - + "AND ql.feedbacktype = 'select' WHERE ql.isactive = 1 AND `pid`=0 AND `qtype` LIKE ? GROUP BY ql.id"; - - List> result = jdbcBusShelterTemplate.queryForList(sql,"%" + qtype + "%"); - - ObjectMapper mapper = new ObjectMapper(); - for (Map row : result) { - Object optionsRaw = row.get("options"); - if (optionsRaw != null && optionsRaw instanceof String) { - try { - List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); - row.put("options", optionsParsed); - } catch (Exception e) { - row.put("options", null); // fallback if malformed - } - } - } - + // String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=0 AND + // `qtype` LIKE ?"; + String sql = "SELECT ql.id AS question_id, ql.q_english, ql.q_tamil, " + + "ql.isactive, ql.img_required, ql.pid, ql.qtype, ql.feedbacktype, ql.img_is_mandatory, " + + "CASE WHEN ql.feedbacktype = 'select' THEN JSON_ARRAYAGG" + + "( JSON_OBJECT( 'option_id', qov.id, 'english_name', qov.english_name, 'tamil_name', " + + "qov.tamil_name, 'value', qov.value, 'isactive', qov.isactive, 'isdelete', qov.isdelete ) ) " + + "ELSE NULL END AS options FROM question_list ql " + + "LEFT JOIN q_option_value qov ON qov.qid = ql.id " + + "AND ql.feedbacktype = 'select' WHERE ql.isactive = 1 AND `pid`=0 AND `qtype` LIKE ? GROUP BY ql.id"; + + List> result = jdbcBusShelterTemplate.queryForList(sql, "%" + qtype + "%"); + + ObjectMapper mapper = new ObjectMapper(); + for (Map row : result) { + Object optionsRaw = row.get("options"); + if (optionsRaw != null && optionsRaw instanceof String) { + try { + List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); + row.put("options", optionsParsed); + } catch (Exception e) { + row.put("options", null); // fallback if malformed + } + } + } + Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Bus Shelter Parent Question List."); - response.put("data", result); - - return Collections.singletonList(response); - } - + response.put("status", "Success"); + response.put("message", "Bus Shelter Parent Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + public List> getChildQuestionsList(String pid) { - String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=?"; - List> result = jdbcBusShelterTemplate.queryForList(sql,pid); + String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=?"; + List> result = jdbcBusShelterTemplate.queryForList(sql, pid); Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Bus Shelter Child Question List."); - response.put("data", result); - - return Collections.singletonList(response); - } - + response.put("status", "Success"); + response.put("message", "Bus Shelter Child Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + public String inactiveFeedBack(String type, String toilet_id) { - + String sql = "UPDATE `bus_shelter_feedback` SET `isactive`=0 WHERE DATE(`bus_shelter_feedback`.`cdate`) = CURDATE() AND `type`= ? AND `shelter_id`=?"; - jdbcBusShelterTemplate.update(sql,type,toilet_id); - + jdbcBusShelterTemplate.update(sql, type, toilet_id); + return "sussess"; - } + } @Transactional public List> saveFeedback( String shelter_id, String cby, String latitude, - String longitude, - String zone, + String longitude, + String zone, String ward, String q_1, String q_2, @@ -310,17 +310,17 @@ public class BusShelterActivity { String q_11, String remarks, MultipartFile file, - - MultipartFile file_1, - MultipartFile file_2, - MultipartFile file_3, - MultipartFile file_4, - MultipartFile file_5, - MultipartFile file_6, - MultipartFile file_7, - MultipartFile file_8, - MultipartFile file_9, - MultipartFile file_10, + + MultipartFile file_1, + MultipartFile file_2, + MultipartFile file_3, + MultipartFile file_4, + MultipartFile file_5, + MultipartFile file_6, + MultipartFile file_7, + MultipartFile file_8, + MultipartFile file_9, + MultipartFile file_10, MultipartFile file_11, String type) { List> result = null; @@ -339,62 +339,62 @@ public class BusShelterActivity { String image_q9 = ""; String image_q10 = ""; String image_q11 = ""; - + var year = DateTimeUtil.getCurrentYear(); var month = DateTimeUtil.getCurrentMonth(); - + // Handle file upload if a file is provided if (file != null && !file.isEmpty()) { image = fileUpload("feedback", "0", file); } - + // Question Images if (file_1 != null && !file_1.isEmpty()) { image_q1 = fileUpload("1", "q1", file_1); } - + if (file_2 != null && !file_2.isEmpty()) { image_q2 = fileUpload("2", "q2", file_2); } - + if (file_3 != null && !file_3.isEmpty()) { image_q3 = fileUpload("3", "q3", file_3); } - + if (file_4 != null && !file_4.isEmpty()) { image_q4 = fileUpload("4", "q4", file_4); } - + if (file_5 != null && !file_5.isEmpty()) { image_q5 = fileUpload("5", "q5", file_5); } - + if (file_6 != null && !file_6.isEmpty()) { image_q6 = fileUpload("6", "q6", file_6); } - + if (file_7 != null && !file_7.isEmpty()) { image_q7 = fileUpload("7", "q7", file_7); } - + if (file_8 != null && !file_8.isEmpty()) { image_q8 = fileUpload("8", "q8", file_8); } - + if (file_9 != null && !file_9.isEmpty()) { image_q9 = fileUpload("9", "q9", file_9); } - + if (file_10 != null && !file_10.isEmpty()) { image_q10 = fileUpload("10", "q10", file_10); } - + if (file_11 != null && !file_11.isEmpty()) { image_q11 = fileUpload("11", "q11", file_11); } - + String feedbackimg = image; - + String q1_image = image_q1; String q2_image = image_q2; String q3_image = image_q3; @@ -406,18 +406,18 @@ public class BusShelterActivity { String q9_image = image_q9; String q10_image = image_q10; String q11_image = image_q11; - - //String type = // Get before & after - + + // String type = // Get before & after + // Get today's date - LocalDate today = LocalDate.now(); + LocalDate today = LocalDate.now(); + + // Format it in the desired format (yyyy-MM-dd) + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayDate = today.format(formatter); - // Format it in the desired format (yyyy-MM-dd) - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - String todayDate = today.format(formatter); - inactiveFeedBack(type, shelter_id); // Upadte already insert data. - + String sqlQuery = "INSERT INTO `bus_shelter_feedback`(" + "`shelter_id`, `cby`, " + "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, " @@ -428,7 +428,7 @@ public class BusShelterActivity { + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); - + try { int affectedRows = jdbcBusShelterTemplate.update(new PreparedStatementCreator() { @Override @@ -454,7 +454,7 @@ public class BusShelterActivity { ps.setString(18, ward); ps.setString(19, type); ps.setString(20, feedbackimg); - + ps.setString(21, q1_image); ps.setString(22, q2_image); ps.setString(23, q3_image); @@ -502,6 +502,5 @@ public class BusShelterActivity { return Collections.singletonList(response); } - - + } diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterPosterRemovalActivity.java b/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterPosterRemovalActivity.java new file mode 100644 index 00000000..bba7cd6d --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterPosterRemovalActivity.java @@ -0,0 +1,728 @@ +package in.gov.chennaicorporation.mobileservice.busshelters.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.LocalDate; +import java.time.format.DateTimeFormatter; +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 com.fasterxml.jackson.databind.ObjectMapper; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class BusShelterPosterRemovalActivity { + private JdbcTemplate jdbcBusShelterTemplate; + + 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("mysqlBusShelterDataSource") DataSource BusShelterDataSource) { + this.jdbcBusShelterTemplate = new JdbcTemplate(BusShelterDataSource); + } + + @Autowired + public BusShelterPosterRemovalActivity(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(); + } + + 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); + + 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("busshelter_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 + 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; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + ////////////////////////////// + public String getConfigValue(int id) { + String sqlQuery = "SELECT `id`, `lat_long_radius` FROM `config` where id = ? LIMIT 1"; + String value = "50"; // default fallback value + List> results = jdbcBusShelterTemplate.queryForList(sqlQuery, id); + + if (!results.isEmpty()) { + Map row = results.get(0); + value = String.valueOf(row.get("lat_long_radius")); // corrected key name + } + + return value; + } + + ////////////////////////////// + + public List> getBusShelterList( + MultiValueMap formData, + String latitude, + String longitude, + String loginid) { + + String configSql = "SELECT fromdate, todate FROM bus_shelter_activity_master WHERE id = 3 AND isactive = 1"; + + Map config = jdbcBusShelterTemplate.queryForMap(configSql); + String fromDate = config.get("fromdate").toString(); + String toDate = config.get("todate").toString(); + + String sqlWhere = ""; + String radius = getConfigValue(1); + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(bsl.latitude)) * cos(radians(bsl.longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(bsl.latitude)), 9))) < " + radius + ")" + + " ORDER BY bsl.`road` ASC"; + } else { + sqlWhere += " ORDER BY bsl.road ASC"; + } + + String sql = "SELECT bsl.*, bsprf.type, bsprf.cdate AS feedbackdate, " + + "CASE " + + "WHEN bsprf.type IS NULL OR bsprf.type = '' THEN 'Before' " + + "WHEN LOWER(bsprf.type) = 'before' THEN 'After' " + + "WHEN LOWER(bsprf.type) = 'after' THEN 'Completed' " + + "ELSE 'Before' END AS current_btn " + + "FROM bus_shelter_list bsl " + + "LEFT JOIN (SELECT t1.* " + + " FROM bus_shelter_poster_removal_feedback t1 " + + " INNER JOIN ( " + + " SELECT shelter_id, MAX(id) AS id " + + " FROM bus_shelter_poster_removal_feedback " + + " WHERE isactive = 1 " + + " GROUP BY shelter_id " + + " ) t2 " + + " ON t1.id = t2.id) bsprf ON bsprf.shelter_id = bsl.id " + + "AND bsprf.isactive = 1 AND DATE(bsprf.cdate) BETWEEN ? AND ? " + + "where bsl.isactive=1 " + sqlWhere; + System.out.println(sql); + List> result = jdbcBusShelterTemplate.queryForList(sql, fromDate, toDate); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getQuestionsList() { + String sql = "SELECT * FROM question_list WHERE isactive=1"; + List> result = jdbcBusShelterTemplate.queryForList(sql); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getParentQuestionsList(String qtype) { + // String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=0 AND + // `qtype` LIKE ?"; + String sql = "SELECT ql.id AS question_id, ql.q_english, ql.q_tamil, " + + "ql.isactive, ql.img_required,ql.img_is_mandatory, ql.pid, ql.qtype, ql.feedbacktype, " + + "CASE WHEN ql.feedbacktype = 'select' THEN JSON_ARRAYAGG" + + "( JSON_OBJECT( 'option_id', qov.id, 'english_name', qov.english_name, 'tamil_name', " + + "qov.tamil_name, 'value', qov.value, 'isactive', qov.isactive, 'isdelete', qov.isdelete ) ) " + + "ELSE NULL END AS options FROM question_list ql " + + "LEFT JOIN q_option_value qov ON qov.qid = ql.id " + + "AND ql.feedbacktype = 'select' WHERE ql.isactive = 1 AND ql.`typeid`=3 AND `pid`=0 AND `qtype` LIKE ? GROUP BY ql.id ORDER BY ql.orderby ASC"; + + List> result = jdbcBusShelterTemplate.queryForList(sql, "%" + qtype + "%"); + + ObjectMapper mapper = new ObjectMapper(); + for (Map row : result) { + Object optionsRaw = row.get("options"); + if (optionsRaw != null && optionsRaw instanceof String) { + try { + List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); + row.put("options", optionsParsed); + } catch (Exception e) { + row.put("options", null); // fallback if malformed + } + } + } + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Parent Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getChildQuestionsList(String pid) { + String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=?"; + List> result = jdbcBusShelterTemplate.queryForList(sql, pid); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Child Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public String inactiveFeedBack(String type, String shelter_id) { + + String sql = "UPDATE `bus_shelter_poster_removal_feedback` SET `isactive`=0 WHERE DATE(`cdate`) = CURDATE() AND `type`= ? AND `shelter_id`=?"; + jdbcBusShelterTemplate.update(sql, type, shelter_id); + + return "sussess"; + } + + private boolean isWithinMeters(String shelterId, String userLat, String userLng, double radius) { + + String sql = "SELECT latitude, longitude FROM bus_shelter_list WHERE id = ? AND isactive = 1 LIMIT 1"; + + List> list = jdbcBusShelterTemplate.queryForList(sql, shelterId); + + if (list.isEmpty()) { + return false; + } + + double assetLat = Double.parseDouble(list.get(0).get("latitude").toString()); + double assetLng = Double.parseDouble(list.get(0).get("longitude").toString()); + + double lat = Double.parseDouble(userLat); + double lng = Double.parseDouble(userLng); + + double distance = calculateDistance(assetLat, assetLng, lat, lng); + + return distance <= radius; + } + + private double calculateDistance(double lat1, double lon1, + double lat2, double lon2) { + + final int EARTH_RADIUS = 6371000; // meters + + double dLat = Math.toRadians(lat2 - lat1); + double dLon = Math.toRadians(lon2 - lon1); + + double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + + Math.cos(Math.toRadians(lat1)) + * Math.cos(Math.toRadians(lat2)) + * Math.sin(dLon / 2) + * Math.sin(dLon / 2); + + double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + + return EARTH_RADIUS * c; + } + + @Transactional + public List> saveFeedback( + String shelter_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, + + MultipartFile file_1, + MultipartFile file_2, + MultipartFile file_3, + MultipartFile file_4, + MultipartFile file_5, + MultipartFile file_6, + MultipartFile file_7, + MultipartFile file_8, + MultipartFile file_9, + MultipartFile file_10, + MultipartFile file_11, + String type) { + List> result = null; + Map response = new HashMap<>(); + + double radius = Double.parseDouble(getConfigValue(2)); // Get Check radius from config + if (!isWithinMeters(shelter_id, latitude, longitude, radius)) { + + response.put("status", "error"); + response.put("message", "You must be within " + radius + " meters of the Bus Shelter."); + + return Collections.singletonList(response); + } + + int lastInsertId = 0; + + String image = ""; + String image_q1 = ""; + String image_q2 = ""; + String image_q3 = ""; + String image_q4 = ""; + String image_q5 = ""; + String image_q6 = ""; + String image_q7 = ""; + String image_q8 = ""; + String image_q9 = ""; + String image_q10 = ""; + String image_q11 = ""; + + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + image = fileUpload("feedback", "0", file); + } + + // Question Images + if (file_1 != null && !file_1.isEmpty()) { + image_q1 = fileUpload("1", "q1", file_1); + } + + if (file_2 != null && !file_2.isEmpty()) { + image_q2 = fileUpload("2", "q2", file_2); + } + + if (file_3 != null && !file_3.isEmpty()) { + image_q3 = fileUpload("3", "q3", file_3); + } + + if (file_4 != null && !file_4.isEmpty()) { + image_q4 = fileUpload("4", "q4", file_4); + } + + if (file_5 != null && !file_5.isEmpty()) { + image_q5 = fileUpload("5", "q5", file_5); + } + + if (file_6 != null && !file_6.isEmpty()) { + image_q6 = fileUpload("6", "q6", file_6); + } + + if (file_7 != null && !file_7.isEmpty()) { + image_q7 = fileUpload("7", "q7", file_7); + } + + if (file_8 != null && !file_8.isEmpty()) { + image_q8 = fileUpload("8", "q8", file_8); + } + + if (file_9 != null && !file_9.isEmpty()) { + image_q9 = fileUpload("9", "q9", file_9); + } + + if (file_10 != null && !file_10.isEmpty()) { + image_q10 = fileUpload("10", "q10", file_10); + } + + if (file_11 != null && !file_11.isEmpty()) { + image_q11 = fileUpload("11", "q11", file_11); + } + + String feedbackimg = image; + + String q1_image = image_q1; + String q2_image = image_q2; + String q3_image = image_q3; + String q4_image = image_q4; + String q5_image = image_q5; + String q6_image = image_q6; + String q7_image = image_q7; + String q8_image = image_q8; + String q9_image = image_q9; + String q10_image = image_q10; + String q11_image = image_q11; + + // String type = // Get before & after + + // Get today's date + LocalDate today = LocalDate.now(); + + // Format it in the desired format (yyyy-MM-dd) + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayDate = today.format(formatter); + + // inactiveFeedBack(type, shelter_id); // Upadte already insert data. + + String sqlQuery = "INSERT INTO `bus_shelter_poster_removal_feedback`(" + + "`shelter_id`, `cby`, " + + "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, " + + "`remarks`,`latitude`, `longitude`,`zone`,`ward`,`type`,`image`," + + "`q1_image`, `q2_image`, `q3_image`, `q4_image`, `q5_image`, `q6_image`, " + + "`q7_image`, `q8_image`, `q9_image`, `q10_image`, `q11_image`" + + ") " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcBusShelterTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, shelter_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); + + ps.setString(21, q1_image); + ps.setString(22, q2_image); + ps.setString(23, q3_image); + ps.setString(24, q4_image); + ps.setString(25, q5_image); + ps.setString(26, q6_image); + ps.setString(27, q7_image); + ps.setString(28, q8_image); + ps.setString(29, q9_image); + ps.setString(30, q10_image); + ps.setString(31, q11_image); + 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:" + shelter_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); + } + + // Reports + + public List> getZoneReport(String loginid) { + + String configSql = "SELECT fromdate, todate FROM bus_shelter_activity_master WHERE id = 3 AND isactive = 1"; + + Map config = jdbcBusShelterTemplate.queryForMap(configSql); + String fromDate = config.get("fromdate").toString(); + String toDate = config.get("todate").toString(); + + String sql = "SELECT" + + " IFNULL(CAST(bsl.zone AS CHAR), 'Grand Total') AS zone," + + " COUNT(DISTINCT bsl.id) AS total_bus_shelter," + + " COUNT(DISTINCT CASE" + + " WHEN fb.before_cnt > 0 AND fb.after_cnt > 0" + + " THEN bsl.id" + + " END) AS completed," + + " COUNT(DISTINCT bsl.id) - COUNT(DISTINCT CASE" + + " WHEN fb.before_cnt > 0 AND fb.after_cnt > 0" + + " THEN bsl.id" + + " END) AS pending " + + "FROM bus_shelter_list bsl " + + "LEFT JOIN (" + + " SELECT" + + " shelter_id," + + " SUM(type='before') AS before_cnt," + + " SUM(type='after') AS after_cnt" + + " FROM bus_shelter_poster_removal_feedback " + + " WHERE isactive = 1 AND DATE(cdate) BETWEEN ? AND ? " + + " GROUP BY shelter_id " + + ") fb ON fb.shelter_id = bsl.id " + + "WHERE bsl.isactive = 1 " + + "GROUP BY bsl.zone WITH ROLLUP"; + + List> result = jdbcBusShelterTemplate.queryForList(sql, fromDate, toDate); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Zone Report."); + response.put("fromDate", fromDate); + response.put("toDate", toDate); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getWardReport(String loginid, String zone) { + + String configSql = "SELECT fromdate, todate FROM bus_shelter_activity_master WHERE id = 3 AND isactive = 1"; + + Map config = jdbcBusShelterTemplate.queryForMap(configSql); + String fromDate = config.get("fromdate").toString(); + String toDate = config.get("todate").toString(); + + String sql = "SELECT" + + " IFNULL(CAST(bsl.ward AS CHAR), 'Grand Total') AS ward," + + " COUNT(DISTINCT bsl.id) AS total_bus_shelter," + + " COUNT(DISTINCT CASE" + + " WHEN fb.before_cnt > 0 AND fb.after_cnt > 0" + + " THEN bsl.id" + + " END) AS completed," + + " COUNT(DISTINCT bsl.id) -" + + " COUNT(DISTINCT CASE" + + " WHEN fb.before_cnt > 0 AND fb.after_cnt > 0" + + " THEN bsl.id" + + " END) AS pending " + + "FROM bus_shelter_list bsl " + + "LEFT JOIN (" + + " SELECT" + + " shelter_id," + + " SUM(type='before') AS before_cnt," + + " SUM(type='after') AS after_cnt" + + " FROM bus_shelter_poster_removal_feedback" + + " WHERE isactive = 1 AND DATE(cdate) BETWEEN ? AND ?" + + " GROUP BY shelter_id " + + ") fb ON fb.shelter_id = bsl.id " + + "WHERE bsl.isactive = 1 " + + "AND bsl.zone = ? " + + "GROUP BY bsl.ward WITH ROLLUP"; + + List> result = jdbcBusShelterTemplate.queryForList(sql, fromDate, toDate, zone); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Ward Report."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getCompletedReport(String loginid, String ward) { + + String configSql = "SELECT fromdate, todate FROM bus_shelter_activity_master WHERE id = 3 AND isactive = 1"; + + Map config = jdbcBusShelterTemplate.queryForMap(configSql); + String fromDate = config.get("fromdate").toString(); + String toDate = config.get("todate").toString(); + + String sql = "SELECT " + + " bsl.*, " + + "" + + " MAX(CASE WHEN bsprf.type='before' THEN bsprf.cdate END) AS before_cdate, " + + " MAX(CASE WHEN bsprf.type='after' THEN bsprf.cdate END) AS after_cdate, " + + "" + + " MAX(CASE WHEN bsprf.type='before' THEN CONCAT('" + fileBaseUrl + + "/gccofficialapp/files', bsprf.q5_image) END) AS before_image, " + + " MAX(CASE WHEN bsprf.type='after' THEN CONCAT('" + fileBaseUrl + + "/gccofficialapp/files', bsprf.q6_image) END) AS after_image " + + "" + + "FROM bus_shelter_list bsl " + + "JOIN bus_shelter_poster_removal_feedback bsprf " + + "ON bsprf.shelter_id=bsl.id " + + "AND bsprf.isactive=1 AND DATE(bsprf.cdate) BETWEEN ? AND ? " + + "WHERE bsl.ward=? " + + "AND bsl.isactive=1 " + + + "GROUP BY bsl.id " + + + "HAVING " + + "SUM(bsprf.type='before')>0 " + + "AND " + + "SUM(bsprf.type='after')>0 " + + "" + + "ORDER BY bsl.road"; + + List> result = jdbcBusShelterTemplate.queryForList(sql, fromDate, toDate, ward); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Completed Report."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getPendingReport(String loginid, String ward) { + + String configSql = "SELECT fromdate, todate FROM bus_shelter_activity_master WHERE id = 3 AND isactive = 1"; + + Map config = jdbcBusShelterTemplate.queryForMap(configSql); + String fromDate = config.get("fromdate").toString(); + String toDate = config.get("todate").toString(); + + String sql = "SELECT bsl.* " + + "FROM bus_shelter_list bsl " + + "LEFT JOIN ( " + + " SELECT " + + " shelter_id, " + + " SUM(type='before') before_cnt, " + + " SUM(type='after') after_cnt " + + " FROM bus_shelter_poster_removal_feedback " + + " WHERE isactive=1 AND DATE(cdate) BETWEEN ? AND ? " + + " GROUP BY shelter_id " + + ") fb" + + " ON fb.shelter_id=bsl.id " + + "WHERE bsl.ward=? " + + "AND bsl.isactive=1 " + + "AND (" + + " fb.before_cnt IS NULL " + + " " + + " OR fb.after_cnt IS NULL " + + ") " + + "ORDER BY bsl.road "; + + List> result = jdbcBusShelterTemplate.queryForList(sql, fromDate, toDate, ward); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Pending Report."); + response.put("data", result); + + return Collections.singletonList(response); + } +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java b/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java index 707657d5..c25849fa 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java @@ -639,6 +639,28 @@ public class DataSourceConfig { dataSource.setPassword(dbpassword); return dataSource; } + + ////////////////////////////// For Rag Picker Survey //////////////////////// + @Bean(name = "mysqlRagPickerSurveyDataSource") + public DataSource mysqlRagPickerSurveyDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://" + host + "/gcc_rag_pick_survey"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + ////////////////////////////// For Night Shelter Inspection //////////////////////// + @Bean(name = "mysqlNightShelterInspectionDataSource") + public DataSource mysqlNightShelterInspectionDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://" + host + "/gcc_night_shelter_inspection"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } ////////// Tenements////////////////////// @Bean(name = "mysqlTenementDataSource") @@ -662,6 +684,17 @@ public class DataSourceConfig { return dataSource; } + //////////Road war web////////////////////// + @Bean(name = "mysqlroadwarwebGccDataSource") + public DataSource mysqlroadwarwebGccDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://" + host + "/gcc_roadwar_web"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + ////////// GCC Mobile Menu ////////////////////// @Bean(name = "mysqlGccMobileMenuDataSource") public DataSource mysqlGccMobileMenuDataSource() { diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/PmcController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/PmcController.java index 4fd36eff..c0399f73 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/PmcController.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/PmcController.java @@ -160,15 +160,25 @@ public class PmcController { } + @GetMapping("/getfoodswingCategory") + public List> getfoodswingCategory( + @RequestParam int shiftid, + @RequestParam int hub_id, + @RequestParam String date) { + + return pmcservice.getfoodswingCategory(shiftid, hub_id, date); + } + @GetMapping("/getfoodswingDataNoCategory") public List> getfoodswingDataNoCategory( @RequestParam int shiftid, @RequestParam int hub_id, @RequestParam String date, @RequestParam(value = "latitude", required = false) String latitude, - @RequestParam(value = "longitude", required = false) String longitude) { + @RequestParam(value = "longitude", required = false) String longitude, + @RequestParam(value = "qcm_id", required = false) Integer qcm_id) { - return pmcservice.getfoodswingDataNoCategory(shiftid, hub_id, date,latitude,longitude); + return pmcservice.getfoodswingDataNoCategory(shiftid, hub_id, date,latitude,longitude,qcm_id); } diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/PmcService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/PmcService.java index 0ae66192..e4943b9f 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/PmcService.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/PmcService.java @@ -2406,7 +2406,111 @@ public class PmcService { return Collections.singletonList(response); } - public List> getfoodswingDataNoCategory(int shiftid, int hub_id, String date,String latitude,String longitude) { + + public List> getfoodswingCategory(int shiftid, int hub_id, String date) { + + String formattedDate = convertDateFormat(date, 0); + Map response = new HashMap<>(); + + try { + + // 2. Check audit exists + StringBuilder auditCheckSql = new StringBuilder( + "SELECT id FROM pmc_audit WHERE shiftid=? AND hub_id=? AND isactive=1 AND isdelete=0 " + ); + + List auditParams = new ArrayList<>(); + auditParams.add(shiftid); + auditParams.add(hub_id); + + if (date != null && !date.trim().isEmpty()) { + auditCheckSql.append(" AND audit_date=? "); + auditParams.add(formattedDate); + } + + List auditIds = jdbcPmcTemplate.query( + auditCheckSql.toString(), + (rs, rowNum) -> rs.getInt("id"), + auditParams.toArray() + ); + + if (auditIds.isEmpty()) { + response.put("message", "No Audit data for " + date +" - shift -"+shiftid); + response.put("status", "Failed"); + return Collections.singletonList(response); + } + + // 3. Fetch data (same query) + StringBuilder reportSql = new StringBuilder(); + + reportSql.append( + "SELECT pa.qcm_id,qcm.code,qcm.audit_category,qcm.penalty,qcm.img_url,qcm.orderby " + + "FROM pmc_audit pa " + + "LEFT JOIN questions_category_master qcm ON qcm.qcm_id=pa.qcm_id AND qcm.isactive=1 AND qcm.isdelete=0 " + + "LEFT JOIN pmc_feedback pf ON pf.pmc_audit_id = pa.id AND pf.isactive=1 AND pf.isdelete=0 AND pf.food_swing_sts is NULL " + + "JOIN pmc_answer_master pam ON pam.aid = pf.answer AND pam.isactive=1 AND pam.isdelete=0 AND pam.opt_mandatory=1 " + + "WHERE pa.shiftid=? AND pa.hub_id=? AND pa.isactive=1 AND pa.isdelete=0 " + ); + + List params = new ArrayList<>(); + params.add(shiftid); + params.add(hub_id); + + if (date != null && !date.trim().isEmpty()) { + reportSql.append(" AND pa.audit_date=? "); + params.add(formattedDate); + } + reportSql.append(" GROUP BY pa.qcm_id "); + reportSql.append(" ORDER BY qcm.orderby "); + + + List> result = jdbcPmcTemplate.queryForList(reportSql.toString(), params.toArray()); + Iterator> iterator = result.iterator(); + ObjectMapper mapper = new ObjectMapper(); + while (iterator.hasNext()) { + Map row = iterator.next(); + Object optionsRaw = row.get("options"); + if (optionsRaw != null && optionsRaw instanceof String) { + try { + List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); + + // Sort options by 'orderby' + optionsParsed.sort(Comparator.comparing(opt -> { + Object order = opt.get("orderby"); + return (order instanceof Number) ? ((Number) order).intValue() : 0; + })); + + row.put("options", optionsParsed); + } catch (Exception e) { + row.put("options", null); // fallback if malformed + } + } + + } + + // 5. Final response + response.put("data", result); + response.put("message", "Food Swing Category Details for " + date); + response.put("status", "Success"); + + } catch (Exception e) { + e.printStackTrace(); + response.put("message", "Error in getting category data"); + response.put("status", "Failed"); + } + + return Collections.singletonList(response); + } + + + + + + + + + + public List> getfoodswingDataNoCategory(int shiftid, int hub_id, String date,String latitude,String longitude,Integer qcm_id) { String formattedDate = convertDateFormat(date, 0); Map response = new HashMap<>(); @@ -2465,6 +2569,12 @@ public class PmcService { auditCheckSql.append(" AND audit_date=? "); auditParams.add(formattedDate); } + + if (qcm_id != null && qcm_id > 0) { + auditCheckSql.append(" AND qcm_id=? "); + auditParams.add(qcm_id); + } + List auditIds = jdbcPmcTemplate.query( auditCheckSql.toString(), @@ -2477,6 +2587,8 @@ public class PmcService { response.put("status", "Failed"); return Collections.singletonList(response); } + + System.err.println("auditIds=="+auditIds); // 3. Fetch data (same query) StringBuilder reportSql = new StringBuilder(); @@ -2523,10 +2635,19 @@ public class PmcService { reportSql.append(" AND pa.audit_date=? "); params.add(formattedDate); } + + if (qcm_id != null && qcm_id > 0) { + reportSql.append(" AND pa.qcm_id=? "); + params.add(qcm_id); + } + + reportSql.append(" GROUP BY pf.id "); reportSql.append(" ORDER BY pq.orderby "); + System.out.println(reportSql.toString()); + List> result = jdbcPmcTemplate.queryForList(reportSql.toString(), params.toArray()); Iterator> iterator = result.iterator(); ObjectMapper mapper = new ObjectMapper(); diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/controller/CattleApiController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/controller/CattleApiController.java index 3b8e6f09..627b15c3 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/controller/CattleApiController.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/controller/CattleApiController.java @@ -140,4 +140,29 @@ public class CattleApiController { } + @GetMapping("/getzonereport") + public List> getzonereport() { + + return cattleService.getzonereport(); + } + + @GetMapping("/getwardreport") + public List> getwardreport(@RequestParam String zone) { + + return cattleService.getwardreport(zone); + } + + @GetMapping("/getwardowners") + public List> getwardowners(@RequestParam String ward) { + + return cattleService.getwardowners(ward); + } + + @GetMapping("/getcattledetails") + public List> getcattledetails(@RequestParam String owner_ref_id,@RequestParam String cattle_maintained) { + + return cattleService.getcattledetails(owner_ref_id,cattle_maintained); + } + + } diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/service/CattleService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/service/CattleService.java index f4a241c1..1fcd1bd7 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/service/CattleService.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/service/CattleService.java @@ -540,6 +540,65 @@ public class CattleService { try { + + // Check duplicate microchip number + if (microchip_no != null && !microchip_no.trim().isEmpty()) { + + String sql = "SELECT COUNT(*) FROM cattle_details " + + "WHERE microchip_no = ? " + + "AND isactive = 1 AND isdelete = 0"; + + Integer count = jdbcTemplate.queryForObject( + sql, + Integer.class, + microchip_no.trim()); + + if (count != null && count > 0) { + response.put("status", "Failed"); + response.put("message", microchip_no+" Microchip Number already exists"); + return Collections.singletonList(response); + } + } + + // Check duplicate license number + if (licenese_no != null && !licenese_no.trim().isEmpty()) { + + String sql = "SELECT COUNT(*) FROM cattle_details " + + "WHERE licenese_no = ? " + + "AND isactive = 1 AND isdelete = 0"; + + Integer count = jdbcTemplate.queryForObject( + sql, + Integer.class, + licenese_no.trim()); + + if (count != null && count > 0) { + response.put("status", "Failed"); + response.put("message", licenese_no+" License Number already exists"); + return Collections.singletonList(response); + } + } + + // Check duplicate insurance number + if (insurance_no != null && !insurance_no.trim().isEmpty()) { + + String sql = "SELECT COUNT(*) FROM cattle_details " + + "WHERE insurance_no = ? " + + "AND isactive = 1 AND isdelete = 0"; + + Integer count = jdbcTemplate.queryForObject( + sql, + Integer.class, + insurance_no.trim()); + + if (count != null && count > 0) { + response.put("status", "Failed"); + response.put("message", insurance_no +" Insurance Number already exists"); + return Collections.singletonList(response); + } + } + + String imagePath = ""; String ipimagePath = ""; if (image == null || image.isEmpty()) { @@ -641,6 +700,248 @@ public class CattleService { } + public List> getzonereport() { + + Map response = new HashMap<>(); + + try { + + + String sql = " SELECT " + + " od.zone, " + + + " COUNT(DISTINCT od.owner_ref_id) AS owner_count, " + + + " ( " + + " SELECT COALESCE(SUM(o2.no_of_cattles), 0) " + + " FROM owner_details o2 " + + " WHERE o2.zone = od.zone " + + " AND o2.isactive = 1 " + + " AND o2.isdelete = 0 " + + " ) AS total_cattlecount, " + + + " COUNT(DISTINCT CASE " + + " WHEN od.is_completed = 0 THEN od.owner_ref_id " + + " END) AS cattle_not_submitted, " + + + " COUNT(DISTINCT CASE " + + " WHEN od.is_completed = 1 THEN od.owner_ref_id " + + " END) AS cattle_submitted, " + + + " COUNT(CASE " + + " WHEN cd.cattle_maintained = 'Home' THEN 1 " + + " END) AS home_count, " + + + " COUNT(CASE " + + " WHEN cd.cattle_maintained = 'GCC' THEN 1 " + + " END) AS gcc_count " + + + " FROM owner_details od " + + " LEFT JOIN cattle_details cd " + + " ON od.owner_ref_id = cd.owner_ref_id " + + " AND cd.isactive = 1 " + + " AND cd.isdelete = 0 " + + + " WHERE od.isactive = 1 " + + " AND od.isdelete = 0 " + + + " GROUP BY od.zone " + + " ORDER BY CAST(od.zone AS UNSIGNED) "; + + List> zone_details=jdbcTemplate.queryForList(sql); + + response.put("data",zone_details); + + response.put("message", "Zonewise Report for Cattle Survey"); + response.put("status", "Success"); + + } catch (Exception e) { + response.put("message", "Error in getting Zonewise Report for Cattle Survey"); + response.put("status", "Failed"); + e.printStackTrace(); + } + + return Collections.singletonList(response); + } + + public List> getwardreport(String zone) { + + Map response = new HashMap<>(); + + try { + + + String sql = " SELECT " + + " od.ward, " + + + " COUNT(DISTINCT od.owner_ref_id) AS owner_count, " + + + " ( " + + " SELECT COALESCE(SUM(o2.no_of_cattles), 0) " + + " FROM owner_details o2 " + + " WHERE o2.zone = od.zone " + + " AND o2.isactive = 1 " + + " AND o2.isdelete = 0 " + + " ) AS total_cattlecount, " + + + " COUNT(DISTINCT CASE " + + " WHEN od.is_completed = 0 THEN od.owner_ref_id " + + " END) AS cattle_not_submitted, " + + + " COUNT(DISTINCT CASE " + + " WHEN od.is_completed = 1 THEN od.owner_ref_id " + + " END) AS cattle_submitted, " + + + " COUNT(CASE " + + " WHEN cd.cattle_maintained = 'Home' THEN 1 " + + " END) AS home_count, " + + + " COUNT(CASE " + + " WHEN cd.cattle_maintained = 'GCC' THEN 1 " + + " END) AS gcc_count " + + + " FROM owner_details od " + + " LEFT JOIN cattle_details cd " + + " ON od.owner_ref_id = cd.owner_ref_id " + + " AND cd.isactive = 1 " + + " AND cd.isdelete = 0 " + + + " WHERE od.isactive = 1 " + + " AND od.isdelete = 0 AND od.zone=? " + + + " GROUP BY od.ward " + + " ORDER BY CAST(od.ward AS UNSIGNED) "; + + List> ward_details=jdbcTemplate.queryForList(sql,zone); + + response.put("data",ward_details); + + response.put("message", "Zone -"+zone+" Wardwise Report for Cattle Survey"); + response.put("status", "Success"); + + } catch (Exception e) { + response.put("message", "Error in getting Zone-"+zone+" Wardwise Report for Cattle Survey"); + response.put("status", "Failed"); + e.printStackTrace(); + } + + return Collections.singletonList(response); + } + + public List> getwardowners(String ward) { + + Map response = new HashMap<>(); + try { + + String sql = + "SELECT " + + " od.owner_ref_id, " + + " od.owner_name, " + + " od.mobile_no, " + + " od.address, " + + " COALESCE(od.no_of_cattles,0) AS total_cattlecount, " + + " COUNT(od.owner_ref_id) AS cattle_submitted, "+ + " (COALESCE(od.no_of_cattles,0) - COUNT(od.owner_ref_id)) AS cattle_not_submitted, "+ + " SUM(CASE WHEN cd.cattle_maintained='Home' THEN 1 ELSE 0 END) AS home_count, " + + " SUM(CASE WHEN cd.cattle_maintained='GCC' THEN 1 ELSE 0 END) AS gcc_count " + + "FROM owner_details od " + + "LEFT JOIN cattle_details cd " + + " ON od.owner_ref_id = cd.owner_ref_id " + + " AND cd.isactive = 1 " + + " AND cd.isdelete = 0 " + + "WHERE od.isactive = 1 " + + " AND od.isdelete = 0 " + + " AND od.ward = ? " + + "GROUP BY od.owner_ref_id, od.owner_name,od.mobile_no,od.address, od.no_of_cattles " + + "ORDER BY od.owner_ref_id"; + + List> owner_details=jdbcTemplate.queryForList(sql,ward); + + response.put("data",owner_details); + + response.put("message", ward+" owners Report for Cattle Survey"); + response.put("status", "Success"); + + } catch (Exception e) { + response.put("message", "Error in getting"+ward+" owners Report for Cattle Survey"); + response.put("status", "Failed"); + e.printStackTrace(); + } + return Collections.singletonList(response); + } + + public List> getcattledetails(String owner_ref_id, String cattle_maintained) { + + Map response = new HashMap<>(); + try { + + String sql = + "SELECT cd.*, " + + + // Master Names + "IFNULL(ctm.cattle_name,'') AS cattle_type_name, " + + "IFNULL(bm.breed_name,'') AS breed_name, " + + "IFNULL(gsm.shed_name,'') AS gcc_shed_name, " + + "IFNULL(vtm.vaccination_name,'') AS vaccination_name, " + + + // Insurance Image + "CASE " + + " WHEN cd.insurance_photo IS NULL OR cd.insurance_photo='' " + + " THEN '' " + + " ELSE CONCAT('" + fileBaseUrl + "/gccofficialapp/files', cd.insurance_photo) " + + "END AS insurance_fullimg, " + + + // Cattle Image + "CASE " + + " WHEN cd.cattle_photo IS NULL OR cd.cattle_photo='' " + + " THEN '' " + + " ELSE CONCAT('" + fileBaseUrl + "/gccofficialapp/files', cd.cattle_photo) " + + "END AS cattle_fullimg " + + + "FROM cattle_details cd " + + + "LEFT JOIN cattle_type_master ctm " + + " ON cd.cattle_type = ctm.id " + + " AND ctm.isactive = 1 " + + " AND ctm.isdelete = 0 " + + + "LEFT JOIN breed_master bm " + + " ON cd.breed_type = bm.id " + + " AND bm.isactive = 1 " + + " AND bm.isdelete = 0 " + + + "LEFT JOIN gcc_shed_master gsm " + + " ON cd.cattle_space_gcc_shed = gsm.id " + + " AND gsm.isactive = 1 " + + " AND gsm.isdelete = 0 " + + + "LEFT JOIN vaccination_type_master vtm " + + " ON cd.vaccination_type = vtm.id " + + " AND vtm.isactive = 1 " + + " AND vtm.isdelete = 0 " + + + "WHERE cd.isactive = 1 " + + " AND cd.isdelete = 0 " + + " AND cd.owner_ref_id = ? " + + " AND UPPER(cd.cattle_maintained) = UPPER(?)"; + + List> cattle_details=jdbcTemplate.queryForList(sql,owner_ref_id,cattle_maintained); + for (Map row : cattle_details) { + row.replaceAll((key, value) -> value == null ? "" : value); + } + response.put("data",cattle_details); + + response.put("message", owner_ref_id+" owner "+cattle_maintained+" -Cattle Report for Cattle Survey"); + response.put("status", "Success"); + + } catch (Exception e) { + response.put("message", "Error in getting"+owner_ref_id+" owner "+cattle_maintained+" -Cattle Report for Cattle Survey"); + response.put("status", "Failed"); + e.printStackTrace(); + } + return Collections.singletonList(response); + } + diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/controller/ChildSurveyApiController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/controller/ChildSurveyApiController.java index 4d42928d..631bad23 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/controller/ChildSurveyApiController.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/controller/ChildSurveyApiController.java @@ -76,6 +76,21 @@ public class ChildSurveyApiController { "message", result)); } + @PostMapping(value = "/save", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity saveSurveyJson(@RequestBody Map jsonParams) { + Map params = new HashMap<>(); + if (jsonParams != null) { + for (Map.Entry entry : jsonParams.entrySet()) { + params.put(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()); + } + } + String result = childSurveyService.saveSurveyFromParams(params); + + return ResponseEntity.ok(Map.of( + "status", true, + "message", result)); + } + @PostMapping(value = "/save_1", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE }) public ResponseEntity saveParticipateSurvey(@RequestParam Map params) { diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/service/ChildSurveyService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/service/ChildSurveyService.java index 9aeddfc7..f6289dc1 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/service/ChildSurveyService.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/service/ChildSurveyService.java @@ -13,6 +13,9 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.type.TypeReference; + @Service public class ChildSurveyService { @@ -99,7 +102,7 @@ public class ChildSurveyService { if (masterTable != null && !masterTable.isEmpty()) { options = getOptionsFromMaster(masterTable, qid); - } + } questionMap.put("options", options); @@ -357,6 +360,78 @@ public class ChildSurveyService { } } + // Detect and save family members details if passed as JSON string + String familyMembersJson = params.get("family_members"); + if (familyMembersJson == null) { + familyMembersJson = params.get("familyMembers"); + } + if (familyMembersJson == null) { + familyMembersJson = params.get("treeData"); + } + + // We will keep a list of keys that were parsed as family members JSON to skip + // them in the main q-param loop + List parsedJsonKeys = new ArrayList<>(); + + // Group and parse family members sent as structured parameters like + // q58[0][name] + Map>> structuredFamilyMap = new HashMap<>(); + java.util.regex.Pattern structPattern = java.util.regex.Pattern + .compile("^q(\\d+)\\[(\\d+)\\]\\[([a-zA-Z0-9_]+)\\]$"); + for (Map.Entry entry : params.entrySet()) { + String key = entry.getKey().trim(); + String val = entry.getValue() == null ? "" : entry.getValue().trim(); + java.util.regex.Matcher m = structPattern.matcher(key); + if (m.matches()) { + String qidStr = m.group(1); + String qPrefix = "q" + qidStr; + int index = Integer.parseInt(m.group(2)); + String prop = m.group(3); + + structuredFamilyMap.computeIfAbsent(qPrefix, k -> new java.util.TreeMap<>()) + .computeIfAbsent(index, k -> new LinkedHashMap<>()) + .put(prop, val); + + // Track this key to skip in the normal parameter loop + parsedJsonKeys.add(key); + } + } + // Save the grouped structured family members + for (Map.Entry>> entry : structuredFamilyMap.entrySet()) { + List> familyList = new ArrayList<>(entry.getValue().values()); + if (!familyList.isEmpty()) { + saveFamilyMembers(familyList, surveyId, cby); + } + } + if (familyMembersJson != null && !familyMembersJson.trim().isEmpty() + && familyMembersJson.trim().startsWith("[")) { + try { + List> familyList = parseFamilyMembersJson(familyMembersJson); + if (familyList != null && !familyList.isEmpty()) { + saveFamilyMembers(familyList, surveyId, cby); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Also check if any qX parameter contains the JSON list of family members + for (Map.Entry entry : params.entrySet()) { + String fieldName = entry.getKey().trim(); + String answer = entry.getValue() == null ? "" : entry.getValue().trim(); + if (fieldName.startsWith("q") && answer.startsWith("[") && answer.endsWith("]")) { + try { + List> familyList = parseFamilyMembersJson(answer); + if (familyList != null && !familyList.isEmpty()) { + saveFamilyMembers(familyList, surveyId, cby); + parsedJsonKeys.add(fieldName); + } + } catch (Exception e) { + // Ignore, not a valid JSON list, process as normal q parameter + } + } + } + String insertSql = "INSERT INTO child_survey_response " + "(survey_id, qid, answer, others_answer, cby, parent_answer_id, cdate, isactive, isdelete) " + "VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; @@ -364,6 +439,9 @@ public class ChildSurveyService { for (Map.Entry entry : params.entrySet()) { String fieldName = entry.getKey().trim(); // q1, q2... + if (parsedJsonKeys.contains(fieldName)) { + continue; + } String answer = entry.getValue() == null ? "" : entry.getValue().trim(); // System.out.println("👉 Processing: " + fieldName); @@ -576,4 +654,192 @@ public class ChildSurveyService { } } + private void saveFamilyMembers(List> familyList, String surveyId, String cby) { + if (familyList == null || familyList.isEmpty()) { + return; + } + + String insertFamilySql = "INSERT INTO child_survey_response_family_members " + + "(qid, answer, others_answer, cby, survey_id, parent_answer_id, cdate, isactive, isdelete) " + + "VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; + + for (Map member : familyList) { + for (Map.Entry field : member.entrySet()) { + String key = field.getKey().trim(); + Object valObj = field.getValue(); + String answer = valObj == null ? "" : valObj.toString().trim(); + + // Skip utility/metadata keys if any + if ("parent_answer_id".equalsIgnoreCase(key) || "parent_aid".equalsIgnoreCase(key)) { + continue; + } + + // Resolve qid + Integer qid = null; + if (key.startsWith("q")) { + try { + qid = Integer.parseInt(key.substring(1)); + } catch (Exception e) { + // ignore + } + } else { + try { + qid = Integer.parseInt(key); + } catch (Exception e) { + // ignore + } + } + + // If not numeric/q-prefixed, resolve statically first + if (qid == null) { + String cleanKey = key.toLowerCase().trim(); + if ("name".equals(cleanKey)) { + qid = 6; + } else if ("gender".equals(cleanKey)) { + qid = 7; + } else if ("age".equals(cleanKey)) { + qid = 10; + } else if ("relationship".equals(cleanKey)) { + qid = 21; + } else if ("education".equals(cleanKey)) { + qid = 26; + } else if ("occupation".equals(cleanKey)) { + qid = 22; + } + } + + // Fallback: If still null, try resolving by field_name or matching q_english + // (case-insensitive) from DB without active/delete constraint + if (qid == null) { + try { + String cleanKey = key.toLowerCase().trim(); + String getQidSql = "SELECT qid FROM child_survey_questions_master " + + "WHERE (LOWER(field_name) = ? OR LOWER(q_english) = ? OR LOWER(q_english) LIKE ?) LIMIT 1"; + List qidList = jdbcChildSurveyTemplate.queryForList(getQidSql, Integer.class, + cleanKey, cleanKey, cleanKey + "%"); + if (!qidList.isEmpty()) { + qid = qidList.get(0); + } + } catch (Exception e) { + // ignore + } + } + + if (qid != null) { + // Extract parent_answer_id (if any is provided in the member object or resolved + // from mapping) + Integer parentAnswerId = null; + Object parentAidVal = member.get("parent_answer_id"); + if (parentAidVal == null) { + parentAidVal = member.get("parent_aid"); + } + if (parentAidVal != null) { + try { + parentAnswerId = Integer.parseInt(parentAidVal.toString()); + } catch (Exception e) { + // ignore + } + } + + // If still null, try resolving statically + if (parentAnswerId == null) { + if (qid == 10) { + parentAnswerId = 1; + } else if (qid == 21) { + parentAnswerId = 8; + } else if (qid == 26) { + parentAnswerId = 9; + } else if (qid == 22) { + parentAnswerId = 5; + } + } + + // Fallback: If still null, try resolving from mapping table (without + // active/delete constraint) + if (parentAnswerId == null) { + try { + String parentAidSql = "SELECT parent_aid FROM child_question_mapping WHERE child_qid = ? LIMIT 1"; + List list = jdbcChildSurveyTemplate.queryForList(parentAidSql, Integer.class, qid); + if (!list.isEmpty()) { + parentAnswerId = list.get(0); + } + } catch (Exception e) { + // ignore + } + } + + // Extract others_answer if any + String othersKey = key + "_other"; + Object othersValObj = member.get(othersKey); + String othersValue = othersValObj == null ? "" : othersValObj.toString().trim(); + + // Insert to child_survey_response_family_members + try { + jdbcChildSurveyTemplate.update(insertFamilySql, qid, answer, othersValue, cby, surveyId, + parentAnswerId); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } + + private List> parseFamilyMembersJson(String jsonStr) { + if (jsonStr == null || jsonStr.trim().isEmpty()) { + return new ArrayList<>(); + } + String str = jsonStr.trim(); + // First try parsing using standard ObjectMapper + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(str, new TypeReference>>() { + }); + } catch (Exception e) { + // Ignore standard JSON parsing exception, try lenient fallback + } + + // Lenient parsing fallback + List> list = new ArrayList<>(); + try { + if (str.startsWith("[")) { + str = str.substring(1); + } + if (str.endsWith("]")) { + str = str.substring(0, str.length() - 1); + } + str = str.trim(); + if (str.isEmpty()) { + return list; + } + + // Match all occurrences of { ... } + java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\{([^}]+)\\}"); + java.util.regex.Matcher matcher = pattern.matcher(str); + while (matcher.find()) { + String objContent = matcher.group(1); + Map map = new LinkedHashMap<>(); + String[] pairs = objContent.split(","); + for (String pair : pairs) { + int colonIdx = pair.indexOf(':'); + if (colonIdx != -1) { + String key = pair.substring(0, colonIdx).trim(); + String value = pair.substring(colonIdx + 1).trim(); + if ((value.startsWith("\"") && value.endsWith("\"")) + || (value.startsWith("'") && value.endsWith("'"))) { + value = value.substring(1, value.length() - 1); + } + map.put(key, value); + } + } + if (!map.isEmpty()) { + list.add(map); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + } diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccNightShelterInspection/Controller/NightShelterInspectionApiController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccNightShelterInspection/Controller/NightShelterInspectionApiController.java new file mode 100644 index 00000000..c5fd55f2 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccNightShelterInspection/Controller/NightShelterInspectionApiController.java @@ -0,0 +1,193 @@ +package in.gov.chennaicorporation.mobileservice.gccNightShelterInspection.Controller; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +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 org.springframework.web.multipart.MultipartHttpServletRequest; + +import jakarta.servlet.http.HttpServletRequest; + +import in.gov.chennaicorporation.mobileservice.gccNightShelterInspection.Service.NightShelterInspectionService; + +@RequestMapping("/gccofficialapp/api/shelterinspection") +@RestController("gccofficialappShelterInspection") +public class NightShelterInspectionApiController { + + @Autowired + private NightShelterInspectionService nightShelterInspectionService; + +// @GetMapping("/questions") +// public ResponseEntity getQuestions() { +// +// List> data = nightShelterInspectionService.getSurveyQuestions(); +// +// Map response = new HashMap<>(); +// response.put("status", true); +// response.put("data", data); +// +// return ResponseEntity.ok(response); +// } + + @GetMapping("/questions") + public ResponseEntity getQuestions(@RequestParam Integer cid) { + + List> data = nightShelterInspectionService.getSurveyQuestions(cid); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/login") + public ResponseEntity getLogin(@RequestParam String mobileNo, @RequestParam String password) { + + Map response = nightShelterInspectionService.getLoginDetails(mobileNo, password); + + return ResponseEntity.ok(response); + } + + @GetMapping("/states") + public ResponseEntity getStates() { + + List> data = nightShelterInspectionService.getStates(); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/districts") + public ResponseEntity getDistricts(@RequestParam(required = false) String sid) { + + List> data = nightShelterInspectionService.getDistricts(sid); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/getShelterList") + public ResponseEntity getShelterList() { + + List> data = nightShelterInspectionService.getShelterList(); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/questions_category") + public ResponseEntity getQuestionsCategory() { + List> data = nightShelterInspectionService.getQuestionsCategory(); + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + return ResponseEntity.ok(response); + } + + // @PostMapping("/save") + // public ResponseEntity saveResponses( + // @RequestParam Map params, + // HttpServletRequest request) { + // MultipartHttpServletRequest multipartRequest = null; + // if (request instanceof MultipartHttpServletRequest) { + // multipartRequest = (MultipartHttpServletRequest) request; + // } + + // Map result = + // nightShelterInspectionService.saveSurveyResponses(params, multipartRequest); + // System.out.println("params ----------------------------------------->" + + // params); + // System.out.println("request-------------" + request); + // System.out.println("multipartRequest --------------------------------->" + + // multipartRequest); + // System.out.println("result ----------------------------------------->" + + // result); + // return ResponseEntity.ok(result); + // } + + @PostMapping("/save") + public ResponseEntity saveResponses( + @RequestParam Map params, + HttpServletRequest request, + MultipartHttpServletRequest multipartRequest) { + + Map files = multipartRequest.getFileMap(); + + // System.out.println("===== FORM PARAMETERS ====="); + + request.getParameterMap().forEach((key, values) -> { + + for (String value : values) { + // System.out.println(key + " = " + value); + } + }); + + // System.out.println("\n===== FILES ===="); + + // multipartRequest.getFileMap().forEach((key, file) -> { + + // System.out.println("Field Name : " + key); + + // System.out.println("File Name : " + file.getOriginalFilename()); + + // System.out.println("Size : " + file.getSize()); + + // System.out.println("ContentType: " + file.getContentType()); + + // System.out.println("---------------------------"); + + // }); + + // System.out.println("\n===== FILES FINAL ===="); + for (Map.Entry entry : files.entrySet()) { + + String fieldName = entry.getKey(); + MultipartFile file = entry.getValue(); + // System.out.println("params :" + params); + // System.out.println("request :" + request); + // System.out.println("multipartRequest :" + multipartRequest); + // System.out.println("Field Name : " + fieldName); + // System.out.println("File Name : " + file.getOriginalFilename()); + // System.out.println("Size : " + file.getSize()); + } + + // Existing service call + Map result = nightShelterInspectionService.saveSurveyResponses(params, multipartRequest); + + return ResponseEntity.ok(result); + } + + @GetMapping("/category_status") + public ResponseEntity getCategoryStatus(@RequestParam("survey_id") String surveyId) { + Map response = nightShelterInspectionService.getCategoryStatus(surveyId); + return ResponseEntity.ok(response); + } + + @GetMapping("/profile_list") + public ResponseEntity getProfileList(@RequestParam(required = false) String cby) { + List> data = nightShelterInspectionService.getProfileCreatedList(cby); + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + return ResponseEntity.ok(response); + } + +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccNightShelterInspection/Service/NightShelterInspectionService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccNightShelterInspection/Service/NightShelterInspectionService.java new file mode 100644 index 00000000..ac56a61e --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccNightShelterInspection/Service/NightShelterInspectionService.java @@ -0,0 +1,1023 @@ +package in.gov.chennaicorporation.mobileservice.gccNightShelterInspection.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.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class NightShelterInspectionService { + + @Autowired + JdbcTemplate jdbcNightShelterInspectionTemplate; + + @Autowired + private Environment environment; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + 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(); + } + + @Autowired + public void setDataSource(@Qualifier("mysqlNightShelterInspectionDataSource") DataSource nightShelterInspectionDataSource) { + this.jdbcNightShelterInspectionTemplate = new JdbcTemplate(nightShelterInspectionDataSource); + } + +// public List> getSurveyQuestions() { +// +// String childSql = "SELECT DISTINCT child_qid FROM night_shelter_inspection_question_mapping " + +// "WHERE isactive=1 AND isdelete=0"; +// +// List childQids = jdbcNightShelterInspectionTemplate.queryForList(childSql, Integer.class); +// +// String questionSql = "SELECT * FROM night_shelter_inspection_questions_master " + +// // "WHERE cid=? AND isactive=1 AND isdelete=0 ORDER BY orderby"; +// "WHERE isactive=1 AND isdelete=0 ORDER BY orderby"; +// +// List> questions = jdbcNightShelterInspectionTemplate.queryForList(questionSql); +// +// List> finalList = new ArrayList<>(); +// +// for (Map q : questions) { +// Integer qid = (Integer) q.get("qid"); +// +// if (childQids.contains(qid)) { +// continue; +// } +// +// Map fullQuestion = buildQuestionWithOptions(q); +// finalList.add(fullQuestion); +// } +// +// return finalList; +// } + + public List> getSurveyQuestions(Integer cid) { + + String childSql = "SELECT DISTINCT child_qid FROM night_shelter_inspection_question_mapping " + + "WHERE isactive=1 AND isdelete=0"; + + List childQids = jdbcNightShelterInspectionTemplate.queryForList(childSql, Integer.class); + + String questionSql = "SELECT * FROM night_shelter_inspection_questions_master " + + "WHERE cid=? AND isactive=1 AND isdelete=0 ORDER BY orderby"; + + List> questions = jdbcNightShelterInspectionTemplate.queryForList(questionSql, cid); + + List> finalList = new ArrayList<>(); + + for (Map q : questions) { + Integer qid = (Integer) q.get("qid"); + + if (childQids.contains(qid)) { + continue; + } + + Map fullQuestion = buildQuestionWithOptions(q); + finalList.add(fullQuestion); + } + + return finalList; + } + + private Map buildQuestionWithOptions(Map q) { + + Integer qid = (Integer) q.get("qid"); + String masterTable = (String) safe(q.get("master_table_name")); + + // Maintain order + Map questionMap = new LinkedHashMap<>(); + + questionMap.put("qid", q.get("qid")); + questionMap.put("q_english", q.get("q_english")); + questionMap.put("q_tamil", safe(q.get("q_tamil"))); + questionMap.put("field_name", q.get("field_name")); + questionMap.put("cdate", q.get("cdate")); + questionMap.put("question_type", q.get("question_type")); + questionMap.put("isactive", q.get("isactive")); + questionMap.put("isdelete", q.get("isdelete")); + questionMap.put("orderby", q.get("orderby")); + questionMap.put("is_mandatory", q.get("is_mandatory")); + questionMap.put("is_dropdown", q.get("is_dropdown")); + questionMap.put("flag", q.get("flag")); + questionMap.put("master_table_name", masterTable); + + List> options = new ArrayList<>(); + + if (masterTable != null && !masterTable.isEmpty()) { + if (masterTable.equalsIgnoreCase("state_master") || masterTable.equalsIgnoreCase("district_master")) { + options = new ArrayList<>(); + } else { + options = getOptionsFromMaster(masterTable, qid); + } + } else { + String optSql = "SELECT id AS option_id, answer AS english_name, " + + "orderby, is_mandatory " + + "FROM night_shelter_inspection_answer_master " + + "WHERE qid=? AND isactive=1 AND isdelete=0 ORDER BY orderby"; + + List> dbOptions = jdbcNightShelterInspectionTemplate.queryForList(optSql, qid); + + for (Map opt : dbOptions) { + + Map optionMap = new LinkedHashMap<>(); + + String englishName = (String) opt.get("english_name"); + optionMap.put("option_id", opt.get("option_id")); + optionMap.put("english_name", englishName); + optionMap.put("tamil_name", ""); + optionMap.put("orderby", opt.get("orderby")); + optionMap.put("is_mandatory", opt.get("is_mandatory")); + + boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others"); + optionMap.put("is_others", isOthers); + optionMap.put("text", isOthers); + + Integer aid = (Integer) opt.get("option_id"); + + List> childQuestions = getChildQuestionsRecursive(aid); + + optionMap.put("child_questions", childQuestions); + + options.add(optionMap); + } + } + + questionMap.put("options", options); + + return questionMap; + } + + private List> getChildQuestionsRecursive(Integer parentAid) { + + String mappingSql = "SELECT child_qid FROM night_shelter_inspection_question_mapping " + + "WHERE parent_aid=? AND isactive=1 AND isdelete=0"; + + List childQids = jdbcNightShelterInspectionTemplate.queryForList(mappingSql, Integer.class, parentAid); + + List> childQuestions = new ArrayList<>(); + + for (Integer cqid : childQids) { + + String qSql = "SELECT * FROM night_shelter_inspection_questions_master " + + "WHERE qid=? AND isactive=1 AND isdelete=0"; + + List> childQList = jdbcNightShelterInspectionTemplate.queryForList(qSql, cqid); + + if (!childQList.isEmpty()) { + Map childQ = childQList.get(0); + Map fullChild = buildQuestionWithOptions(childQ); + childQuestions.add(fullChild); + } + } + + return childQuestions; + } + + private List> getOptionsFromMaster(String tableName, Integer parentQid) { + + String sql = "SELECT id AS option_id, " + + "english_name, " + + "IFNULL(tamil_name, '') AS tamil_name, " + + "orderby, " + + "is_mandatory " + + "FROM " + tableName + " " + + "WHERE isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + + List> dbOptions = jdbcNightShelterInspectionTemplate.queryForList(sql); + + List> options = new ArrayList<>(); + + for (Map opt : dbOptions) { + + Map optionMap = new LinkedHashMap<>(); + + String englishName = (String) opt.get("english_name"); + + optionMap.put("option_id", opt.get("option_id")); + optionMap.put("english_name", englishName); + optionMap.put("tamil_name", opt.get("tamil_name")); + optionMap.put("orderby", opt.get("orderby")); + optionMap.put("is_mandatory", opt.get("is_mandatory")); + + List> childQuestions = new ArrayList<>(); + + boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others"); + optionMap.put("is_others", isOthers); + optionMap.put("text", isOthers); + + if (isOthers) { + Map child = new LinkedHashMap<>(); + + child.put("qid", parentQid); // same parent qid + child.put("q_english", "Please specify"); + child.put("q_tamil", ""); + child.put("question_type", "text"); + child.put("field_name", "q" + parentQid + "_other"); + child.put("is_mandatory", false); + child.put("is_dropdown", false); + + childQuestions.add(child); + } + + optionMap.put("child_questions", childQuestions); + + options.add(optionMap); + } + + return options; + } + + public List> getStates() { + String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, orderby " + + "FROM state_master " + + "WHERE isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + return jdbcNightShelterInspectionTemplate.queryForList(sql); + } + + public List> getQuestionsCategory() { + String sql = "SELECT * FROM question_category_master where isactive=1 and isdelete=0 order by orderby"; + return jdbcNightShelterInspectionTemplate.queryForList(sql); + + } + + public List> getDistricts(String sid) { + if (sid != null && !sid.trim().isEmpty()) { + String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, sid, orderby " + + "FROM district_master " + + "WHERE sid=? AND isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + return jdbcNightShelterInspectionTemplate.queryForList(sql, sid); + } else { + String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, sid, orderby " + + "FROM district_master " + + "WHERE isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + return jdbcNightShelterInspectionTemplate.queryForList(sql); + } + } + + public List> getShelterList() { + + String sql = "SELECT " + + "id AS option_id, " + + "english_name, " + + "IFNULL(tamil_name, '') AS tamil_name, " + + "zone, " + + "ward, " + + "shelter_category, " + + "ngo_name, " + + "is_mandatory, " + + "is_child, " + + "orderby " + + "FROM night_shelter_list_master " + + "WHERE isactive = 1 AND isdelete = 0 " + + "ORDER BY orderby ASC"; + + return jdbcNightShelterInspectionTemplate.queryForList(sql); + } + + private Object safe(Object value) { + return value == null ? "" : value; + } + + public Map getLoginDetails(String mobileNo, String password) { + + try { + + String sql = "SELECT uid as loginId,user_name, password, mobile_no, is_active, is_delete " + + "FROM login_details " + + "WHERE mobile_no = ? AND password = ? AND is_active = 1 AND is_delete = 0 Limit 1"; + + List> data = jdbcNightShelterInspectionTemplate.queryForList(sql, mobileNo, password); + + Map response = new HashMap<>(); + + if (!data.isEmpty()) { + // Login success + response.put("is_login", true); + response.put("message", "Login Success"); + response.put("data", data); + } else { + // Login failed + response.put("is_login", false); + response.put("message", "Invalid mobile number or password"); + } + + return response; + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Error fetching login details: " + e.getMessage()); + } + } + + @Transactional + public Map saveSurveyResponses(Map params, + MultipartHttpServletRequest fileRequest) { + Map result = new HashMap<>(); + try { + // URL-decode all parameter values to handle spaces, etc. (e.g. Adi%20Dravidar) + for (Map.Entry entry : params.entrySet()) { + if (entry.getValue() != null) { + String val = entry.getValue(); + try { + if (val.contains("%")) { + entry.setValue(java.net.URLDecoder.decode(val, "UTF-8")); + } + } catch (Exception ex) { + // ignore + } + } + } + + String surveyId = params.get("survey_id"); + String cid = params.get("cid"); + String cby = params.get("cby"); + String zone = params.get("zone"); + String ward = params.get("ward"); + String latitude = params.get("latitude"); + String longitude = params.get("longitude"); + String shelterId = params.get("shelter_id"); + //String address = params.get("address"); ) + // System.out.println(" surveyId: " + surveyId); + // System.out.println(" cid: " + cid); + // System.out.println(" cby: " + cby); + // System.out.println(" zone: " + zone); + // System.out.println(" ward: " + ward); + // System.out.println(" latitude: " + latitude); + // System.out.println(" longitude: " + longitude); + // System.out.println(" address: " + address); + + // If it is NOT the Profile category, verify that the profile is already created + if (cid == null || !cid.equals("1")) { + if (surveyId == null || surveyId.trim().isEmpty() || surveyId.equalsIgnoreCase("null")) { + result.put("status", false); + result.put("message", + "Survey ID is required for this category. Please save the Profile category first."); + return result; + } + + // Check if the Profile category responses or surveyor location record exists + // for this surveyId + String checkProfileSql = "SELECT COUNT(*) FROM night_shelter_inspection_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0"; + Integer profileCount = jdbcNightShelterInspectionTemplate.queryForObject(checkProfileSql, Integer.class, + surveyId); + + String checkLocSql = "SELECT COUNT(*) FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0"; + Integer locCount = jdbcNightShelterInspectionTemplate.queryForObject(checkLocSql, Integer.class, surveyId); + + if ((profileCount == null || profileCount == 0) && (locCount == null || locCount == 0)) { + result.put("status", false); + result.put("message", + "Profile not created for this survey ID. Please save the Profile category first."); + return result; + } + } + + // 1. Generate surveyId if not provided + if (surveyId == null || surveyId.trim().isEmpty() || surveyId.equalsIgnoreCase("null")) { + String timeStr = java.time.LocalDateTime.now() + .format(java.time.format.DateTimeFormatter.ofPattern("ddMMyyHHmmss")); + surveyId = "GCC_NSI_" + timeStr; + } + + String resolvedLat = latitude; + if (resolvedLat == null || resolvedLat.trim().isEmpty() || resolvedLat.equalsIgnoreCase("null")) { + resolvedLat = params.get("lat"); + } + if (resolvedLat == null || resolvedLat.trim().isEmpty() || resolvedLat.equalsIgnoreCase("null")) { + if (fileRequest != null) { + resolvedLat = fileRequest.getParameter("lat"); + } + } + String resolvedLng = longitude; + if (resolvedLng == null || resolvedLng.trim().isEmpty() || resolvedLng.equalsIgnoreCase("null")) { + resolvedLng = params.get("long"); + } + if (resolvedLng == null || resolvedLng.trim().isEmpty() || resolvedLng.equalsIgnoreCase("null")) { + if (fileRequest != null) { + resolvedLng = fileRequest.getParameter("long"); + } + } + + // If Profile category (cid = 1) is created, save surveyor location details + // first (like in child_survey) + if (cid != null && cid.equals("1") && (zone != null || resolvedLat != null || resolvedLng != null)) { + try { + String logindetailsSql = "INSERT INTO surveyor_location_details " + + "(loginId, zone, ward, latitude, longitude, shelter_id, is_active, is_delete, cdate) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())"; + + org.springframework.jdbc.support.KeyHolder keyHolder = new org.springframework.jdbc.support.GeneratedKeyHolder(); + + final String finalLat = resolvedLat; + final String finalLng = resolvedLng; + final String finalZone = zone; + final String finalWard = ward; + final String finalshelter = shelterId; + final String finalCby = cby; + + jdbcNightShelterInspectionTemplate.update( + connection -> { + java.sql.PreparedStatement ps = connection.prepareStatement(logindetailsSql, + java.sql.Statement.RETURN_GENERATED_KEYS); + ps.setString(1, finalCby); + ps.setString(2, finalZone); + ps.setString(3, finalWard); + ps.setString(4, finalLat); + ps.setString(5, finalLng); + ps.setString(6, shelterId); + return ps; + }, + keyHolder); + + Number key = keyHolder.getKey(); + if (key != null) { + Integer locationId = key.intValue(); + + // Append the locationId to surveyId + surveyId = surveyId + locationId; + + // Update the location record with the final surveyId + String updateSql = "UPDATE surveyor_location_details SET survey_id = ? WHERE id = ?"; + jdbcNightShelterInspectionTemplate.update(updateSql, surveyId, locationId); + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Error saving surveyor location details: " + ex.getMessage()); + } + } + + // Deactivate existing active responses for this surveyId and cid + String deactivateSql = "UPDATE night_shelter_inspection_response SET isactive = 0, isdelete = 1 WHERE survey_id = ? AND cid = ? AND isactive = 1"; + jdbcNightShelterInspectionTemplate.update(deactivateSql, surveyId, cid); + + String deactivateParticipateSql = "UPDATE night_shelter_inspection_participate_response SET isactive = 0, isdelete = 1 WHERE survey_id = ? AND cid = ? AND isactive = 1"; + jdbcNightShelterInspectionTemplate.update(deactivateParticipateSql, surveyId, cid); + + String insertparticipateSql = "INSERT INTO night_shelter_inspection_participate_response (qid, answer, others_answer, survey_id, cid, cby, parent_answer_id, cdate, isactive, isdelete) " + + + "VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; + + String insertSql = "INSERT INTO night_shelter_inspection_response (qid, answer, others_answer, survey_id, cid, cby, parent_answer_id, cdate, isactive, isdelete) " + + + "VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; + + String qSql = "SELECT qid, question_type, field_name, q_english FROM night_shelter_inspection_questions_master " + + "WHERE cid = ? AND (isactive = 1 AND isdelete = 0 OR (cid = '1' AND field_name IN ('q2', 'q78', 'q11', 'q8', 'q9', 'q10', 'q77')))"; + List> questions = jdbcNightShelterInspectionTemplate.queryForList(qSql, cid); + + boolean hasNotWillingResponse = false; + // First pass: check if qid = 1 is answered with "38" or "Not willing to respond + // (mark them)" + for (Map q : questions) { + + Integer qid = (Integer) q.get("qid"); + String fieldName = (String) q.get("field_name"); + if (qid != null && qid == 1 && fieldName != null && params.containsKey(fieldName)) { + String answer = params.get(fieldName); + if (answer != null) { + String trimmed = answer.trim(); + if ("38".equals(trimmed) || "Not willing to respond (mark them)".equalsIgnoreCase(trimmed)) { + hasNotWillingResponse = true; + } + } + } + } + + for (Map q : questions) { + Integer qid = (Integer) q.get("qid"); + String fieldName = (String) q.get("field_name"); + String questionType = (String) q.get("question_type"); + String qEnglish = (String) q.get("q_english"); + + // System.out.println("qid: " + qid); + // System.out.println("fieldName: " + fieldName); + // System.out.println("questionType: " + questionType); + // System.out.println("qEnglish: " + qEnglish); + + if (fieldName == null || fieldName.trim().isEmpty()) { + continue; + } + + // Check if the param exists or has a file upload + boolean hasParam = params.containsKey(fieldName); + boolean hasFile = false; + if (fileRequest != null) { + + // System.out.println( + // "fieldName: " + fieldName + " - " + + // fileRequest.getFileMap().containsKey(fieldName)); + // System.out.println("q_" + qid + " - " + + // fileRequest.getFileMap().containsKey("q_" + qid)); + + if (fileRequest.getFileMap().containsKey(fieldName) || + fileRequest.getFileMap().containsKey("q_" + qid) || + fileRequest.getFileMap().containsKey("file_" + qid) || + fileRequest.getFileMap().containsKey("file" + qid) || + fileRequest.getFileMap().containsKey("f_" + qid) || + fileRequest.getFileMap().containsKey("f" + qid) || + fileRequest.getFileMap().containsKey("q" + qid)) { + hasFile = true; + } else if (questionType != null + && (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) { + boolean matchesOrGeneric = false; + if (fileRequest.getFileMap().size() == 1) { + String singleKey = fileRequest.getFileMap().keySet().iterator().next(); + if (singleKey != null && (singleKey.equalsIgnoreCase(fieldName) || + singleKey.contains("q_" + qid) || + singleKey.contains("file_" + qid) || + singleKey.contains("file" + qid) || + singleKey.contains("f_" + qid) || + singleKey.contains("f" + qid) || + singleKey.contains("q" + qid) || + singleKey.equalsIgnoreCase("files") || + singleKey.equalsIgnoreCase("file") || + singleKey.equalsIgnoreCase("image"))) { + matchesOrGeneric = true; + } + } + if (fileRequest.getFileMap().containsKey("files") || + fileRequest.getFileMap().containsKey("file") || + fileRequest.getFileMap().containsKey("image") || + matchesOrGeneric) { + hasFile = true; + } + } + } + + if (hasParam || hasFile) { + String answer = params.getOrDefault(fieldName, ""); + if (answer == null) { + answer = ""; + } + + // Extract others_answer + String othersKey = fieldName + "_other"; + String othersAnswer = params.getOrDefault(othersKey, ""); + + // Extract parent_answer_id + String parentKey = fieldName + "_parent_answer_id"; + Integer parentAnswerId = 0; + if (params.get(parentKey) != null && !params.get(parentKey).isEmpty()) { + try { + parentAnswerId = Integer.parseInt(params.get(parentKey)); + } catch (Exception ex) { + // ignore + } + } + + // Handle image/file uploads + if (questionType != null + && (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) { + MultipartFile file = null; + if (fileRequest != null) { + file = fileRequest.getFile(fieldName); + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("q_" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("file_" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("file" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("f_" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("f" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("q" + qid); + } + // Fallback generic scan + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("files"); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("file"); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("image"); + } + // Fallback scan + if (file == null || file.isEmpty()) { + for (String name : fileRequest.getFileMap().keySet()) { + if (name.equalsIgnoreCase(fieldName) + || name.contains("q_" + qid) + || name.contains("file_" + qid) + || name.contains("file" + qid) + || name.contains("f_" + qid) + || name.contains("f" + qid) + || name.contains("q" + qid)) { + file = fileRequest.getFile(name); + break; + } + } + } + // Ultimate fallback: if only 1 file exists in the request, use it + if ((file == null || file.isEmpty()) && fileRequest.getFileMap().size() == 1) { + String singleKey = fileRequest.getFileMap().keySet().iterator().next(); + if (singleKey != null && (singleKey.equalsIgnoreCase(fieldName) || + singleKey.contains("q_" + qid) || + singleKey.contains("file_" + qid) || + singleKey.contains("file" + qid) || + singleKey.contains("f_" + qid) || + singleKey.contains("f" + qid) || + singleKey.contains("q" + qid) || + singleKey.equalsIgnoreCase("files") || + singleKey.equalsIgnoreCase("file") || + singleKey.equalsIgnoreCase("image"))) { + file = fileRequest.getFileMap().values().iterator().next(); + } + } + } + + if (file != null && !file.isEmpty()) { + String uploadedPath = uploadSurveyFile(file, qEnglish, surveyId); + if (uploadedPath != null && !uploadedPath.startsWith("Failed")) { + answer = uploadedPath; + // System.out.println("--- Image Uploaded --- QID: " + qid + " | FieldName: " + + // fieldName + " | File: " + file.getOriginalFilename() + " | Path: " + + // uploadedPath); + } + } + } + + boolean isNotWilling = false; + if (qid != null && qid == 1) { + String trimmed = answer.trim(); + if ("38".equals(trimmed) || "Not willing to respond (mark them)".equalsIgnoreCase(trimmed)) { + isNotWilling = true; + } + } + + if (isNotWilling) { + jdbcNightShelterInspectionTemplate.update(insertparticipateSql, qid, answer, othersAnswer, surveyId, + cid, cby, + parentAnswerId); + // System.out.println("--- DB SAVE (Participate) --- QID: " + qid + " | + // FieldName: " + fieldName + " | Answer: " + answer + " | OthersAnswer: " + + // othersAnswer); + } else { + if (!hasNotWillingResponse) { + jdbcNightShelterInspectionTemplate.update(insertSql, qid, answer, othersAnswer, surveyId, cid, cby, + parentAnswerId); + // System.out.println("--- DB SAVE (Response) --- QID: " + qid + " | FieldName: + // " + fieldName + " | Answer: " + answer + " | OthersAnswer: " + othersAnswer); + } + } + } + } + + // Insert placeholder responses for all other active categories if they do not + // exist + if (!hasNotWillingResponse) { + try { + String catSql = "SELECT id FROM question_category_master WHERE isactive = 1 AND isdelete = 0"; + List> allCats = jdbcNightShelterInspectionTemplate.queryForList(catSql); + for (Map catMap : allCats) { + Object otherCidObj = catMap.get("id"); + if (otherCidObj != null) { + String otherCid = otherCidObj.toString(); + if (!otherCid.equals(cid)) { + String checkExistSql = "SELECT COUNT(*) FROM night_shelter_inspection_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0"; + Integer existCount = jdbcNightShelterInspectionTemplate.queryForObject(checkExistSql, + Integer.class, + surveyId, otherCid); + if (existCount == null || existCount == 0) { + String otherQSql = "SELECT qid FROM night_shelter_inspection_questions_master WHERE cid = ? AND isactive = 1 AND isdelete = 0"; + List otherQids = jdbcNightShelterInspectionTemplate.queryForList(otherQSql, + Integer.class, otherCid); + for (Integer otherQid : otherQids) { + jdbcNightShelterInspectionTemplate.update(insertSql, otherQid, null, null, surveyId, + otherCid, cby, 0); + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Error inserting placeholder survey responses: " + ex.getMessage()); + } + } + + result.put("status", true); + result.put("message", "Survey responses saved successfully"); + result.put("survey_id", surveyId); + + } catch (Exception e) { + e.printStackTrace(); + result.put("status", false); + result.put("message", "Error saving survey responses: " + e.getMessage()); + } + return result; + } + + private String uploadSurveyFile(MultipartFile file, String qEnglish, String surveyId) { + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("nightshelterinspection_document_foldername"); + // if (serviceFolderName == null || serviceFolderName.trim().isEmpty()) { + // serviceFolderName = "homelesssurvey_image/"; + // } + + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + var date = DateTimeUtil.getCurrentDay(); + + String finalUploadDir = uploadDirectory + serviceFolderName + year + "/" + month + "/" + date + "/" + surveyId; + + try { + Path directoryPath = Paths.get(finalUploadDir); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + String cleanName = qEnglish.replaceAll("[^a-zA-Z0-9]", "_").replaceAll("_+", "_"); + String datetimetxt = DateTimeUtil.getCurrentDateTime() + "_" + generateRandomString(); + String fileName = cleanName + "_" + datetimetxt + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); + + String filePath = finalUploadDir + "/" + fileName; + String relativePath = "/" + serviceFolderName + year + "/" + month + "/" + date + "/" + surveyId + "/" + + fileName; + + Path path = Paths.get(filePath); + byte[] bytes = file.getBytes(); + + try { + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + if (image != null) { + byte[] compressedBytes = compressImage(image, 0.5f); + Files.write(path, compressedBytes); + } else { + Files.write(path, bytes); + } + } catch (Exception e) { + Files.write(path, bytes); + } + + return relativePath; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file: " + e.getMessage(); + } + } + + 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(); + byteArrayOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public Map getCategoryStatus(String surveyId) { + Map result = new HashMap<>(); + try { + // Check if the Profile category responses or surveyor location record exists + // for this surveyId + String checkProfileSql = "SELECT COUNT(*) FROM night_shelter_inspection_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0"; + Integer profileCount = jdbcNightShelterInspectionTemplate.queryForObject(checkProfileSql, Integer.class, surveyId); + + String checkLocSql = "SELECT COUNT(*) FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0"; + Integer locCount = jdbcNightShelterInspectionTemplate.queryForObject(checkLocSql, Integer.class, surveyId); + + if ((profileCount == null || profileCount == 0) && (locCount == null || locCount == 0)) { + result.put("status", false); + result.put("message", + "Profile not created for this survey ID. Please save the Profile category first."); + return result; + } + + String catSql = "SELECT id, english_name, icon, orderby FROM question_category_master WHERE isactive=1 AND isdelete=0 ORDER BY orderby"; + List> categories = jdbcNightShelterInspectionTemplate.queryForList(catSql); + + List> dataList = new ArrayList<>(); + + for (Map cat : categories) { + Object cidObj = cat.get("id"); + String cidStr = cidObj != null ? cidObj.toString() : ""; + + String responseSql = "SELECT COUNT(*) FROM (" + + " SELECT id FROM night_shelter_inspection_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0 AND answer IS NOT NULL AND answer != '' " + + + " UNION ALL " + + " SELECT id FROM night_shelter_inspection_participate_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0 AND answer IS NOT NULL AND answer != '' " + + + ") t"; + Integer count = jdbcNightShelterInspectionTemplate.queryForObject(responseSql, Integer.class, surveyId, cidStr, + surveyId, cidStr); + + Map statusMap = new HashMap<>(); + statusMap.put("cid", cidObj); + statusMap.put("english_name", cat.get("english_name")); + statusMap.put("orderby", cat.get("orderby")); + statusMap.put("icon", cat.get("icon")); + statusMap.put("status", (count != null && count > 0) ? "Completed" : "Pending"); + + dataList.add(statusMap); + } + + result.put("status", true); + result.put("data", dataList); + return result; + } catch (Exception e) { + e.printStackTrace(); + result.put("status", false); + result.put("message", "Error fetching category status: " + e.getMessage()); + return result; + } + } + + public List> getProfileCreatedList(String cby) { + List> resultList = new ArrayList<>(); + try { + String sql; + List args = new ArrayList<>(); + if (cby != null && !cby.trim().isEmpty() && !cby.equalsIgnoreCase("null")) { + sql = "SELECT DISTINCT survey_id FROM night_shelter_inspection_response WHERE cid = '1' AND cby = ? AND isactive = 1 AND isdelete = 0"; + args.add(cby); + } else { + sql = "SELECT DISTINCT survey_id FROM night_shelter_inspection_response WHERE cid = '1' AND isactive = 1 AND isdelete = 0"; + } + + List surveyIds = jdbcNightShelterInspectionTemplate.queryForList(sql, args.toArray(), String.class); + + for (String surveyId : surveyIds) { + Map profileMap = new LinkedHashMap<>(); + profileMap.put("survey_id", surveyId); + + // Fetch Location Details + String locSql = "SELECT zone, ward, latitude, longitude, address, loginId as cby, cdate FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0 LIMIT 1"; + List> locData = jdbcNightShelterInspectionTemplate.queryForList(locSql, surveyId); + + if (!locData.isEmpty()) { + Map loc = locData.get(0); + profileMap.put("cby", loc.get("cby")); + profileMap.put("cdate", loc.get("cdate")); + profileMap.put("zone", loc.get("zone")); + profileMap.put("ward", loc.get("ward")); + profileMap.put("latitude", loc.get("latitude")); + profileMap.put("longitude", loc.get("longitude")); + profileMap.put("address", loc.get("address")); + } else { + profileMap.put("zone", ""); + profileMap.put("ward", ""); + profileMap.put("latitude", ""); + profileMap.put("longitude", ""); + profileMap.put("address", ""); + + String fallbackSql = "SELECT cby, cdate FROM night_shelter_inspection_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0 LIMIT 1"; + List> fallbackData = jdbcNightShelterInspectionTemplate.queryForList(fallbackSql, + surveyId); + if (!fallbackData.isEmpty()) { + profileMap.put("cby", fallbackData.get(0).get("cby")); + profileMap.put("cdate", fallbackData.get(0).get("cdate")); + } else { + profileMap.put("cby", ""); + profileMap.put("cdate", ""); + } + } + + // Fetch Answers + String ansSql = "SELECT q.qid, q.field_name, q.question_type, q.q_english, q.master_table_name, r.answer, r.others_answer " + + + "FROM night_shelter_inspection_response r " + + "JOIN night_shelter_inspection_questions_master q ON r.qid = q.qid " + + "WHERE r.survey_id = ? AND r.cid = '1' AND r.isactive = 1 AND r.isdelete = 0 " + + "AND ((q.isactive = 1 AND q.isdelete = 0) OR (q.cid = '1' AND q.field_name IN ('q2', 'q78', 'q11', 'q8', 'q9', 'q10', 'q77')))"; + + List> ansData = jdbcNightShelterInspectionTemplate.queryForList(ansSql, surveyId); + List> answersList = new ArrayList<>(); + + String fileBaseUrlVal = environment.getProperty("fileBaseUrl"); + if (fileBaseUrlVal == null) { + fileBaseUrlVal = ""; + } + + List allowedFields = java.util.Arrays.asList("q2", "q78", "q11", "q8", "q9", "q10", "q77"); + + for (Map ans : ansData) { + String fieldName = (String) ans.get("field_name"); + if (fieldName != null && allowedFields.contains(fieldName)) { + Integer qid = (Integer) ans.get("qid"); + String qEnglish = (String) ans.get("q_english"); + String masterTable = (String) ans.get("master_table_name"); + String questionType = (String) ans.get("question_type"); + String answerVal = (String) ans.get("answer"); + + String resolvedValue = answerVal != null ? answerVal : ""; + + if (answerVal != null && !answerVal.trim().isEmpty()) { + // Try to resolve the option ID to its english name + try { + int optionId = Integer.parseInt(answerVal.trim()); + if (masterTable != null && !masterTable.trim().isEmpty()) { + String query = "SELECT english_name FROM " + masterTable + " WHERE id = ? LIMIT 1"; + List names = jdbcNightShelterInspectionTemplate.queryForList(query, String.class, + optionId); + if (!names.isEmpty()) { + resolvedValue = names.get(0); + } + } else { + String query = "SELECT answer FROM night_shelter_inspection_answer_master WHERE qid = ? AND id = ? LIMIT 1"; + List names = jdbcNightShelterInspectionTemplate.queryForList(query, String.class, + qid, optionId); + if (!names.isEmpty()) { + resolvedValue = names.get(0); + } + } + } catch (NumberFormatException e) { + // Keep original value if not a valid number ID + } + } + + if (resolvedValue != null && !resolvedValue.isEmpty() && questionType != null && + (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) { + resolvedValue = fileBaseUrlVal + "/gccofficialapp/files" + resolvedValue; + } + + Map ansMap = new LinkedHashMap<>(); + ansMap.put("question", qEnglish != null ? qEnglish : ""); + ansMap.put("field_name", fieldName); + ansMap.put("field_value", resolvedValue != null ? resolvedValue : ""); + answersList.add(ansMap); + + String othersVal = (String) ans.get("others_answer"); + if (othersVal != null && !othersVal.isEmpty()) { + Map othersMap = new LinkedHashMap<>(); + othersMap.put("question", "Please specify"); + othersMap.put("field_name", fieldName + "_other"); + othersMap.put("field_value", othersVal); + answersList.add(othersMap); + } + } + } + profileMap.put("answers", answersList); + resultList.add(profileMap); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return resultList; + } +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccRagPickerSurvey/Controller/RagPickerSurveyApiController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccRagPickerSurvey/Controller/RagPickerSurveyApiController.java new file mode 100644 index 00000000..e0561fa9 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccRagPickerSurvey/Controller/RagPickerSurveyApiController.java @@ -0,0 +1,245 @@ +package in.gov.chennaicorporation.mobileservice.gccRagPickerSurvey.Controller; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +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 org.springframework.web.multipart.MultipartHttpServletRequest; + +import jakarta.servlet.http.HttpServletRequest; + +import in.gov.chennaicorporation.mobileservice.gccRagPickerSurvey.Service.RagPickerSurveyService; + +@RequestMapping("/gccofficialapp/api/ragpickersurvey") +@RestController("gccofficialappragpickersurvey") +public class RagPickerSurveyApiController { + + @Autowired + private RagPickerSurveyService ragPickerSurveyService; + + @GetMapping("/questions") + public ResponseEntity getQuestions(@RequestParam Integer cid) { + + List> data = ragPickerSurveyService.getSurveyQuestions(cid); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/login") + public ResponseEntity getLogin(@RequestParam String mobileNo, @RequestParam String password) { + + Map response = ragPickerSurveyService.getLoginDetails(mobileNo, password); + + return ResponseEntity.ok(response); + } + + @GetMapping("/states") + public ResponseEntity getStates() { + + List> data = ragPickerSurveyService.getStates(); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/districts") + public ResponseEntity getDistricts(@RequestParam(required = false) String sid) { + + List> data = ragPickerSurveyService.getDistricts(sid); + + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + + return ResponseEntity.ok(response); + } + + @GetMapping("/questions_category") + public ResponseEntity getQuestionsCategory() { + List> data = ragPickerSurveyService.getQuestionsCategory(); + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + return ResponseEntity.ok(response); + } + + // @PostMapping("/save") + // public ResponseEntity saveResponses( + // @RequestParam Map params, + // HttpServletRequest request) { + // MultipartHttpServletRequest multipartRequest = null; + // if (request instanceof MultipartHttpServletRequest) { + // multipartRequest = (MultipartHttpServletRequest) request; + // } + + // Map result = + // ragPickerSurveyService.saveSurveyResponses(params, multipartRequest); + // System.out.println("params ----------------------------------------->" + + // params); + // System.out.println("request-------------" + request); + // System.out.println("multipartRequest --------------------------------->" + + // multipartRequest); + // System.out.println("result ----------------------------------------->" + + // result); + // return ResponseEntity.ok(result); + // } + + @PostMapping("/save") + public ResponseEntity saveResponses( + @RequestParam Map params, + HttpServletRequest request, + MultipartHttpServletRequest multipartRequest) { + + Map files = multipartRequest.getFileMap(); + + // System.out.println("===== FORM PARAMETERS ====="); + + request.getParameterMap().forEach((key, values) -> { + + for (String value : values) { + // System.out.println(key + " = " + value); + } + }); + + // System.out.println("\n===== FILES ===="); + + // multipartRequest.getFileMap().forEach((key, file) -> { + + // System.out.println("Field Name : " + key); + + // System.out.println("File Name : " + file.getOriginalFilename()); + + // System.out.println("Size : " + file.getSize()); + + // System.out.println("ContentType: " + file.getContentType()); + + // System.out.println("---------------------------"); + + // }); + + // System.out.println("\n===== FILES FINAL ===="); + for (Map.Entry entry : files.entrySet()) { + + String fieldName = entry.getKey(); + MultipartFile file = entry.getValue(); + // System.out.println("params :" + params); + // System.out.println("request :" + request); + // System.out.println("multipartRequest :" + multipartRequest); + // System.out.println("Field Name : " + fieldName); + // System.out.println("File Name : " + file.getOriginalFilename()); + // System.out.println("Size : " + file.getSize()); + } + + // Existing service call + Map result = ragPickerSurveyService.saveSurveyResponses(params, multipartRequest); + + return ResponseEntity.ok(result); + } + + @GetMapping("/category_status") + public ResponseEntity getCategoryStatus(@RequestParam("survey_id") String surveyId) { + Map response = ragPickerSurveyService.getCategoryStatus(surveyId); + return ResponseEntity.ok(response); + } + + @GetMapping("/profile_list") + public ResponseEntity getProfileList(@RequestParam(required = false) String cby) { + List> data = ragPickerSurveyService.getProfileCreatedList(cby); + Map response = new HashMap<>(); + response.put("status", true); + response.put("data", data); + return ResponseEntity.ok(response); + } + +// @PostMapping(value = "/save", consumes = MediaType.APPLICATION_JSON_VALUE) +// public ResponseEntity saveSurveyJson(@RequestBody Map jsonParams) { +// Map params = new HashMap<>(); +// if (jsonParams != null) { +// for (Map.Entry entry : jsonParams.entrySet()) { +// params.put(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()); +// } +// } +// String result = ragPickerSurveyService.saveSurveyFromParams(params); +// +// return ResponseEntity.ok(Map.of( +// "status", true, +// "message", result)); +// } + + @PostMapping(value= "/save", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity saveResponsesJson( + @RequestBody Map jsonparams, + HttpServletRequest request, + MultipartHttpServletRequest multipartRequest) { + + + Map params = new HashMap<>(); + if (jsonparams != null) { + for (Map.Entry entry : jsonparams.entrySet()) { + params.put(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()); + } + } + Map files = multipartRequest.getFileMap(); + + // System.out.println("===== FORM PARAMETERS ====="); + + request.getParameterMap().forEach((key, values) -> { + + for (String value : values) { + // System.out.println(key + " = " + value); + } + }); + + // System.out.println("\n===== FILES ===="); + + // multipartRequest.getFileMap().forEach((key, file) -> { + + // System.out.println("Field Name : " + key); + + // System.out.println("File Name : " + file.getOriginalFilename()); + + // System.out.println("Size : " + file.getSize()); + + // System.out.println("ContentType: " + file.getContentType()); + + // System.out.println("---------------------------"); + + // }); + + // System.out.println("\n===== FILES FINAL ===="); + for (Map.Entry entry : files.entrySet()) { + + String fieldName = entry.getKey(); + MultipartFile file = entry.getValue(); + // System.out.println("params :" + params); + // System.out.println("request :" + request); + // System.out.println("multipartRequest :" + multipartRequest); + // System.out.println("Field Name : " + fieldName); + // System.out.println("File Name : " + file.getOriginalFilename()); + // System.out.println("Size : " + file.getSize()); + } + + // Existing service call + Map result = ragPickerSurveyService.saveSurveyResponses(params, multipartRequest); + + return ResponseEntity.ok(result); + } + +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccRagPickerSurvey/Service/RagPickerSurveyService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccRagPickerSurvey/Service/RagPickerSurveyService.java new file mode 100644 index 00000000..05871a5d --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccRagPickerSurvey/Service/RagPickerSurveyService.java @@ -0,0 +1,1207 @@ +package in.gov.chennaicorporation.mobileservice.gccRagPickerSurvey.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.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class RagPickerSurveyService { + + @Autowired + JdbcTemplate jdbcRagPickerSurveyTemplate; + + @Autowired + private Environment environment; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + 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(); + } + + @Autowired + public void setDataSource(@Qualifier("mysqlRagPickerSurveyDataSource") DataSource RagPickerSurveyDataSource) { + this.jdbcRagPickerSurveyTemplate = new JdbcTemplate(RagPickerSurveyDataSource); + } + + public List> getSurveyQuestions(Integer cid) { + + String childSql = "SELECT DISTINCT child_qid FROM rag_picker_question_mapping " + + "WHERE isactive=1 AND isdelete=0"; + + List childQids = jdbcRagPickerSurveyTemplate.queryForList(childSql, Integer.class); + + String questionSql = "SELECT * FROM rag_picker_survey_questions_master " + + "WHERE cid=? AND isactive=1 AND isdelete=0 ORDER BY orderby"; + + List> questions = jdbcRagPickerSurveyTemplate.queryForList(questionSql, cid); + + List> finalList = new ArrayList<>(); + + for (Map q : questions) { + Integer qid = (Integer) q.get("qid"); + + if (childQids.contains(qid)) { + continue; + } + + Map fullQuestion = buildQuestionWithOptions(q); + finalList.add(fullQuestion); + } + + return finalList; + } + + private Map buildQuestionWithOptions(Map q) { + + Integer qid = (Integer) q.get("qid"); + String masterTable = (String) safe(q.get("master_table_name")); + + // Maintain order + Map questionMap = new LinkedHashMap<>(); + + questionMap.put("qid", q.get("qid")); + questionMap.put("q_english", q.get("q_english")); + questionMap.put("q_tamil", safe(q.get("q_tamil"))); + questionMap.put("field_name", q.get("field_name")); + questionMap.put("cdate", q.get("cdate")); + questionMap.put("question_type", q.get("question_type")); + questionMap.put("isactive", q.get("isactive")); + questionMap.put("isdelete", q.get("isdelete")); + questionMap.put("orderby", q.get("orderby")); + questionMap.put("is_mandatory", q.get("is_mandatory")); + questionMap.put("is_dropdown", q.get("is_dropdown")); + questionMap.put("flag", q.get("flag")); + questionMap.put("master_table_name", masterTable); + + List> options = new ArrayList<>(); + + if (masterTable != null && !masterTable.isEmpty()) { + if (masterTable.equalsIgnoreCase("state_master") || masterTable.equalsIgnoreCase("district_master")) { + options = new ArrayList<>(); + } else { + options = getOptionsFromMaster(masterTable, qid); + } + } else { + String optSql = "SELECT id AS option_id, answer AS english_name, " + + "orderby, is_mandatory " + + "FROM rag_picker_survey_answer_master " + + "WHERE qid=? AND isactive=1 AND isdelete=0 ORDER BY orderby"; + + List> dbOptions = jdbcRagPickerSurveyTemplate.queryForList(optSql, qid); + + for (Map opt : dbOptions) { + + Map optionMap = new LinkedHashMap<>(); + + String englishName = (String) opt.get("english_name"); + optionMap.put("option_id", opt.get("option_id")); + optionMap.put("english_name", englishName); + optionMap.put("tamil_name", ""); + optionMap.put("orderby", opt.get("orderby")); + optionMap.put("is_mandatory", opt.get("is_mandatory")); + + boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others"); + optionMap.put("is_others", isOthers); + optionMap.put("text", isOthers); + + Integer aid = (Integer) opt.get("option_id"); + + List> childQuestions = getChildQuestionsRecursive(aid); + + optionMap.put("child_questions", childQuestions); + + options.add(optionMap); + } + } + + questionMap.put("options", options); + + return questionMap; + } + + private List> getChildQuestionsRecursive(Integer parentAid) { + + String mappingSql = "SELECT child_qid FROM rag_picker_question_mapping " + + "WHERE parent_aid=? AND isactive=1 AND isdelete=0"; + + List childQids = jdbcRagPickerSurveyTemplate.queryForList(mappingSql, Integer.class, parentAid); + + List> childQuestions = new ArrayList<>(); + + for (Integer cqid : childQids) { + + String qSql = "SELECT * FROM rag_picker_survey_questions_master " + + "WHERE qid=? AND isactive=1 AND isdelete=0"; + + List> childQList = jdbcRagPickerSurveyTemplate.queryForList(qSql, cqid); + + if (!childQList.isEmpty()) { + Map childQ = childQList.get(0); + Map fullChild = buildQuestionWithOptions(childQ); + childQuestions.add(fullChild); + } + } + + return childQuestions; + } + + private List> getOptionsFromMaster(String tableName, Integer parentQid) { + + String sql = "SELECT id AS option_id, " + + "english_name, " + + "IFNULL(tamil_name, '') AS tamil_name, " + + "orderby, " + + "is_mandatory " + + "FROM " + tableName + " " + + "WHERE isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + + List> dbOptions = jdbcRagPickerSurveyTemplate.queryForList(sql); + + List> options = new ArrayList<>(); + + for (Map opt : dbOptions) { + + Map optionMap = new LinkedHashMap<>(); + + String englishName = (String) opt.get("english_name"); + + optionMap.put("option_id", opt.get("option_id")); + optionMap.put("english_name", englishName); + optionMap.put("tamil_name", opt.get("tamil_name")); + optionMap.put("orderby", opt.get("orderby")); + optionMap.put("is_mandatory", opt.get("is_mandatory")); + + List> childQuestions = new ArrayList<>(); + + boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others"); + optionMap.put("is_others", isOthers); + optionMap.put("text", isOthers); + + if (isOthers) { + Map child = new LinkedHashMap<>(); + + child.put("qid", parentQid); // same parent qid + child.put("q_english", "Please specify"); + child.put("q_tamil", ""); + child.put("question_type", "text"); + child.put("field_name", "q" + parentQid + "_other"); + child.put("is_mandatory", false); + child.put("is_dropdown", false); + + childQuestions.add(child); + } + + optionMap.put("child_questions", childQuestions); + + options.add(optionMap); + } + + return options; + } + + public List> getStates() { + String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, orderby " + + "FROM state_master " + + "WHERE isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + return jdbcRagPickerSurveyTemplate.queryForList(sql); + } + + public List> getQuestionsCategory() { + String sql = "SELECT * FROM question_category_master where isactive=1 and isdelete=0 order by orderby"; + return jdbcRagPickerSurveyTemplate.queryForList(sql); + + } + + public List> getDistricts(String sid) { + if (sid != null && !sid.trim().isEmpty()) { + String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, sid, orderby " + + "FROM district_master " + + "WHERE sid=? AND isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + return jdbcRagPickerSurveyTemplate.queryForList(sql, sid); + } else { + String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, sid, orderby " + + "FROM district_master " + + "WHERE isactive=1 AND isdelete=0 " + + "ORDER BY orderby"; + return jdbcRagPickerSurveyTemplate.queryForList(sql); + } + } + + private Object safe(Object value) { + return value == null ? "" : value; + } + + public Map getLoginDetails(String mobileNo, String password) { + + try { + + String sql = "SELECT uid as loginId,user_name, password, mobile_no, is_active, is_delete " + + "FROM login_details " + + "WHERE mobile_no = ? AND password = ? AND is_active = 1 AND is_delete = 0 Limit 1"; + + List> data = jdbcRagPickerSurveyTemplate.queryForList(sql, mobileNo, password); + + Map response = new HashMap<>(); + + if (!data.isEmpty()) { + // Login success + response.put("is_login", true); + response.put("message", "Login Success"); + response.put("data", data); + } else { + // Login failed + response.put("is_login", false); + response.put("message", "Invalid mobile number or password"); + } + + return response; + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Error fetching login details: " + e.getMessage()); + } + } + + @Transactional + public Map saveSurveyResponses(Map params, + MultipartHttpServletRequest fileRequest) { + Map result = new HashMap<>(); + try { + // URL-decode all parameter values to handle spaces, etc. (e.g. Adi%20Dravidar) + for (Map.Entry entry : params.entrySet()) { + if (entry.getValue() != null) { + String val = entry.getValue(); + try { + if (val.contains("%")) { + entry.setValue(java.net.URLDecoder.decode(val, "UTF-8")); + } + } catch (Exception ex) { + // ignore + } + } + } + + String surveyId = params.get("survey_id"); + String cid = params.get("cid"); + String cby = params.get("cby"); + String zone = params.get("zone"); + String ward = params.get("ward"); + String latitude = params.get("latitude"); + String longitude = params.get("longitude"); + String address = params.get("address"); + + // System.out.println(" surveyId: " + surveyId); + // System.out.println(" cid: " + cid); + // System.out.println(" cby: " + cby); + // System.out.println(" zone: " + zone); + // System.out.println(" ward: " + ward); + // System.out.println(" latitude: " + latitude); + // System.out.println(" longitude: " + longitude); + // System.out.println(" address: " + address); + + // If it is NOT the Profile category, verify that the profile is already created + if (cid == null || !cid.equals("1")) { + if (surveyId == null || surveyId.trim().isEmpty() || surveyId.equalsIgnoreCase("null")) { + result.put("status", false); + result.put("message", + "Survey ID is required for this category. Please save the Profile category first."); + return result; + } + + // Check if the Profile category responses or surveyor location record exists + // for this surveyId + String checkProfileSql = "SELECT COUNT(*) FROM rag_picker_survey_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0"; + Integer profileCount = jdbcRagPickerSurveyTemplate.queryForObject(checkProfileSql, Integer.class, + surveyId); + + String checkLocSql = "SELECT COUNT(*) FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0"; + Integer locCount = jdbcRagPickerSurveyTemplate.queryForObject(checkLocSql, Integer.class, surveyId); + + if ((profileCount == null || profileCount == 0) && (locCount == null || locCount == 0)) { + result.put("status", false); + result.put("message", + "Profile not created for this survey ID. Please save the Profile category first."); + return result; + } + } + + // 1. Generate surveyId if not provided + if (surveyId == null || surveyId.trim().isEmpty() || surveyId.equalsIgnoreCase("null")) { + String timeStr = java.time.LocalDateTime.now() + .format(java.time.format.DateTimeFormatter.ofPattern("ddMMyyHHmmss")); + surveyId = "GCC_RPS_" + timeStr; + } + + String resolvedLat = latitude; + if (resolvedLat == null || resolvedLat.trim().isEmpty() || resolvedLat.equalsIgnoreCase("null")) { + resolvedLat = params.get("lat"); + } + if (resolvedLat == null || resolvedLat.trim().isEmpty() || resolvedLat.equalsIgnoreCase("null")) { + if (fileRequest != null) { + resolvedLat = fileRequest.getParameter("lat"); + } + } + String resolvedLng = longitude; + if (resolvedLng == null || resolvedLng.trim().isEmpty() || resolvedLng.equalsIgnoreCase("null")) { + resolvedLng = params.get("long"); + } + if (resolvedLng == null || resolvedLng.trim().isEmpty() || resolvedLng.equalsIgnoreCase("null")) { + if (fileRequest != null) { + resolvedLng = fileRequest.getParameter("long"); + } + } + + // If Profile category (cid = 1) is created, save surveyor location details + // first (like in child_survey) + if (cid != null && cid.equals("1") && (zone != null || resolvedLat != null || resolvedLng != null)) { + try { + String logindetailsSql = "INSERT INTO surveyor_location_details " + + "(loginId, zone, ward, latitude, longitude, address, is_active, is_delete, cdate) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())"; + + org.springframework.jdbc.support.KeyHolder keyHolder = new org.springframework.jdbc.support.GeneratedKeyHolder(); + + final String finalLat = resolvedLat; + final String finalLng = resolvedLng; + final String finalZone = zone; + final String finalWard = ward; + final String finalAddress = address; + final String finalCby = cby; + + jdbcRagPickerSurveyTemplate.update( + connection -> { + java.sql.PreparedStatement ps = connection.prepareStatement(logindetailsSql, + java.sql.Statement.RETURN_GENERATED_KEYS); + ps.setString(1, finalCby); + ps.setString(2, finalZone); + ps.setString(3, finalWard); + ps.setString(4, finalLat); + ps.setString(5, finalLng); + ps.setString(6, finalAddress); + return ps; + }, + keyHolder); + + Number key = keyHolder.getKey(); + if (key != null) { + Integer locationId = key.intValue(); + + // Append the locationId to surveyId + surveyId = surveyId + locationId; + + // Update the location record with the final surveyId + String updateSql = "UPDATE surveyor_location_details SET survey_id = ? WHERE id = ?"; + jdbcRagPickerSurveyTemplate.update(updateSql, surveyId, locationId); + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Error saving surveyor location details: " + ex.getMessage()); + } + } + + //to save family members details + // Detect and save family members details if passed as JSON string + String familyMembersJson = params.get("family_members"); + if (familyMembersJson == null) { + familyMembersJson = params.get("familyMembers"); + } + if (familyMembersJson == null) { + familyMembersJson = params.get("treeData"); + } + + // We will keep a list of keys that were parsed as family members JSON to skip + // them in the main q-param loop + List parsedJsonKeys = new ArrayList<>(); + if (familyMembersJson != null && !familyMembersJson.trim().isEmpty() + && familyMembersJson.trim().startsWith("[")) { + try { + List> familyList = parseFamilyMembersJson(familyMembersJson); + if (familyList != null && !familyList.isEmpty()) { + saveFamilyMembers(familyList, surveyId, cby); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Also check if any qX parameter contains the JSON list of family members + for (Map.Entry entry : params.entrySet()) { + String fieldName = entry.getKey().trim(); + String answer = entry.getValue() == null ? "" : entry.getValue().trim(); + if (fieldName.startsWith("q") && answer.startsWith("[") && answer.endsWith("]")) { + try { + List> familyList = parseFamilyMembersJson(answer); + if (familyList != null && !familyList.isEmpty()) { + saveFamilyMembers(familyList, surveyId, cby); + parsedJsonKeys.add(fieldName); + } + } catch (Exception e) { + // Ignore, not a valid JSON list, process as normal q parameter + } + } + } + + + // Deactivate existing active responses for this surveyId and cid + String deactivateSql = "UPDATE rag_picker_survey_response SET isactive = 0, isdelete = 1 WHERE survey_id = ? AND cid = ? AND isactive = 1"; + jdbcRagPickerSurveyTemplate.update(deactivateSql, surveyId, cid); + + String deactivateParticipateSql = "UPDATE rag_picker_survey_participate_response SET isactive = 0, isdelete = 1 WHERE survey_id = ? AND cid = ? AND isactive = 1"; + jdbcRagPickerSurveyTemplate.update(deactivateParticipateSql, surveyId, cid); + + String insertparticipateSql = "INSERT INTO rag_picker_survey_participate_response (qid, answer, others_answer, survey_id, cid, cby, parent_answer_id, cdate, isactive, isdelete) " + + + "VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; + + String insertSql = "INSERT INTO rag_picker_survey_response (qid, answer, others_answer, survey_id, cid, cby, parent_answer_id, cdate, isactive, isdelete) " + + + "VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; + + String qSql = "SELECT qid, question_type, field_name, q_english FROM rag_picker_survey_questions_master " + + "WHERE cid = ? AND (isactive = 1 AND isdelete = 0 OR (cid = '1' AND field_name IN ('q2', 'q78', 'q11', 'q8', 'q9', 'q10', 'q77')))"; + List> questions = jdbcRagPickerSurveyTemplate.queryForList(qSql, cid); + + boolean hasNotWillingResponse = false; + // First pass: check if qid = 1 is answered with "38" or "Not willing to respond + // (mark them)" + for (Map q : questions) { + + Integer qid = (Integer) q.get("qid"); + String fieldName = (String) q.get("field_name"); + if (parsedJsonKeys.contains(fieldName)) { + continue; // Already saved in family table + } + if (qid != null && qid == 1 && fieldName != null && params.containsKey(fieldName)) { + String answer = params.get(fieldName); + if (answer != null) { + String trimmed = answer.trim(); + if ("38".equals(trimmed) || "Not willing to respond (mark them)".equalsIgnoreCase(trimmed)) { + hasNotWillingResponse = true; + } + } + } + } + + for (Map q : questions) { + Integer qid = (Integer) q.get("qid"); + String fieldName = (String) q.get("field_name"); + String questionType = (String) q.get("question_type"); + String qEnglish = (String) q.get("q_english"); + + if (parsedJsonKeys.contains(fieldName)) { + continue; // Already saved in family table + } + + // System.out.println("qid: " + qid); + // System.out.println("fieldName: " + fieldName); + // System.out.println("questionType: " + questionType); + // System.out.println("qEnglish: " + qEnglish); + + if (fieldName == null || fieldName.trim().isEmpty()) { + continue; + } + + // Check if the param exists or has a file upload + boolean hasParam = params.containsKey(fieldName); + boolean hasFile = false; + if (fileRequest != null) { + + // System.out.println( + // "fieldName: " + fieldName + " - " + + // fileRequest.getFileMap().containsKey(fieldName)); + // System.out.println("q_" + qid + " - " + + // fileRequest.getFileMap().containsKey("q_" + qid)); + + if (fileRequest.getFileMap().containsKey(fieldName) || + fileRequest.getFileMap().containsKey("q_" + qid) || + fileRequest.getFileMap().containsKey("file_" + qid) || + fileRequest.getFileMap().containsKey("file" + qid) || + fileRequest.getFileMap().containsKey("f_" + qid) || + fileRequest.getFileMap().containsKey("f" + qid) || + fileRequest.getFileMap().containsKey("q" + qid)) { + hasFile = true; + } else if (questionType != null + && (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) { + boolean matchesOrGeneric = false; + if (fileRequest.getFileMap().size() == 1) { + String singleKey = fileRequest.getFileMap().keySet().iterator().next(); + if (singleKey != null && (singleKey.equalsIgnoreCase(fieldName) || + singleKey.contains("q_" + qid) || + singleKey.contains("file_" + qid) || + singleKey.contains("file" + qid) || + singleKey.contains("f_" + qid) || + singleKey.contains("f" + qid) || + singleKey.contains("q" + qid) || + singleKey.equalsIgnoreCase("files") || + singleKey.equalsIgnoreCase("file") || + singleKey.equalsIgnoreCase("image"))) { + matchesOrGeneric = true; + } + } + if (fileRequest.getFileMap().containsKey("files") || + fileRequest.getFileMap().containsKey("file") || + fileRequest.getFileMap().containsKey("image") || + matchesOrGeneric) { + hasFile = true; + } + } + } + + if (hasParam || hasFile) { + String answer = params.getOrDefault(fieldName, ""); + if (answer == null) { + answer = ""; + } + + // Extract others_answer + String othersKey = fieldName + "_other"; + String othersAnswer = params.getOrDefault(othersKey, ""); + + // Extract parent_answer_id + String parentKey = fieldName + "_parent_answer_id"; + Integer parentAnswerId = 0; + if (params.get(parentKey) != null && !params.get(parentKey).isEmpty()) { + try { + parentAnswerId = Integer.parseInt(params.get(parentKey)); + } catch (Exception ex) { + // ignore + } + } + + // Handle image/file uploads + if (questionType != null + && (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) { + MultipartFile file = null; + if (fileRequest != null) { + file = fileRequest.getFile(fieldName); + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("q_" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("file_" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("file" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("f_" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("f" + qid); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("q" + qid); + } + // Fallback generic scan + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("files"); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("file"); + } + if (file == null || file.isEmpty()) { + file = fileRequest.getFile("image"); + } + // Fallback scan + if (file == null || file.isEmpty()) { + for (String name : fileRequest.getFileMap().keySet()) { + if (name.equalsIgnoreCase(fieldName) + || name.contains("q_" + qid) + || name.contains("file_" + qid) + || name.contains("file" + qid) + || name.contains("f_" + qid) + || name.contains("f" + qid) + || name.contains("q" + qid)) { + file = fileRequest.getFile(name); + break; + } + } + } + // Ultimate fallback: if only 1 file exists in the request, use it + if ((file == null || file.isEmpty()) && fileRequest.getFileMap().size() == 1) { + String singleKey = fileRequest.getFileMap().keySet().iterator().next(); + if (singleKey != null && (singleKey.equalsIgnoreCase(fieldName) || + singleKey.contains("q_" + qid) || + singleKey.contains("file_" + qid) || + singleKey.contains("file" + qid) || + singleKey.contains("f_" + qid) || + singleKey.contains("f" + qid) || + singleKey.contains("q" + qid) || + singleKey.equalsIgnoreCase("files") || + singleKey.equalsIgnoreCase("file") || + singleKey.equalsIgnoreCase("image"))) { + file = fileRequest.getFileMap().values().iterator().next(); + } + } + } + + if (file != null && !file.isEmpty()) { + String uploadedPath = uploadSurveyFile(file, qEnglish, surveyId); + if (uploadedPath != null && !uploadedPath.startsWith("Failed")) { + answer = uploadedPath; + // System.out.println("--- Image Uploaded --- QID: " + qid + " | FieldName: " + + // fieldName + " | File: " + file.getOriginalFilename() + " | Path: " + + // uploadedPath); + } + } + } + + boolean isNotWilling = false; + if (qid != null && qid == 1) { + String trimmed = answer.trim(); + if ("38".equals(trimmed) || "Not willing to respond (mark them)".equalsIgnoreCase(trimmed)) { + isNotWilling = true; + } + } + + if (isNotWilling) { + jdbcRagPickerSurveyTemplate.update(insertparticipateSql, qid, answer, othersAnswer, surveyId, + cid, cby, + parentAnswerId); + // System.out.println("--- DB SAVE (Participate) --- QID: " + qid + " | + // FieldName: " + fieldName + " | Answer: " + answer + " | OthersAnswer: " + + // othersAnswer); + } else { + if (!hasNotWillingResponse) { + jdbcRagPickerSurveyTemplate.update(insertSql, qid, answer, othersAnswer, surveyId, cid, cby, + parentAnswerId); + // System.out.println("--- DB SAVE (Response) --- QID: " + qid + " | FieldName: + // " + fieldName + " | Answer: " + answer + " | OthersAnswer: " + othersAnswer); + } + } + } + } + + // Insert placeholder responses for all other active categories if they do not + // exist + if (!hasNotWillingResponse) { + try { + String catSql = "SELECT id FROM question_category_master WHERE isactive = 1 AND isdelete = 0"; + List> allCats = jdbcRagPickerSurveyTemplate.queryForList(catSql); + for (Map catMap : allCats) { + Object otherCidObj = catMap.get("id"); + if (otherCidObj != null) { + String otherCid = otherCidObj.toString(); + if (!otherCid.equals(cid)) { + String checkExistSql = "SELECT COUNT(*) FROM rag_picker_survey_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0"; + Integer existCount = jdbcRagPickerSurveyTemplate.queryForObject(checkExistSql, + Integer.class, + surveyId, otherCid); + if (existCount == null || existCount == 0) { + String otherQSql = "SELECT qid FROM rag_picker_survey_questions_master WHERE cid = ? AND isactive = 1 AND isdelete = 0"; + List otherQids = jdbcRagPickerSurveyTemplate.queryForList(otherQSql, + Integer.class, otherCid); + for (Integer otherQid : otherQids) { + jdbcRagPickerSurveyTemplate.update(insertSql, otherQid, null, null, surveyId, + otherCid, cby, 0); + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + System.out.println("Error inserting placeholder survey responses: " + ex.getMessage()); + } + } + + result.put("status", true); + result.put("message", "Survey responses saved successfully"); + result.put("survey_id", surveyId); + + } catch (Exception e) { + e.printStackTrace(); + result.put("status", false); + result.put("message", "Error saving survey responses: " + e.getMessage()); + } + return result; + } + + private String uploadSurveyFile(MultipartFile file, String qEnglish, String surveyId) { + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("ragpickersurvey_document_foldername"); + // if (serviceFolderName == null || serviceFolderName.trim().isEmpty()) { + // serviceFolderName = "homelesssurvey_image/"; + // } + + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + var date = DateTimeUtil.getCurrentDay(); + + String finalUploadDir = uploadDirectory + serviceFolderName + year + "/" + month + "/" + date + "/" + surveyId; + + try { + Path directoryPath = Paths.get(finalUploadDir); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + String cleanName = qEnglish.replaceAll("[^a-zA-Z0-9]", "_").replaceAll("_+", "_"); + String datetimetxt = DateTimeUtil.getCurrentDateTime() + "_" + generateRandomString(); + String fileName = cleanName + "_" + datetimetxt + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); + + String filePath = finalUploadDir + "/" + fileName; + String relativePath = "/" + serviceFolderName + year + "/" + month + "/" + date + "/" + surveyId + "/" + + fileName; + + Path path = Paths.get(filePath); + byte[] bytes = file.getBytes(); + + try { + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + if (image != null) { + byte[] compressedBytes = compressImage(image, 0.5f); + Files.write(path, compressedBytes); + } else { + Files.write(path, bytes); + } + } catch (Exception e) { + Files.write(path, bytes); + } + + return relativePath; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file: " + e.getMessage(); + } + } + + 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(); + byteArrayOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public Map getCategoryStatus(String surveyId) { + Map result = new HashMap<>(); + try { + // Check if the Profile category responses or surveyor location record exists + // for this surveyId + String checkProfileSql = "SELECT COUNT(*) FROM rag_picker_survey_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0"; + Integer profileCount = jdbcRagPickerSurveyTemplate.queryForObject(checkProfileSql, Integer.class, surveyId); + + String checkLocSql = "SELECT COUNT(*) FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0"; + Integer locCount = jdbcRagPickerSurveyTemplate.queryForObject(checkLocSql, Integer.class, surveyId); + + if ((profileCount == null || profileCount == 0) && (locCount == null || locCount == 0)) { + result.put("status", false); + result.put("message", + "Profile not created for this survey ID. Please save the Profile category first."); + return result; + } + + String catSql = "SELECT id, english_name, icon, orderby FROM question_category_master WHERE isactive=1 AND isdelete=0 ORDER BY orderby"; + List> categories = jdbcRagPickerSurveyTemplate.queryForList(catSql); + + List> dataList = new ArrayList<>(); + + for (Map cat : categories) { + Object cidObj = cat.get("id"); + String cidStr = cidObj != null ? cidObj.toString() : ""; + + String responseSql = "SELECT COUNT(*) FROM (" + + " SELECT id FROM rag_picker_survey_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0 AND answer IS NOT NULL AND answer != '' " + + + " UNION ALL " + + " SELECT id FROM rag_picker_survey_participate_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0 AND answer IS NOT NULL AND answer != '' " + + + ") t"; + Integer count = jdbcRagPickerSurveyTemplate.queryForObject(responseSql, Integer.class, surveyId, cidStr, + surveyId, cidStr); + + Map statusMap = new HashMap<>(); + statusMap.put("cid", cidObj); + statusMap.put("english_name", cat.get("english_name")); + statusMap.put("orderby", cat.get("orderby")); + statusMap.put("icon", cat.get("icon")); + statusMap.put("status", (count != null && count > 0) ? "Completed" : "Pending"); + + dataList.add(statusMap); + } + + result.put("status", true); + result.put("data", dataList); + return result; + } catch (Exception e) { + e.printStackTrace(); + result.put("status", false); + result.put("message", "Error fetching category status: " + e.getMessage()); + return result; + } + } + + public List> getProfileCreatedList(String cby) { + List> resultList = new ArrayList<>(); + try { + String sql; + List args = new ArrayList<>(); + if (cby != null && !cby.trim().isEmpty() && !cby.equalsIgnoreCase("null")) { + sql = "SELECT DISTINCT survey_id FROM rag_picker_survey_response WHERE cid = '1' AND cby = ? AND isactive = 1 AND isdelete = 0"; + args.add(cby); + } else { + sql = "SELECT DISTINCT survey_id FROM rag_picker_survey_response WHERE cid = '1' AND isactive = 1 AND isdelete = 0"; + } + + List surveyIds = jdbcRagPickerSurveyTemplate.queryForList(sql, args.toArray(), String.class); + + for (String surveyId : surveyIds) { + Map profileMap = new LinkedHashMap<>(); + profileMap.put("survey_id", surveyId); + + // Fetch Location Details + String locSql = "SELECT zone, ward, latitude, longitude, address, loginId as cby, cdate FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0 LIMIT 1"; + List> locData = jdbcRagPickerSurveyTemplate.queryForList(locSql, surveyId); + + if (!locData.isEmpty()) { + Map loc = locData.get(0); + profileMap.put("cby", loc.get("cby")); + profileMap.put("cdate", loc.get("cdate")); + profileMap.put("zone", loc.get("zone")); + profileMap.put("ward", loc.get("ward")); + profileMap.put("latitude", loc.get("latitude")); + profileMap.put("longitude", loc.get("longitude")); + profileMap.put("address", loc.get("address")); + } else { + profileMap.put("zone", ""); + profileMap.put("ward", ""); + profileMap.put("latitude", ""); + profileMap.put("longitude", ""); + profileMap.put("address", ""); + + String fallbackSql = "SELECT cby, cdate FROM rag_picker_survey_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0 LIMIT 1"; + List> fallbackData = jdbcRagPickerSurveyTemplate.queryForList(fallbackSql, + surveyId); + if (!fallbackData.isEmpty()) { + profileMap.put("cby", fallbackData.get(0).get("cby")); + profileMap.put("cdate", fallbackData.get(0).get("cdate")); + } else { + profileMap.put("cby", ""); + profileMap.put("cdate", ""); + } + } + + // Fetch Answers + String ansSql = "SELECT q.qid, q.field_name, q.question_type, q.q_english, q.master_table_name, r.answer, r.others_answer " + + + "FROM rag_picker_survey_response r " + + "JOIN rag_picker_survey_questions_master q ON r.qid = q.qid " + + "WHERE r.survey_id = ? AND r.cid = '1' AND r.isactive = 1 AND r.isdelete = 0 " + + "AND ((q.isactive = 1 AND q.isdelete = 0) OR (q.cid = '1' AND q.field_name IN ('q2', 'q78', 'q11', 'q8', 'q9', 'q10', 'q77')))"; + + List> ansData = jdbcRagPickerSurveyTemplate.queryForList(ansSql, surveyId); + List> answersList = new ArrayList<>(); + + String fileBaseUrlVal = environment.getProperty("fileBaseUrl"); + if (fileBaseUrlVal == null) { + fileBaseUrlVal = ""; + } + + List allowedFields = java.util.Arrays.asList("q2", "q78", "q11", "q8", "q9", "q10", "q77"); + + for (Map ans : ansData) { + String fieldName = (String) ans.get("field_name"); + if (fieldName != null && allowedFields.contains(fieldName)) { + Integer qid = (Integer) ans.get("qid"); + String qEnglish = (String) ans.get("q_english"); + String masterTable = (String) ans.get("master_table_name"); + String questionType = (String) ans.get("question_type"); + String answerVal = (String) ans.get("answer"); + + String resolvedValue = answerVal != null ? answerVal : ""; + + if (answerVal != null && !answerVal.trim().isEmpty()) { + // Try to resolve the option ID to its english name + try { + int optionId = Integer.parseInt(answerVal.trim()); + if (masterTable != null && !masterTable.trim().isEmpty()) { + String query = "SELECT english_name FROM " + masterTable + " WHERE id = ? LIMIT 1"; + List names = jdbcRagPickerSurveyTemplate.queryForList(query, String.class, + optionId); + if (!names.isEmpty()) { + resolvedValue = names.get(0); + } + } else { + String query = "SELECT answer FROM rag_picker_survey_answer_master WHERE qid = ? AND id = ? LIMIT 1"; + List names = jdbcRagPickerSurveyTemplate.queryForList(query, String.class, + qid, optionId); + if (!names.isEmpty()) { + resolvedValue = names.get(0); + } + } + } catch (NumberFormatException e) { + // Keep original value if not a valid number ID + } + } + + if (resolvedValue != null && !resolvedValue.isEmpty() && questionType != null && + (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) { + resolvedValue = fileBaseUrlVal + "/gccofficialapp/files" + resolvedValue; + } + + Map ansMap = new LinkedHashMap<>(); + ansMap.put("question", qEnglish != null ? qEnglish : ""); + ansMap.put("field_name", fieldName); + ansMap.put("field_value", resolvedValue != null ? resolvedValue : ""); + answersList.add(ansMap); + + String othersVal = (String) ans.get("others_answer"); + if (othersVal != null && !othersVal.isEmpty()) { + Map othersMap = new LinkedHashMap<>(); + othersMap.put("question", "Please specify"); + othersMap.put("field_name", fieldName + "_other"); + othersMap.put("field_value", othersVal); + answersList.add(othersMap); + } + } + } + profileMap.put("answers", answersList); + resultList.add(profileMap); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return resultList; + } + + private List> parseFamilyMembersJson(String jsonStr) { + if (jsonStr == null || jsonStr.trim().isEmpty()) { + return new ArrayList<>(); + } + String str = jsonStr.trim(); + // First try parsing using standard ObjectMapper + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(str, new TypeReference>>() { + }); + } catch (Exception e) { + // Ignore standard JSON parsing exception, try lenient fallback + } + + // Lenient parsing fallback + List> list = new ArrayList<>(); + try { + if (str.startsWith("[")) { + str = str.substring(1); + } + if (str.endsWith("]")) { + str = str.substring(0, str.length() - 1); + } + str = str.trim(); + if (str.isEmpty()) { + return list; + } + + // Match all occurrences of { ... } + java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\{([^}]+)\\}"); + java.util.regex.Matcher matcher = pattern.matcher(str); + while (matcher.find()) { + String objContent = matcher.group(1); + Map map = new LinkedHashMap<>(); + String[] pairs = objContent.split(","); + for (String pair : pairs) { + int colonIdx = pair.indexOf(':'); + if (colonIdx != -1) { + String key = pair.substring(0, colonIdx).trim(); + String value = pair.substring(colonIdx + 1).trim(); + if ((value.startsWith("\"") && value.endsWith("\"")) + || (value.startsWith("'") && value.endsWith("'"))) { + value = value.substring(1, value.length() - 1); + } + map.put(key, value); + } + } + if (!map.isEmpty()) { + list.add(map); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + + private void saveFamilyMembers(List> familyList, String surveyId, String cby) { + if (familyList == null || familyList.isEmpty()) { + return; + } + + String insertFamilySql = "INSERT INTO rag_picker_survey_family_response " + + "(qid, answer, others_answer, cby, survey_id, parent_answer_id, cdate, isactive, isdelete) " + + "VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, 0)"; + + for (Map member : familyList) { + for (Map.Entry field : member.entrySet()) { + String key = field.getKey().trim(); + Object valObj = field.getValue(); + String answer = valObj == null ? "" : valObj.toString().trim(); + + // Skip utility/metadata keys if any + if ("parent_answer_id".equalsIgnoreCase(key) || "parent_aid".equalsIgnoreCase(key)) { + continue; + } + + // Resolve qid + Integer qid = null; + if (key.startsWith("q")) { + try { + qid = Integer.parseInt(key.substring(1)); + } catch (Exception e) { + // ignore + } + } else { + try { + qid = Integer.parseInt(key); + } catch (Exception e) { + // ignore + } + } + + // If not numeric/q-prefixed, resolve statically first + if (qid == null) { + String cleanKey = key.toLowerCase().trim(); + if ("name".equals(cleanKey)) { + qid = 2; + } else if ("relationship".equals(cleanKey)) { + qid = 15; + } else if ("age".equals(cleanKey)) { + qid = 6; + } + } + + // Fallback: If still null, try resolving by field_name or matching q_english + // (case-insensitive) from DB without active/delete constraint + if (qid == null) { + try { + String cleanKey = key.toLowerCase().trim(); + String getQidSql = "SELECT qid FROM rag_picker_survey_questions_master " + + "WHERE (LOWER(field_name) = ? OR LOWER(q_english) = ? OR LOWER(q_english) LIKE ?) LIMIT 1"; + List qidList = jdbcRagPickerSurveyTemplate.queryForList(getQidSql, Integer.class, + cleanKey, cleanKey, cleanKey + "%"); + if (!qidList.isEmpty()) { + qid = qidList.get(0); + } + } catch (Exception e) { + // ignore + } + } + + if (qid != null) { + // Extract parent_answer_id (if any is provided in the member object or resolved + // from mapping) + Integer parentAnswerId = null; + Object parentAidVal = member.get("parent_answer_id"); + if (parentAidVal == null) { + parentAidVal = member.get("parent_aid"); + } + if (parentAidVal != null) { + try { + parentAnswerId = Integer.parseInt(parentAidVal.toString()); + } catch (Exception e) { + // ignore + } + } + + // If still null, try resolving statically + if (parentAnswerId == null) { + if (qid == 2) { + parentAnswerId = 1; + } else if (qid == 15) { + parentAnswerId = 7; + } else if (qid == 6) { + parentAnswerId = 3; + } + } + + // Fallback: If still null, try resolving from mapping table (without + // active/delete constraint) + if (parentAnswerId == null) { + try { + String parentAidSql = "SELECT parent_aid FROM rag_picker_question_mapping WHERE child_qid = ? LIMIT 1"; + List list = jdbcRagPickerSurveyTemplate.queryForList(parentAidSql, Integer.class, qid); + if (!list.isEmpty()) { + parentAnswerId = list.get(0); + } + } catch (Exception e) { + // ignore + } + } + + // Extract others_answer if any + String othersKey = key + "_other"; + Object othersValObj = member.get(othersKey); + String othersValue = othersValObj == null ? "" : othersValObj.toString().trim(); + + // Insert to child_survey_response_family_members + try { + jdbcRagPickerSurveyTemplate.update(insertFamilySql, qid, answer, othersValue, cby, surveyId, + parentAnswerId); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } + + + +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccroadwarweb/controller/RoadWarWebAPIController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccroadwarweb/controller/RoadWarWebAPIController.java new file mode 100644 index 00000000..e1f110c1 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccroadwarweb/controller/RoadWarWebAPIController.java @@ -0,0 +1,91 @@ +package in.gov.chennaicorporation.mobileservice.gccroadwarweb.controller; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +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.gccroadwarweb.service.RoadWarWebService; + +@RestController("gccofficialapproadwarweb") +@RequestMapping("/gccofficialapp/api/roadwarweb") +public class RoadWarWebAPIController { + + @Autowired + RoadWarWebService roadwarwebservice; + + // @GetMapping("/getRoadMasterDetails") + // public Map getRoadMasterDetails(@RequestParam String loginId) + // { + // Map response = new HashMap<>(); + + // List> roadDetails = + // roadwarwebservice.getRoadMasterDetails(loginId); + + // if (roadDetails != null) { + // response.put("status", "200"); + // response.put("message", "Success"); + // response.put("data", roadDetails); + // } else { + // response.put("status", "200"); + // response.put("message", "No Data Found"); + // response.put("data", null); + // } + // return response; + // } + + @GetMapping("/getRoadMasterDetails") + public Map getRoadMasterDetails(@RequestParam String road_id) { + Map response = new HashMap<>(); + + Map roadDetails = roadwarwebservice.getRoadMasterDetails(road_id); + + if (roadDetails != null) { + response.put("status", "200"); + response.put("message", "Success"); + response.put("data", roadDetails); + } else { + response.put("status", "200"); + response.put("message", "No Data Found"); + response.put("data", ""); + } + return response; + } + + @PostMapping("/saveRoadMasterFiles") + public Map saveRoadMasterFiles( + @RequestParam("ref_id") String ref_id, + @RequestParam("file1") MultipartFile file1, + @RequestParam("file2") MultipartFile file2, + @RequestParam("file3") MultipartFile file3, + @RequestParam(value = "file4", required = false) MultipartFile file4, + @RequestParam("loginId") String loginId) { + Map response = new HashMap<>(); + + String result = roadwarwebservice.saveRoadMasterFiles(ref_id, file1, file2, file3, file4, loginId); + + if ("already_exists".equalsIgnoreCase(result)) { + Map existingData = roadwarwebservice.getRoadMasterFileDetails(ref_id); + response.put("status", "200"); + response.put("message", "Files already uploaded for this road."); + response.put("data", existingData); + } else if ("Success".equalsIgnoreCase(result)) { + response.put("status", "200"); + response.put("message", "Success"); + response.put("data", result); + } else { + response.put("status", "200"); + response.put("message", result != null ? result : "Failed to save files"); + response.put("data", null); + } + return response; + } + +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/gccroadwarweb/service/RoadWarWebService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/gccroadwarweb/service/RoadWarWebService.java new file mode 100644 index 00000000..93aa9e3c --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/gccroadwarweb/service/RoadWarWebService.java @@ -0,0 +1,479 @@ +package in.gov.chennaicorporation.mobileservice.gccroadwarweb.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.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.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class RoadWarWebService { + + @Autowired + private JdbcTemplate jdbcRoadWarWebTemplate; + + 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("mysqlroadwarwebGccDataSource") DataSource roadwarwebDataSource) { + this.jdbcRoadWarWebTemplate = new JdbcTemplate(roadwarwebDataSource); + } + + public RoadWarWebService(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(MultipartFile file, String name) { + + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("roadwarweb_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 + "_" + 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); + + // Detect file type using extension and MIME content type + String originalFilename = file.getOriginalFilename() != null ? file.getOriginalFilename().toLowerCase() + : ""; + String contentType = file.getContentType() != null ? file.getContentType().toLowerCase() : ""; + + boolean isImage = originalFilename.endsWith(".jpg") || originalFilename.endsWith(".jpeg") + || contentType.equals("image/jpeg"); + boolean isPdf = originalFilename.endsWith(".pdf") || contentType.equals("application/pdf"); + + // 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); + + if (isImage) { + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image with 50% quality and write to file + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); + Files.write(path, compressedBytes); + + } else if (isPdf) { + // Directly save the PDF without any compression + Files.write(path, file.getBytes()); + + } else { + // Unsupported file type — reject the upload + return "Unsupported file type: " + file.getOriginalFilename(); + } + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + // public List> getRoadMasterDetails(String loginId) { + + // String zone = getZoneFromLoginId(loginId); + + // String sqlQuery = "SELECT " + + // " rm.ref_id, " + + // " rm.zone, " + + // " rm.ward, " + + // " rm.road_name, " + + // " rt.road_type, " + + // " rm.road_length, " + + // " rm.road_avg_width, " + + // " rm.road_area, " + + // " rm.footpath_material, " + + // " rm.footpath_length, " + + // " rm.footpath_width, " + + // " rm.footpath_from_location, " + + // " rm.footpath_to_location, " + + // " rm.is_swd, " + + // " ifnull(rm.swd_from,'') as swd_from_location, " + + // " ifnull(rm.swd_to,'') as swd_to_location, " + + // " ifnull(rm.swd_length,'') as swd_length, " + + // " ifnull(rm.is_scp,'') as scp_availability, " + + // " ifnull(rm.scp_count,'') as scp_count, " + + // " ifnull(rm.is_manhole,'') as manhole_availability, " + + // " ifnull(rm.manhole_count,'') as manhole_count, " + + // " ifnull(rm.manhole_location,'') as manhole_location, " + + // " ifnull(rm.is_cpipe,'') as chutpipe_availability, " + + // " ifnull(rm.cpipe_count,'') as chutpipe_count, " + + // " ifnull(rm.is_rwh,'') as rain_water_harvesting_availability, " + + // " ifnull(rm.rwh_count,'') as rain_water_harvesting_count, " + + // " ifnull(rm.sewer_length,'') as sewer_length, " + + // " ifnull(rm.sewer_size,'') as sewer_size, " + + // " ifnull(rm.is_electric_poles,'') as electric_poles_availability, " + + // " ifnull(rm.ep_count,'') as electric_pole_count, " + + // " ifnull(rm.is_hml,'') as high_mass_light_availability, " + + // " ifnull(rm.culvert_bridge_count,'') as culvert_bridge_count, " + + // " ifnull(rm.details,'') as culvert_bridge_details, " + + // " ifnull(rm.is_busshelter,'') as bus_shelter_availability , " + + // " ifnull(rm.busshelter_count,'') as bus_shelter_count, " + + // " ifnull(rm.is_centermedian,'') as center_median_availability, " + + // " ifnull(rm.erp_asset_code,'') as erp_asset_code, " + + // " DATE_FORMAT(rm.cdate,'%d-%m-%Y %r') AS cdate, " + + // " rm.cby, " + + // " rd.relaying_history " + + // "FROM road_details_master rm " + + // "LEFT JOIN road_type_master rt " + + // " ON rm.road_type = rt.id " + + // " AND rt.is_active = 1 " + + // "LEFT JOIN ( " + + // " SELECT " + + // " road_ref_id, " + + // " JSON_ARRAYAGG( " + + // " JSON_OBJECT( " + + // " 'relayMonth', relay_month, " + + // " 'relayYear', relay_year, " + + // " 'crValue', cr_value, " + + // " 'roadType', road_type, " + + // " 'remarks', remarks, " + + // " 'cdate', DATE_FORMAT(cdate, '%d-%m-%Y %r') " + + // " ) " + + // " ) AS relaying_history " + + // " FROM relaying_details " + + // " WHERE is_active = 1 " + + // " GROUP BY road_ref_id " + + // ") rd " + + // "ON rm.ref_id = rd.road_ref_id " + + // "WHERE NOT EXISTS ( SELECT ref_id " + + // "FROM road_master_files rmf " + + // "WHERE rmf.road_ref_id = rm.ref_id " + + // "AND rmf.is_active = 1 " + + // "AND rmf.is_delete = 0 ) and rm.zone = ? "; + + // List> results = + // jdbcRoadWarWebTemplate.queryForList(sqlQuery, zone); + // return results; + + // } + + public Map getRoadMasterDetails(String road_id) { + + Map result = new HashMap<>(); + + // String checkSql = "SELECT COUNT(*)as count, ifnull(group_concat( ' " + + // fileBaseUrl + // + "gccofficialapp/files',rmf.file_path),'File not uploaded') as filePaths " + + // "FROM road_master_files rmf " + + // "left join road_details_master rdm on rmf.road_ref_id = rdm.ref_id and + // rdm.is_active = 1 and rdm.is_delete = 0 " + // + + // "WHERE rdm.road_id = ? AND rmf.is_active = 1 AND rmf.is_delete = 0"; + + // result = jdbcRoadWarWebTemplate.queryForMap(checkSql, road_id); + + // long existingCount = result.get("count") != null ? ((Number) + // result.get("count")).longValue() : 0L; + + // if (existingCount > 0) { + // return result; + // } + // String zone = getZoneFromLoginId(loginId); + + try { + String sqlQuery = "SELECT " + + " rm.ref_id, " + + " rm.zone, " + + " rm.ward, " + + " ifnull(rm.road_name,'') as road_name, " + + " ifnull(rt.road_type,'') as road_type, " + + " ifnull(rm.road_length,'') as road_length, " + + " ifnull(rm.road_avg_width,'') as road_avg_width, " + + " ifnull(rm.road_area,'') as road_area, " + + " ifnull(rm.footpath_material,'') as footpath_material, " + + " ifnull(rm.footpath_length,'') as footpath_length, " + + " ifnull(rm.footpath_width,'') as footpath_width, " + + " ifnull(rm.footpath_from_location,'') as footpath_from_location, " + + " ifnull(rm.footpath_to_location,'') as footpath_to_location, " + + " ifnull(rm.is_swd,'') as is_swd, " + + " ifnull(rm.swd_from,'') as swd_from_location, " + + " ifnull(rm.swd_to,'') as swd_to_location, " + + " ifnull(rm.swd_length,'') as swd_length, " + + " ifnull(rm.is_scp,'') as scp_availability, " + + " ifnull(rm.scp_count,'') as scp_count, " + + " ifnull(rm.is_manhole,'') as manhole_availability, " + + " ifnull(rm.manhole_count,'') as manhole_count, " + + " ifnull(rm.manhole_location,'') as manhole_location, " + + " ifnull(rm.is_cpipe,'') as chutpipe_availability, " + + " ifnull(rm.cpipe_count,'') as chutpipe_count, " + + " ifnull(rm.is_rwh,'') as rain_water_harvesting_availability, " + + " ifnull(rm.rwh_count,'') as rain_water_harvesting_count, " + + " ifnull(rm.sewer_length,'') as sewer_length, " + + " ifnull(rm.sewer_size,'') as sewer_size, " + + " ifnull(rm.is_electric_poles,'') as electric_poles_availability, " + + " ifnull(rm.ep_count,'') as electric_pole_count, " + + " ifnull(rm.is_hml,'') as high_mass_light_availability, " + + " ifnull(rm.culvert_bridge_count,'') as culvert_bridge_count, " + + " ifnull(rm.details,'') as culvert_bridge_details, " + + " ifnull(rm.is_busshelter,'') as bus_shelter_availability , " + + " ifnull(rm.busshelter_count,'') as bus_shelter_count, " + + " ifnull(rm.is_centermedian,'') as center_median_availability, " + + " ifnull(rm.erp_asset_code,'') as erp_asset_code, " + + " DATE_FORMAT(rm.cdate,'%d-%m-%Y %r') AS cdate, " + + " rm.cby, " + + " rd.relaying_history, " + + "CASE WHEN EXISTS ( " + + " SELECT 1 " + + " FROM road_master_files rmf " + + " WHERE rmf.road_ref_id = rm.ref_id " + + " AND rmf.file_path IS NOT NULL " + + " AND rmf.is_active = 1 " + + " AND rmf.is_delete = 0 ) THEN FALSE ELSE TRUE END AS fileFlag, " + + " (SELECT JSON_ARRAYAGG( CONCAT('https://gccservices.in/gccofficialapp/files', file_path) ) " + + " FROM road_master_files rmf WHERE rmf.road_ref_id = rm.ref_id " + + " AND rmf.is_active = 1 AND rmf.is_delete = 0 ) AS filePaths " + + "FROM road_details_master rm " + + "LEFT JOIN road_type_master rt ON rm.road_type = rt.id AND rt.is_active = 1 " + + "LEFT JOIN ( SELECT road_ref_id, JSON_ARRAYAGG( JSON_OBJECT( " + + " 'relayMonth', relay_month, " + + " 'relayYear', relay_year, " + + " 'crValue', cr_value, " + + " 'roadType', road_type, " + + " 'remarks', remarks, " + + " 'cdate', DATE_FORMAT(cdate, '%d-%m-%Y %r') " + + " ) " + + " ) AS relaying_history " + + " FROM relaying_details " + + " WHERE is_active = 1 " + + " GROUP BY road_ref_id " + + ") rd " + + "ON rm.ref_id = rd.road_ref_id " + + "WHERE rm.is_active=1 and rm.is_delete=0 and rm.road_id = ? "; + + result = jdbcRoadWarWebTemplate.queryForMap(sqlQuery, road_id); + return result; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + + } + + private String getZoneFromLoginId(String loginId) { + String sqlQuery = "SELECT `zone` FROM gcc_penalty_hoardings.hoading_user_list WHERE userid = ? LIMIT 1"; + + // Query the database using queryForList + List> results = jdbcRoadWarWebTemplate.queryForList(sqlQuery, loginId); + + // Check if results is not empty and extract the ward value + if (!results.isEmpty()) { + System.out.println("zone....." + results); + // Extract the ward value from the first result + return (String) results.get(0).get("zone"); + } + + // Handle the case where no result is found + return "00"; // or return null based on your needs + + } + + // public String saveRoadMasterFiles(String ref_id, List files, + // String loginId) { + + // try { + + // String checkSql = "SELECT COUNT(*) FROM road_master_files WHERE road_ref_id = + // ? AND is_active = 1 AND is_delete = 0"; + // Integer existingCount = jdbcRoadWarWebTemplate.queryForObject(checkSql, + // Integer.class, ref_id); + + // if (existingCount != null && existingCount > 0) { + // return "already_exists"; + // } + + // String insertSql = "INSERT INTO road_master_files (road_ref_id, file_path, + // file_flag, cby, is_active, is_delete) " + // + "VALUES (?, ?, ?, ?, 1, 0)"; + + // if (files != null) { + // for (int i = 0; i < files.size(); i++) { + // MultipartFile file = files.get(i); + // String fileFlag = "file" + (i + 1); + + // if (file == null || file.isEmpty()) { + // continue; + // } + + // String filepath_txt = fileUpload(file, fileFlag); + + // if (filepath_txt == null || filepath_txt.startsWith("Failed") + // || filepath_txt.startsWith("Unsupported")) { + // System.err.println("File upload failed for " + fileFlag + ": " + + // filepath_txt); + // continue; + // } + + // jdbcRoadWarWebTemplate.update(insertSql, ref_id, filepath_txt, fileFlag, + // loginId); + // } + // } + + // return "Success"; + + // } catch (Exception e) { + // e.printStackTrace(); + // return "Failed to upload image " + e.getMessage(); + // } + // } + + public String saveRoadMasterFiles(String ref_id, MultipartFile file1, MultipartFile file2, MultipartFile file3, + MultipartFile file4, + String loginId) { + + try { + + String checkSql = "SELECT COUNT(*) FROM road_master_files WHERE road_ref_id = ? AND is_active = 1 AND is_delete = 0"; + Integer existingCount = jdbcRoadWarWebTemplate.queryForObject(checkSql, Integer.class, ref_id); + + if (existingCount != null && existingCount > 0) { + return "already_exists"; + } + + MultipartFile[] files = { file1, file2, file3, file4 }; + String[] fileFlags = { "file1", "file2", "file3", "file4" }; + + String insertSql = "INSERT INTO road_master_files (road_ref_id, file_path, file_flag, cby, is_active, is_delete) " + + "VALUES (?, ?, ?, ?, 1, 0)"; + + for (int i = 0; i < files.length; i++) { + MultipartFile file = files[i]; + + if (file == null || file.isEmpty()) { + break; + } + String filepath_txt = fileUpload(file, fileFlags[i]); + + if (filepath_txt == null || filepath_txt.startsWith("Failed") + || filepath_txt.startsWith("Unsupported")) { + System.err.println("File upload failed for " + fileFlags[i] + ": " + filepath_txt); + break; + } + + jdbcRoadWarWebTemplate.update(insertSql, ref_id, filepath_txt, fileFlags[i], loginId); + } + + return "Success"; + + } catch (Exception e) { + e.printStackTrace(); + return "Failed to upload image " + e.getMessage(); + } + } + + public Map getRoadMasterFileDetails(String ref_id) { + Map result = new HashMap<>(); + + String checkSql = "SELECT COUNT(*)as count, ifnull(group_concat( ' " + fileBaseUrl + + "gccofficialapp/files',rmf.file_path),'File not uploaded') as filePaths " + + "FROM road_master_files rmf " + + "left join road_details_master rdm on rmf.road_ref_id = rdm.ref_id and rdm.is_active = 1 and rdm.is_delete = 0 " + + + "WHERE rdm.ref_id = ? AND rmf.is_active = 1 AND rmf.is_delete = 0 "; + + result = jdbcRoadWarWebTemplate.queryForMap(checkSql, ref_id); + + long existingCount = result.get("count") != null ? ((Number) result.get("count")).longValue() : 0L; + + if (existingCount > 0) { + return result; + } else { + result.put("status", "200"); + result.put("message", "File not uploaded"); + result.put("data", null); + } + return result; + } + +} diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/controller/GreenCommitteeController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/controller/GreenCommitteeController.java index 934ebb92..e776ec4c 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/controller/GreenCommitteeController.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/controller/GreenCommitteeController.java @@ -47,8 +47,10 @@ public class GreenCommitteeController { @GetMapping(value = "/getComplaintList") public List getComplaintList( - @RequestParam(value = "loginId", required = true) String loginId) { - return greenCommitteeService.getComplaintList(loginId); + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "zone", required = false) String zone, + @RequestParam(value = "ward", required = false) String ward) { + return greenCommitteeService.getComplaintList(loginId, zone, ward); } @PostMapping("/saveInspectionData") diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/service/GreenCommitteeService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/service/GreenCommitteeService.java index d33e8efd..fe903a0b 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/service/GreenCommitteeService.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/greenCommittee/service/GreenCommitteeService.java @@ -351,13 +351,13 @@ public class GreenCommitteeService { // } @Transactional(readOnly = true) - public List getComplaintList(String loginId) { + public List getComplaintList(String loginId, String zone, String ward) { // 1️ Get department (GCC / NGO / TNFD) String department = getUserDepartment(loginId); // 2️ Get only ref_ids NOT inspected by this department - List refIds = getAllinspectionComplaintList(department); + List refIds = getAllinspectionComplaintList(department, zone, ward); List> dataList = new ArrayList<>(); @@ -387,7 +387,44 @@ public class GreenCommitteeService { return jdbcTemplate.queryForObject(sql, String.class, loginId); } - public List getAllinspectionComplaintList(String inspectionDepartment) { + public List getAllinspectionComplaintList(String inspectionDepartment, String zone, String ward) { + + StringBuilder sql = new StringBuilder(); + List params = new ArrayList<>(); + + sql.append("SELECT rd.ref_id ") + .append("FROM reg_details rd ") + .append("LEFT JOIN inspection_data id ") + .append(" ON rd.ref_id = id.ref_id ") + .append(" AND id.inspection_by = ? ") + .append(" AND id.isactive = 1 ") + .append("WHERE rd.is_active = 1 ") + .append(" AND id.ref_id IS NULL "); + + params.add(inspectionDepartment); + + // Apply total_trees condition only for NGO + if ("NGO".equalsIgnoreCase(inspectionDepartment)) { + sql.append(" AND rd.total_trees > 3 "); + } + + if (zone != null && !zone.isEmpty()) { + sql.append(" AND rd.zone = ? "); + params.add(zone); + } + + if (ward != null && !ward.isEmpty()) { + sql.append(" AND rd.ward = ? "); + params.add(ward); + } + + return jdbcTemplate.query( + sql.toString(), + params.toArray(), + (rs, rowNum) -> rs.getString("ref_id")); + } + + public List getAllinspectionComplaintList1(String inspectionDepartment, String zone, String ward) { String sql = "SELECT rd.ref_id " + "FROM reg_details rd " + @@ -398,9 +435,21 @@ public class GreenCommitteeService { "WHERE rd.is_active = 1 " + " AND id.ref_id IS NULL"; + List params = new ArrayList<>(); + params.add(inspectionDepartment); + + if (zone != null && !zone.isEmpty()) { + sql += " AND rd.zone = ? "; + params.add(zone); + } + if (ward != null && !ward.isEmpty()) { + sql += " AND rd.ward = ? "; + params.add(ward); + } + return jdbcTemplate.query( sql, - new Object[] { inspectionDepartment }, + params.toArray(), (rs, rowNum) -> rs.getString("ref_id")); } diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/ie_complaints/service/ieComplaintService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/ie_complaints/service/ieComplaintService.java index 2415f426..85f274ab 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/ie_complaints/service/ieComplaintService.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/ie_complaints/service/ieComplaintService.java @@ -886,6 +886,178 @@ public class ieComplaintService { Map response = new HashMap<>(); + try { + + // String ward = getWardByLoginId(loginid, "si_so"); + String ward = getWardByLoginId(loginid); + String zone = getZoneByLoginId(loginid); + System.out.println("ward.....12" + ward); + System.out.println("zone.....12" + zone); + // Zone 04 and Zone 08 + /* + * if (!"04".equals(zone) && !"08".equals(zone)) { + * + * response.put("status", "Failed"); + * response.put("message", "No data available"); + * response.put("data", new ArrayList<>()); + * + * return response; + * } + * + * // Zone 07 - allow only wards 082,083,085 + * if ("07".equals(zone) + * && Arrays.asList("082", "083", "085").contains(ward)) { + * + * response.put("status", "Failed"); + * response.put("message", "No data available"); + * response.put("data", new ArrayList<>()); + * + * return response; + * } + */ + String mappingSql = "SELECT zone, ward FROM gcc_users.ward_mapping WHERE userid = ?"; + + Map mapping = jdbcTemplate.queryForMap(mappingSql, loginid); + + String multiplezone = mapping.get("zone") == null ? "all" : mapping.get("zone").toString().trim(); + String multipleward = mapping.get("ward") == null ? "all" : mapping.get("ward").toString().trim(); + + StringBuilder sqlQuery = new StringBuilder(); + + sqlQuery.append( + "SELECT " + + " cd.zone, " + + " cd.ward, " + + " cd.street_name, " + + " cd.latitude, " + + " cd.longitude, " + + " CASE WHEN cd.image_path IS NOT NULL " + + " THEN CONCAT('" + fileBaseUrl + "/gccofficialapp/files', cd.image_path) " + + " ELSE '' END AS image_path, " + + " cd.remarks, " + + " cd.street_id, " + + " cd.cby, " + + " cm.complaint_name, " + + " cd.ref_id, " + + " cd.complaint_id, " + + " q.q_english AS question_name, " + + " CASE " + + " WHEN q.input_type = 'text' THEN r.answer_text " + + " ELSE GROUP_CONCAT(DISTINCT a.english_name ORDER BY a.answer_id SEPARATOR ', ') " + + " END AS answer_value " + + "FROM complaint_details cd " + + "LEFT JOIN response r ON r.ref_id = cd.ref_id " + + "LEFT JOIN questionmaster q ON q.question_id = r.q_id " + + "LEFT JOIN answer a ON FIND_IN_SET(a.answer_id, r.answer_id) " + + "JOIN complaint_master cm ON cm.complaint_id = cd.complaint_id " + + "WHERE cd.status='pending' "); + + List params = new ArrayList<>(); + + // Zone Filter + if (!"all".equalsIgnoreCase(multiplezone)) { + sqlQuery.append(" AND FIND_IN_SET(cd.zone, ?) "); + params.add(multiplezone); + } + + // Ward Filter + if (!"all".equalsIgnoreCase(multipleward)) { + sqlQuery.append(" AND FIND_IN_SET(cd.ward, ?) "); + params.add(multipleward); + } + + sqlQuery.append( + " GROUP BY " + + " cd.zone, cd.ward, cd.street_name, cd.street_id, " + + " cd.latitude, cd.longitude, cd.image_path, " + + " cd.remarks, cd.cby, cm.complaint_name, " + + " cd.ref_id, cd.complaint_id, q.question_id, r.answer_text " + + " ORDER BY cd.ref_id, q.question_id"); + + List> rows = jdbcTemplate.queryForList(sqlQuery.toString(), params.toArray()); + + /* "AND cd.ref_id NOT IN (SELECT ref_id FROM completion) " + */ + + // ✅ NO DATA CASE + if (rows == null || rows.isEmpty()) { + response.put("status", "Failed"); + response.put("message", "No data available"); + response.put("data", new ArrayList<>()); + return response; + } + + // ✅ GROUPING + Map> complaintMap = new LinkedHashMap<>(); + + for (Map row : rows) { + + String refId = String.valueOf(row.get("ref_id")); + + if (!complaintMap.containsKey(refId)) { + + Map complaint = new LinkedHashMap<>(); + + complaint.put("zone", row.get("zone")); + complaint.put("ward", row.get("ward")); + complaint.put("street_name", row.get("street_name")); + complaint.put("street_id", row.get("street_id")); + + complaint.put("latitude", row.get("latitude")); + complaint.put("longitude", row.get("longitude")); + complaint.put("image_path", row.get("image_path")); + complaint.put("remarks", row.get("remarks")); + complaint.put("complaint_name", row.get("complaint_name")); + + complaint.put("cby", row.get("cby")); + + complaint.put("ref_id", refId); + + complaint.put("questions", new ArrayList<>()); + + complaintMap.put(refId, complaint); + } + + Map question = new LinkedHashMap<>(); + question.put("question_name", + row.get("question_name") == null ? "" : row.get("question_name").toString()); + + question.put("answer_value", + row.get("answer_value") == null ? "" : row.get("answer_value").toString()); + /* + * question.put("question_name", row.get("question_name")); + * question.put("answer_value", row.get("answer_value")); + */ + + List> questions = (List>) complaintMap + .get(refId) + .get("questions"); + + questions.add(question); + } + + List> result = new ArrayList<>(complaintMap.values()); + + // ✅ SUCCESS RESPONSE + response.put("status", "Success"); + response.put("message", "IE SiSO List."); + response.put("data", result); + + } catch (Exception e) { + + e.printStackTrace(); + + response.put("status", "Error"); + response.put("message", "Something went wrong"); + response.put("data", null); + } + + return response; + } + + public Map getZoneComplaintListforFeedback1beforegccuser(String loginid) { + + Map response = new HashMap<>(); + try { // String ward = getWardByLoginId(loginid, "si_so"); @@ -1844,6 +2016,148 @@ public class ieComplaintService { Map response = new HashMap<>(); + try { + + // Fetch Zone & Ward from ward_mapping + String mappingSql = "SELECT zone, ward FROM gcc_users.ward_mapping WHERE userid = ?"; + + Map mapping = jdbcTemplate.queryForMap(mappingSql, loginid); + + String zone = mapping.get("zone") == null ? "all" : mapping.get("zone").toString().trim(); + String ward = mapping.get("ward") == null ? "all" : mapping.get("ward").toString().trim(); + + System.out.println("Zone : " + zone); + System.out.println("Ward : " + ward); + + StringBuilder sqlQuery = new StringBuilder(); + + sqlQuery.append( + "SELECT " + + " cd.zone, " + + " cd.ward, " + + " cd.street_name, " + + " cd.latitude, " + + " cd.longitude, " + + " CASE WHEN cd.image_path IS NOT NULL " + + " THEN CONCAT('" + fileBaseUrl + "/gccofficialapp/files', cd.image_path) " + + " ELSE '' END AS image_path, " + + " cd.remarks, " + + " cd.street_id, " + + " cd.cby, " + + " cm.complaint_name, " + + " cd.ref_id, " + + " cd.complaint_id, " + + " q.q_english AS question_name, " + + " CASE " + + " WHEN q.input_type = 'text' THEN r.answer_text " + + " ELSE GROUP_CONCAT(DISTINCT a.english_name ORDER BY a.answer_id SEPARATOR ', ') " + + " END AS answer_value " + + "FROM complaint_details cd " + + "LEFT JOIN response r ON r.ref_id = cd.ref_id " + + "LEFT JOIN questionmaster q ON q.question_id = r.q_id " + + "LEFT JOIN answer a ON FIND_IN_SET(a.answer_id, r.answer_id) " + + "JOIN complaint_master cm ON cm.complaint_id = cd.complaint_id " + + "WHERE cd.status='pending' " + + "AND cd.complaint_id IN (3,4,6,12) "); + + List params = new ArrayList<>(); + + // Zone Filter + if (!"all".equalsIgnoreCase(zone)) { + sqlQuery.append(" AND FIND_IN_SET(cd.zone, ?) "); + params.add(zone); + } + + // Ward Filter + if (!"all".equalsIgnoreCase(ward)) { + sqlQuery.append(" AND FIND_IN_SET(cd.ward, ?) "); + params.add(ward); + } + + sqlQuery.append( + " GROUP BY " + + " cd.zone, cd.ward, cd.street_name, cd.street_id, " + + " cd.latitude, cd.longitude, cd.image_path, " + + " cd.remarks, cd.cby, cm.complaint_name, " + + " cd.ref_id, cd.complaint_id, " + + " q.question_id, r.answer_text " + + " ORDER BY cd.ref_id, q.question_id"); + + List> rows = jdbcTemplate.queryForList(sqlQuery.toString(), params.toArray()); + + // No Data + if (rows == null || rows.isEmpty()) { + response.put("status", "Failed"); + response.put("message", "No data available"); + response.put("data", new ArrayList<>()); + return response; + } + + // Group complaints by ref_id + Map> complaintMap = new LinkedHashMap<>(); + + for (Map row : rows) { + + String refId = String.valueOf(row.get("ref_id")); + + if (!complaintMap.containsKey(refId)) { + + Map complaint = new LinkedHashMap<>(); + + complaint.put("zone", row.get("zone")); + complaint.put("ward", row.get("ward")); + complaint.put("street_name", row.get("street_name")); + complaint.put("street_id", row.get("street_id")); + complaint.put("latitude", row.get("latitude")); + complaint.put("longitude", row.get("longitude")); + complaint.put("image_path", row.get("image_path")); + complaint.put("remarks", row.get("remarks")); + complaint.put("complaint_name", row.get("complaint_name")); + complaint.put("cby", row.get("cby")); + complaint.put("ref_id", refId); + complaint.put("questions", new ArrayList<>()); + + complaintMap.put(refId, complaint); + } + + Map question = new LinkedHashMap<>(); + + question.put( + "question_name", + row.get("question_name") == null ? "" : row.get("question_name").toString()); + + question.put( + "answer_value", + row.get("answer_value") == null ? "" : row.get("answer_value").toString()); + + List> questions = (List>) complaintMap.get(refId) + .get("questions"); + + questions.add(question); + } + + List> result = new ArrayList<>(complaintMap.values()); + + response.put("status", "Success"); + response.put("message", "Vendor Pending List."); + response.put("data", result); + + } catch (Exception e) { + + e.printStackTrace(); + + response.put("status", "Error"); + response.put("message", "Something went wrong"); + response.put("data", null); + } + + return response; + } + + public Map getvendorPendingList1(String loginid) { + + Map response = new HashMap<>(); + try { // String ward = getWardByLoginId(loginid, "si_so"); diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java b/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java index 076f163f..776cc45a 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java @@ -170,6 +170,12 @@ public class NULMOfficerActivity { + " a.outby, " + " a.inphoto, " + " a.outphoto " + // + " CASE " + + // " WHEN DATE(a.indatetime) = CURDATE() THEN 'Present' " + + // " WHEN DATE(a.oddatetime) = CURDATE() THEN 'OD Marked' " + + // " WHEN DATE(a.leavedatetime) = CURDATE() THEN 'Leave Marked' " + + // " ELSE '' " + + // " END AS attendance_status " + "FROM enrollment_table e " + "LEFT JOIN attendance a ON e.enrollment_id = a.enrollment_id" + " AND a.indatetime = (" @@ -203,6 +209,11 @@ public class NULMOfficerActivity { + " a.outby, " + " a.inphoto, " + " a.outphoto " + // + " CASE " + // + " WHEN DATE(a.oddatetime) = CURDATE() THEN 'OD Marked' " + // + " WHEN DATE(a.leavedatetime) = CURDATE() THEN 'Leave Marked' " + // + " ELSE '' " + // + " END AS attendance_status " + " FROM enrollment_table e " + " LEFT JOIN attendance a ON e.enrollment_id = a.enrollment_id" + " AND a.indatetime = (" @@ -237,6 +248,11 @@ public class NULMOfficerActivity { + " a.outby, " + " a.inphoto, " + " a.outphoto " + // + " CASE " + // + " WHEN DATE(a.oddatetime) = CURDATE() THEN 'OD Marked' " + // + " WHEN DATE(a.leavedatetime) = CURDATE() THEN 'Leave Marked' " + // + " ELSE '' " + // + " END AS attendance_status " + " FROM enrollment_table e " + " LEFT JOIN attendance a ON e.enrollment_id = a.enrollment_id" + " AND a.indatetime = (" @@ -592,6 +608,16 @@ public class NULMOfficerActivity { } } else if ("od".equalsIgnoreCase(action)) { // Mark On Duty (OD) even if no check-in + + // String updateSql = "UPDATE attendance " + + // "SET outdatetime = DATE_ADD(indatetime, INTERVAL 8 HOUR) " + + // "WHERE enrollment_id = ? " + + // "AND outdatetime IS NULL " + + // "ORDER BY indatetime DESC " + + // "LIMIT 1"; + + // int rows = jdbcNULMTemplate.update(updateSql, enrollId); + String sqlQuery = "INSERT INTO attendance (oddatetime, odby, enrollment_id, location, appversion, apptype) " + "VALUES (?, ?, ?, ?, ?, ?)"; @@ -609,6 +635,16 @@ public class NULMOfficerActivity { } else if ("leave".equalsIgnoreCase(action)) { // Mark Leave even if no check-in + + // String updateSql = "UPDATE attendance " + + // "SET outdatetime = DATE_ADD(indatetime, INTERVAL 8 HOUR) " + + // "WHERE enrollment_id = ? " + + // "AND outdatetime IS NULL " + + // "ORDER BY indatetime DESC " + + // "LIMIT 1"; + + // int rows = jdbcNULMTemplate.update(updateSql, enrollId); + String sqlQuery = "INSERT INTO attendance (leavedatetime, leaveby, enrollment_id, location, appversion, apptype) " + "VALUES (?, ?, ?, ?, ?, ?)"; diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/controller/APIController.java index 2068d3ec..82b0fcb5 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/controller/APIController.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/controller/APIController.java @@ -13,103 +13,140 @@ import java.util.Map; @RequestMapping("/gccofficialapp/api/roadwar/") @RestController("gccofficialappsroadwar") public class APIController { - @Autowired - private RoadWarAPIService apiService; - - - @GetMapping(value="/road-types") - public List getRoadTypes(){ - return apiService.getRoadTypes(); - } - - @GetMapping(value="/lay-types") - public List getRoadLayTypes(){ - return apiService.getRoadLayTypes(); - } - - /** - * Save Start Street details - */ - @PostMapping("/street/start") - public ResponseEntity> saveStartStreet( - @RequestParam String roadName, - @RequestParam String roadZone, - @RequestParam String roadWard, - @RequestParam String roadId, - @RequestParam String roadType, - @RequestParam String manualZone, - @RequestParam String manualWard, - @RequestParam String manualroadType, - @RequestParam String roadLayType, - @RequestParam(required = false) String lastLayOn, - @RequestParam String roadLength, - @RequestParam String carriagewayWidth, - @RequestParam String walltowallWidth, - @RequestParam String footpath, - @RequestParam String median, - @RequestParam String swd, - @RequestParam String inby, - @RequestParam String latitude, - @RequestParam String longitude, - @RequestParam String streetboard, - @RequestParam(required = false) MultipartFile roadImage - ) { - Map result = apiService.saveStreetDetails( - "START", roadName, roadZone, roadWard, roadId, roadType, - manualZone, manualWard, manualroadType, - roadLayType, lastLayOn, roadLength, carriagewayWidth, - walltowallWidth, footpath, median, swd, inby, latitude, - longitude, streetboard, roadImage, null - ); - return ResponseEntity.ok(result); - } - - @GetMapping(value="/street/startlist") - public List getStartRoadList(@RequestParam String inby){ - return apiService.getStartRoadList(inby); - } + @Autowired + private RoadWarAPIService apiService; - /** - * Save End Street details (linked with Start Street) - */ - @PostMapping("/street/end") - public ResponseEntity> saveEndStreet( - @RequestParam String roadName, - @RequestParam String roadZone, - @RequestParam String roadWard, - @RequestParam String roadId, - @RequestParam String roadType, - @RequestParam String manualZone, - @RequestParam String manualWard, - @RequestParam String manualroadType, - @RequestParam String roadLayType, - @RequestParam(required = false) String lastLayOn, - @RequestParam String roadLength, - @RequestParam String carriagewayWidth, - @RequestParam String walltowallWidth, - @RequestParam String footpath, - @RequestParam String median, - @RequestParam String swd, - @RequestParam String inby, - @RequestParam String latitude, - @RequestParam String longitude, - @RequestParam String streetboard, - @RequestParam(required = false) MultipartFile roadImage, - @RequestParam Integer startId // required for END street - ) { - Map result = apiService.saveStreetDetails( - "END", roadName, roadZone, roadWard, roadId, roadType, - manualZone, manualWard, manualroadType, - roadLayType, lastLayOn, roadLength, carriagewayWidth, - walltowallWidth, footpath, median, swd, inby, latitude, - longitude, streetboard, roadImage, startId - ); - return ResponseEntity.ok(result); - } - - - @GetMapping(value="/getCompletedRoadLists") - public List getCompletedRoadLists(){ - return apiService.getCompletedRoadLists(); - } + @GetMapping(value = "/road-types") + public List getRoadTypes() { + return apiService.getRoadTypes(); + } + + @GetMapping(value = "/lay-types") + public List getRoadLayTypes() { + return apiService.getRoadLayTypes(); + } + + /** + * Save Start Street details + */ + @PostMapping("/street/start") + public ResponseEntity> saveStartStreet( + @RequestParam String roadName, + @RequestParam String roadZone, + @RequestParam String roadWard, + @RequestParam String roadId, + @RequestParam String roadType, + @RequestParam String manualZone, + @RequestParam String manualWard, + @RequestParam String manualroadType, + @RequestParam String roadLayType, + @RequestParam(required = false) String lastLayOn, + @RequestParam String roadLength, + @RequestParam String carriagewayWidth, + @RequestParam String walltowallWidth, + @RequestParam String footpath, + @RequestParam String median, + @RequestParam String swd, + @RequestParam String inby, + @RequestParam String latitude, + @RequestParam String longitude, + @RequestParam String streetboard, + @RequestParam(required = false) MultipartFile roadImage) { + Map result = apiService.saveStreetDetails( + "START", roadName, roadZone, roadWard, roadId, roadType, + manualZone, manualWard, manualroadType, + roadLayType, lastLayOn, roadLength, carriagewayWidth, + walltowallWidth, footpath, median, swd, inby, latitude, + longitude, streetboard, roadImage, null); + return ResponseEntity.ok(result); + } + + @GetMapping(value = "/street/startlist") + public List getStartRoadList(@RequestParam String inby) { + return apiService.getStartRoadList(inby); + } + + /** + * Save End Street details (linked with Start and centre Street) + */ + @PostMapping("/street/end") + public ResponseEntity> saveEndStreet( + @RequestParam String roadName, + @RequestParam String roadZone, + @RequestParam String roadWard, + @RequestParam String roadId, + @RequestParam String roadType, + @RequestParam String manualZone, + @RequestParam String manualWard, + @RequestParam(required = false) String manualroadType, + @RequestParam(required = false) String roadLayType, + @RequestParam(required = false) String lastLayOn, + @RequestParam(required = false) String roadLength, + @RequestParam(required = false) String carriagewayWidth, + @RequestParam(required = false) String walltowallWidth, + @RequestParam(required = false) String footpath, + @RequestParam(required = false) String median, + @RequestParam(required = false) String swd, + @RequestParam String inby, + @RequestParam(required = false) String latitude, + @RequestParam(required = false) String longitude, + @RequestParam(required = false) String streetboard, + @RequestParam(required = false) MultipartFile roadImage, + @RequestParam Integer startId // required for END street + ) { + Map result = apiService.saveStreetDetails( + "END", roadName, roadZone, roadWard, roadId, roadType, + manualZone, manualWard, manualroadType, + roadLayType, lastLayOn, roadLength, carriagewayWidth, + walltowallWidth, footpath, median, swd, inby, latitude, + longitude, streetboard, roadImage, startId); + return ResponseEntity.ok(result); + } + + @GetMapping(value = "/street/centrelist") + public List getCentreRoadList(@RequestParam String inby) { + return apiService.getCentreRoadList(inby); + } + + /** + * Save Centre Street details (linked with Start Street) + */ + @PostMapping("/street/centre") + public ResponseEntity> saveCentreStreet( + @RequestParam String roadName, + @RequestParam String roadZone, + @RequestParam String roadWard, + @RequestParam String roadId, + @RequestParam String roadType, + @RequestParam String manualZone, + @RequestParam String manualWard, + @RequestParam(required = false) String manualroadType, + @RequestParam(required = false) String roadLayType, + @RequestParam(required = false) String lastLayOn, + @RequestParam(required = false) String roadLength, + @RequestParam(required = false) String carriagewayWidth, + @RequestParam(required = false) String walltowallWidth, + @RequestParam(required = false) String footpath, + @RequestParam(required = false) String median, + @RequestParam(required = false) String swd, + @RequestParam String inby, + @RequestParam(required = false) String latitude, + @RequestParam(required = false) String longitude, + @RequestParam(required = false) String streetboard, + @RequestParam(required = false) MultipartFile roadImage, + @RequestParam Integer startId // required for END street + ) { + Map result = apiService.saveStreetDetails( + "CENTRE", roadName, roadZone, roadWard, roadId, roadType, + manualZone, manualWard, manualroadType, + roadLayType, lastLayOn, roadLength, carriagewayWidth, + walltowallWidth, footpath, median, swd, inby, latitude, + longitude, streetboard, roadImage, startId); + return ResponseEntity.ok(result); + } + + @GetMapping(value = "/getCompletedRoadLists") + public List getCompletedRoadLists() { + return apiService.getCompletedRoadLists(); + } } diff --git a/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/service/RoadWarAPIService.java b/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/service/RoadWarAPIService.java index 22398fbb..9485e1c4 100644 --- a/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/service/RoadWarAPIService.java +++ b/src/main/java/in/gov/chennaicorporation/mobileservice/roadwarregister/service/RoadWarAPIService.java @@ -42,7 +42,7 @@ public class RoadWarAPIService { private JdbcTemplate jdbcRoadWar; 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(); @@ -51,13 +51,13 @@ public class RoadWarAPIService { public void setDataSource(@Qualifier("mysqlGccRoadWarSource") DataSource RoadWarDataSource) { this.jdbcRoadWar = new JdbcTemplate(RoadWarDataSource); } - + @Autowired public RoadWarAPIService(Environment environment) { this.environment = environment; - this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + this.fileBaseUrl = environment.getProperty("fileBaseUrl"); } - + public static String generateRandomString() { StringBuilder result = new StringBuilder(STRING_LENGTH); for (int i = 0; i < STRING_LENGTH; i++) { @@ -65,7 +65,7 @@ public class RoadWarAPIService { } return result.toString(); } - + public static String generateRandomFileString(int lenthval) { StringBuilder result = new StringBuilder(lenthval); for (int i = 0; i < lenthval; i++) { @@ -116,9 +116,9 @@ public class RoadWarAPIService { // Datetime string String datetimetxt = DateTimeUtil.getCurrentDateTime(); - - datetimetxt = datetimetxt + "_"+ generateRandomFileString(6); // Attached Random text - + + datetimetxt = datetimetxt + "_" + generateRandomFileString(6); // Attached Random text + // File name String fileName = name + "_" + id + "_" + datetimetxt + "_" + file.getOriginalFilename(); fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename @@ -148,295 +148,362 @@ public class RoadWarAPIService { return "Failed to save file " + file.getOriginalFilename(); } } - - public List> getRoadTypes(){ - String sql = "SELECT `roadtype_id`, `name` FROM `road_type` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`"; - List> result = jdbcRoadWar.queryForList(sql); + + public List> getRoadTypes() { + String sql = "SELECT `roadtype_id`, `name` FROM `road_type` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`"; + List> result = jdbcRoadWar.queryForList(sql); Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Road Type List."); - response.put("data", result); - - return Collections.singletonList(response); - } - - public List> getRoadLayTypes(){ - String sql = "SELECT `lay_type_id`, `name` FROM `road_lay_type` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`"; - List> result = jdbcRoadWar.queryForList(sql); + response.put("status", "Success"); + response.put("message", "Road Type List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getRoadLayTypes() { + String sql = "SELECT `lay_type_id`, `name` FROM `road_lay_type` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`"; + List> result = jdbcRoadWar.queryForList(sql); Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Road Lay Type List."); - response.put("data", result); - - return Collections.singletonList(response); - } - + response.put("status", "Success"); + response.put("message", "Road Lay Type List."); + response.put("data", result); + + return Collections.singletonList(response); + } + @Transactional public List> checkAssetExists(String latitudeStr, String longitudeStr) { double latitude = Double.parseDouble(latitudeStr); - double longitude = Double.parseDouble(longitudeStr); - - String checkSql = "SELECT COUNT(*) FROM road_list list " + - "WHERE (6371008.8 * ACOS(COS(RADIANS(?)) * COS(RADIANS(list.latitude)) * " + - "COS(RADIANS(list.longitude) - RADIANS(?)) + SIN(RADIANS(?)) * SIN(RADIANS(list.latitude)))) < 50"; - - Integer count = jdbcRoadWar.queryForObject( - checkSql, - Integer.class, - latitude, longitude, latitude - ); - - Map response = new HashMap<>(); - if (count != null && count > 0) { - response.put("count", count); - response.put("status", "error"); - response.put("message", "Duplicate: Road already exists."); - } else { - response.put("count", count); - response.put("status", "success"); - response.put("message", "No existing Road found."); - } - return Collections.singletonList(response); + double longitude = Double.parseDouble(longitudeStr); + + String checkSql = "SELECT COUNT(*) FROM road_list list " + + "WHERE (6371008.8 * ACOS(COS(RADIANS(?)) * COS(RADIANS(list.latitude)) * " + + "COS(RADIANS(list.longitude) - RADIANS(?)) + SIN(RADIANS(?)) * SIN(RADIANS(list.latitude)))) < 50"; + + Integer count = jdbcRoadWar.queryForObject( + checkSql, + Integer.class, + latitude, longitude, latitude); + + Map response = new HashMap<>(); + if (count != null && count > 0) { + response.put("count", count); + response.put("status", "error"); + response.put("message", "Duplicate: Road already exists."); + } else { + response.put("count", count); + response.put("status", "success"); + response.put("message", "No existing Road found."); + } + return Collections.singletonList(response); } - - public List> getStartRoadList(String inby){ - /* - String sql = "SELECT *, " - + "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', start_img) AS start_img_url " - + " FROM `start_street_details` WHERE (`isactive`=1 AND `isdelete`=0) AND (`inby`=?) " - + "AND s.strat_id NOT IN ( SELECT e.start_id FROM end_street_details e )"; - */ - String sql ="SELECT " - + " s.*, " - + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', start_img) AS start_img_url " - + "FROM " - + " `start_street_details` s " - + "WHERE " - + " s.`isactive` = 1" - + " AND s.`isdelete` = 0 AND (`inby`=?)" - + " AND s.`strat_id` NOT IN (" - + " SELECT e.`start_id` " - + " FROM `end_street_details` e" - + " )"; - List> result = jdbcRoadWar.queryForList(sql,inby); + + public List> getStartRoadList(String inby) { + /* + * String sql = "SELECT *, " + * + "CONCAT('" + fileBaseUrl + + * "/gccofficialapp/files', start_img) AS start_img_url " + * + + * " FROM `start_street_details` WHERE (`isactive`=1 AND `isdelete`=0) AND (`inby`=?) " + * + "AND s.strat_id NOT IN ( SELECT e.start_id FROM end_street_details e )"; + */ + String sql = "SELECT " + + " s.*, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', start_img) AS start_img_url " + + "FROM " + + " `start_street_details` s " + + "WHERE " + + " s.`isactive` = 1" + + " AND s.`isdelete` = 0 AND (`inby`=?)" + + " AND s.`road_id` NOT IN (" + + " SELECT c.`road_id` " + + " FROM `centre_street_details` c" + + " )"; + List> result = jdbcRoadWar.queryForList(sql, inby); Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Road Start List."); - response.put("data", result); - - return Collections.singletonList(response); - } - + response.put("status", "Success"); + response.put("message", "Road Start List."); + response.put("data", result); + + return Collections.singletonList(response); + } + @Transactional public Map saveStreetDetails( - String type, // "START" or "END" - String roadName, - String roadZone, - String roadWard, - String roadId, - String roadType, - String manualZone, - String manualWard, - String manualroadType, - String roadLayType, - String lastLayOn, // yyyy-MM-dd or yyyy-MM format - String roadLength, - String carriagewayWidth, - String walltowallWidth, - String footpath, - String median, - String swd, - String inby, - String latitude, - String longitude, - String streetboard, - MultipartFile roadImage, - Integer startId // only for END street (foreign key to start_street_details) + String type, // "START" or "END" + String roadName, + String roadZone, + String roadWard, + String roadId, + String roadType, + String manualZone, + String manualWard, + String manualroadType, + String roadLayType, + String lastLayOn, // yyyy-MM-dd or yyyy-MM format + String roadLength, + String carriagewayWidth, + String walltowallWidth, + String footpath, + String median, + String swd, + String inby, + String latitude, + String longitude, + String streetboard, + MultipartFile roadImage, + Integer startId // only for END street (foreign key to start_street_details) ) { - Map response = new HashMap<>(); - - // ✅ Handle file upload safely - final String uploadedImg = (roadImage != null && !roadImage.isEmpty()) - ? fileUpload("RoadRegister", type.toLowerCase(), roadImage) - : null; - /* - String uploadedImg = null; - if (roadImage != null && !roadImage.isEmpty()) { - uploadedImg = fileUpload("RoadRegister", type.toLowerCase(), roadImage); - } - */ - // ✅ Choose table & generated key column - String sql; - String[] generatedKey = new String[1]; - - if ("START".equalsIgnoreCase(type)) { - sql = "INSERT INTO start_street_details " + - "(road_name, road_zone, road_ward, road_id, road_type, " + - "manual_zone, manual_ward, manual_roadType, road_lay_type, last_lay_on, " + - "road_length, carriageway_width, walltowall_width, footpath, median, " + - "swd, inby, start_latitude, start_longitude, streetboard, start_img) " + - "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - generatedKey[0] = "strat_id"; - } else { - sql = "INSERT INTO end_street_details " + - "(road_name, road_zone, road_ward, road_id, road_type, " + - "manual_zone, manual_ward, manual_roadType, road_lay_type, last_lay_on, " + - "road_length, carriageway_width, walltowall_width, footpath, median, " + - "swd, inby, start_latitude, start_longitude, streetboard, start_id, end_img) " + - "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - generatedKey[0] = "end_id"; - } - - KeyHolder keyHolder = new GeneratedKeyHolder(); - - int affected = jdbcRoadWar.update(connection -> { - PreparedStatement ps = connection.prepareStatement(sql, generatedKey); - int i = 1; - ps.setString(i++, roadName); - ps.setString(i++, roadZone); - ps.setString(i++, roadWard); - ps.setString(i++, roadId); - ps.setString(i++, roadType); - - // ✅ Manual fields - ps.setString(i++, manualZone); - ps.setString(i++, manualWard); - ps.setString(i++, manualroadType); - ps.setString(i++, roadLayType); - ps.setString(i++, lastLayOn); - - // ✅ Road dimensions - ps.setString(i++, roadLength); - ps.setString(i++, carriagewayWidth); - ps.setString(i++, walltowallWidth); - ps.setString(i++, footpath); - ps.setString(i++, median); - ps.setString(i++, swd); - ps.setString(i++, inby); - - // ✅ Location + Board - ps.setString(i++, latitude); - ps.setString(i++, longitude); - ps.setString(i++, streetboard); - - // ✅ Image & FK handling - if ("START".equalsIgnoreCase(type)) { - ps.setString(i++, uploadedImg); - } else { - ps.setObject(i++, startId); // foreign key - ps.setString(i++, uploadedImg); - } - return ps; - }, keyHolder); - - if (affected > 0) { - response.put("status", "success"); - response.put("insertId", keyHolder.getKey().intValue()); - response.put("message", type + " Street details saved successfully"); - } else { - response.put("status", "error"); - response.put("message", type + " Street details insert failed"); - } - - return response; + Map response = new HashMap<>(); + + // ✅ Handle file upload safely + final String uploadedImg = (roadImage != null && !roadImage.isEmpty()) + ? fileUpload("RoadRegister", type.toLowerCase(), roadImage) + : null; + /* + * String uploadedImg = null; + * if (roadImage != null && !roadImage.isEmpty()) { + * uploadedImg = fileUpload("RoadRegister", type.toLowerCase(), roadImage); + * } + */ + // ✅ Choose table & generated key column + String sql; + String[] generatedKey = new String[1]; + + String existsql = "select count(*) from start_street_details where road_id = ? and isactive=1 and isdelete=0"; + int exists = jdbcRoadWar.queryForObject(existsql, Integer.class, roadId); + if (exists > 0) { + response.put("status", "error"); + response.put("message", "Road already exists."); + return response; + } + + if ("START".equalsIgnoreCase(type)) { + + sql = "INSERT INTO start_street_details " + + "(road_name, road_zone, road_ward, road_id, road_type, " + + "manual_zone, manual_ward, inby, start_latitude, start_longitude, start_id, start_img) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + generatedKey[0] = "start_id"; + } else if ("CENTRE".equalsIgnoreCase(type)) { + sql = "INSERT INTO centre_street_details " + + "(road_name, road_zone, road_ward, road_id, road_type, " + + "manual_zone, manual_ward, inby, start_latitude, start_longitude, start_id, centre_img) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + generatedKey[0] = "centre_id"; + } + + else { + sql = "INSERT INTO end_street_details " + + "(road_name, road_zone, road_ward, road_id, road_type, " + + "manual_zone, manual_ward, inby, start_latitude, start_longitude, start_id, end_img) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + generatedKey[0] = "end_id"; + } + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + int affected = jdbcRoadWar.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, generatedKey); + int i = 1; + + // if ("CENTRE".equalsIgnoreCase(type) || "END".equalsIgnoreCase(type)) { + + ps.setString(i++, roadName); + ps.setString(i++, roadZone); + ps.setString(i++, roadWard); + ps.setString(i++, roadId); + ps.setString(i++, roadType); + ps.setString(i++, manualZone); + ps.setString(i++, manualWard); + ps.setString(i++, inby); + ps.setString(i++, latitude); + ps.setString(i++, longitude); + ps.setObject(i++, startId); // foreign key + ps.setString(i++, uploadedImg); + + /* + * } else { + * ps.setString(i++, roadName); + * ps.setString(i++, roadZone); + * ps.setString(i++, roadWard); + * ps.setString(i++, roadId); + * ps.setString(i++, roadType); + * + * // ✅ Manual fields + * ps.setString(i++, manualZone); + * ps.setString(i++, manualWard); + * ps.setString(i++, manualroadType); + * ps.setString(i++, roadLayType); + * ps.setString(i++, lastLayOn); + * + * // ✅ Road dimensions + * ps.setString(i++, roadLength); + * ps.setString(i++, carriagewayWidth); + * ps.setString(i++, walltowallWidth); + * ps.setString(i++, footpath); + * ps.setString(i++, median); + * ps.setString(i++, swd); + * ps.setString(i++, inby); + * + * // ✅ Location + Board + * ps.setString(i++, latitude); + * ps.setString(i++, longitude); + * ps.setString(i++, streetboard); + * } + * + * // ✅ Image & FK handling + * if ("START".equalsIgnoreCase(type)) { + * ps.setString(i++, uploadedImg); + * } + */ + return ps; + }, keyHolder); + + if (affected > 0) { + response.put("status", "success"); + response.put("insertId", keyHolder.getKey().intValue()); + response.put("message", type + " Street details saved successfully"); + } else { + response.put("status", "error"); + response.put("message", type + " Street details insert failed"); + } + + return response; } - + public List> getCompletedRoadLists() { - String sql = "SELECT " - + " s.strat_id AS UnicID, " - + " s.road_name AS StreetName, " - + " JSON_OBJECT(" - + " 'strat_id', s.strat_id, " - + " 'road_name', s.road_name, " - + " 'road_zone', s.road_zone, " - + " 'road_ward', s.road_ward, " - + " 'road_id', s.road_id, " - + " 'road_type', s.road_type, " - + " 'manual_zone', s.manual_zone, " - + " 'manual_ward', s.manual_ward, " - + " 'manual_roadType', s.manual_roadType, " - + " 'road_lay_type', s.road_lay_type, " - + " 'last_lay_on', s.last_lay_on, " - + " 'road_length', s.road_length, " - + " 'carriageway_width', s.carriageway_width, " - + " 'walltowall_width', s.walltowall_width, " - + " 'footpath', s.footpath, " - + " 'median', s.median, " - + " 'swd', s.swd, " - + " 'inby', s.inby, " - + " 'indate', s.indate, " - + " 'start_latitude', s.start_latitude, " - + " 'start_longitude', s.start_longitude, " - + " 'isactive', s.isactive, " - + " 'isdelete', s.isdelete, " - + " 'streetboard', s.streetboard, " - + " 'start_img', s.start_img, " - + " 'start_img_url', CONCAT('" + fileBaseUrl + "/gccofficialapp/files', IFNULL(s.start_img, '/nostreetboard.png'))" - + " ) AS `start`, " - + " JSON_OBJECT(" - + " 'end_id', e.end_id, " - + " 'road_name', e.road_name, " - + " 'road_zone', e.road_zone, " - + " 'road_ward', e.road_ward, " - + " 'road_id', e.road_id, " - + " 'road_type', e.road_type, " - + " 'manual_zone', e.manual_zone, " - + " 'manual_ward', e.manual_ward, " - + " 'manual_roadType', e.manual_roadType, " - + " 'road_lay_type', e.road_lay_type, " - + " 'last_lay_on', e.last_lay_on, " - + " 'road_length', e.road_length, " - + " 'carriageway_width', e.carriageway_width, " - + " 'walltowall_width', e.walltowall_width, " - + " 'footpath', e.footpath, " - + " 'median', e.median, " - + " 'swd', e.swd, " - + " 'inby', e.inby, " - + " 'indate', e.indate, " - + " 'start_latitude', e.start_latitude, " - + " 'start_longitude', e.start_longitude, " - + " 'isactive', e.isactive, " - + " 'isdelete', e.isdelete, " - + " 'streetboard', e.streetboard, " - + " 'end_img', e.end_img, " - + " 'end_img_url', CONCAT('" + fileBaseUrl + "/gccofficialapp/files', IFNULL(e.end_img, '/nostreetboard.png'))" - + " ) AS `end` " - + "FROM start_street_details s " - + "INNER JOIN end_street_details e " - + " ON e.start_id = s.strat_id " - + "WHERE s.isactive = 1 " - + " AND s.isdelete = 0 " - + " AND e.isactive = 1 " - + " AND e.isdelete = 0"; - - List> rawResult = jdbcRoadWar.queryForList(sql); - - ObjectMapper mapper = new ObjectMapper(); - List> formattedResult = new ArrayList<>(); - - for (Map row : rawResult) { - Map formattedRow = new HashMap<>(); - formattedRow.put("UnicID", row.get("UnicID")); - formattedRow.put("StreetName", row.get("StreetName")); - - // Convert JSON strings to proper objects - try { - Map startObj = mapper.readValue(row.get("start").toString(), new TypeReference>() {}); - Map endObj = mapper.readValue(row.get("end").toString(), new TypeReference>() {}); - formattedRow.put("start", startObj); - formattedRow.put("end", endObj); - } catch (Exception ex) { - ex.printStackTrace(); - } - - formattedResult.add(formattedRow); - } - - Map response = new HashMap<>(); - response.put("status", "Success"); - response.put("message", "Completed road list."); - response.put("data", formattedResult); - - return Collections.singletonList(response); + String sql = "SELECT " + + " s.start_id AS UnicID, " + + " s.road_name AS StreetName, " + + " JSON_OBJECT(" + + " 'start_id', s.start_id, " + + " 'road_name', s.road_name, " + + " 'road_zone', s.road_zone, " + + " 'road_ward', s.road_ward, " + + " 'road_id', s.road_id, " + + " 'road_type', s.road_type, " + + " 'manual_zone', s.manual_zone, " + + " 'manual_ward', s.manual_ward, " + + " 'manual_roadType', s.manual_roadType, " + + " 'road_lay_type', s.road_lay_type, " + + " 'last_lay_on', s.last_lay_on, " + + " 'road_length', s.road_length, " + + " 'carriageway_width', s.carriageway_width, " + + " 'walltowall_width', s.walltowall_width, " + + " 'footpath', s.footpath, " + + " 'median', s.median, " + + " 'swd', s.swd, " + + " 'inby', s.inby, " + + " 'indate', s.indate, " + + " 'start_latitude', s.start_latitude, " + + " 'start_longitude', s.start_longitude, " + + " 'isactive', s.isactive, " + + " 'isdelete', s.isdelete, " + + " 'streetboard', s.streetboard, " + + " 'start_img', s.start_img, " + + " 'start_img_url', CONCAT('" + fileBaseUrl + + "/gccofficialapp/files', IFNULL(s.start_img, '/nostreetboard.png'))" + + " ) AS `start`, " + + " JSON_OBJECT(" + + " 'end_id', e.end_id, " + + " 'road_name', e.road_name, " + + " 'road_zone', e.road_zone, " + + " 'road_ward', e.road_ward, " + + " 'road_id', e.road_id, " + + " 'road_type', e.road_type, " + + " 'manual_zone', e.manual_zone, " + + " 'manual_ward', e.manual_ward, " + + " 'manual_roadType', e.manual_roadType, " + + " 'road_lay_type', e.road_lay_type, " + + " 'last_lay_on', e.last_lay_on, " + + " 'road_length', e.road_length, " + + " 'carriageway_width', e.carriageway_width, " + + " 'walltowall_width', e.walltowall_width, " + + " 'footpath', e.footpath, " + + " 'median', e.median, " + + " 'swd', e.swd, " + + " 'inby', e.inby, " + + " 'indate', e.indate, " + + " 'start_latitude', e.start_latitude, " + + " 'start_longitude', e.start_longitude, " + + " 'isactive', e.isactive, " + + " 'isdelete', e.isdelete, " + + " 'streetboard', e.streetboard, " + + " 'end_img', e.end_img, " + + " 'end_img_url', CONCAT('" + fileBaseUrl + + "/gccofficialapp/files', IFNULL(e.end_img, '/nostreetboard.png'))" + + " ) AS `end` " + + "FROM start_street_details s " + + "INNER JOIN end_street_details e " + + " ON e.start_id = s.start_id " + + "WHERE s.isactive = 1 " + + " AND s.isdelete = 0 " + + " AND e.isactive = 1 " + + " AND e.isdelete = 0"; + + List> rawResult = jdbcRoadWar.queryForList(sql); + + ObjectMapper mapper = new ObjectMapper(); + List> formattedResult = new ArrayList<>(); + + for (Map row : rawResult) { + Map formattedRow = new HashMap<>(); + formattedRow.put("UnicID", row.get("UnicID")); + formattedRow.put("StreetName", row.get("StreetName")); + + // Convert JSON strings to proper objects + try { + Map startObj = mapper.readValue(row.get("start").toString(), + new TypeReference>() { + }); + Map endObj = mapper.readValue(row.get("end").toString(), + new TypeReference>() { + }); + formattedRow.put("start", startObj); + formattedRow.put("end", endObj); + } catch (Exception ex) { + ex.printStackTrace(); + } + + formattedResult.add(formattedRow); + } + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Completed road list."); + response.put("data", formattedResult); + + return Collections.singletonList(response); + } + + public List> getCentreRoadList(String inby) { + /* + * String sql = "SELECT *, " + * + "CONCAT('" + fileBaseUrl + + * "/gccofficialapp/files', start_img) AS start_img_url " + * + + * " FROM `start_street_details` WHERE (`isactive`=1 AND `isdelete`=0) AND (`inby`=?) " + * + "AND s.strat_id NOT IN ( SELECT e.start_id FROM end_street_details e )"; + */ + String sql = "SELECT " + + " s.*, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', centre_img) AS centre_img_url " + + "FROM " + + " `centre_street_details` s " + + "WHERE " + + " s.`isactive` = 1" + + " AND s.`isdelete` = 0 AND (`inby`=?)" + + " AND s.`road_id` NOT IN (" + + " SELECT e.`start_id` " + + " FROM `end_street_details` e" + + " )"; + List> result = jdbcRoadWar.queryForList(sql, inby); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Road Centre List."); + response.put("data", result); + + return Collections.singletonList(response); } } diff --git a/src/main/resources/.DS_Store b/src/main/resources/.DS_Store index 7e1a9bcc..c8f6dfd1 100644 Binary files a/src/main/resources/.DS_Store and b/src/main/resources/.DS_Store differ diff --git a/src/main/resources/application-local.properties b/src/main/resources/application-local.properties index e6efdd29..ee826e74 100644 --- a/src/main/resources/application-local.properties +++ b/src/main/resources/application-local.properties @@ -1,3 +1,3 @@ assets.base-url=/assets/ -fileBaseUrl=http://localhost:8064 +fileBaseUrl=http://localhost:8067 \ No newline at end of file diff --git a/src/main/resources/application-production.properties b/src/main/resources/application-production.properties index 6146ec0c..029057f3 100644 --- a/src/main/resources/application-production.properties +++ b/src/main/resources/application-production.properties @@ -1,3 +1,3 @@ -assets.base-url=/gcc/assets/ +assets.base-url=/gccofficialapp/assets/ fileBaseUrl=https://gccservices.in \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 2f562e69..9089f43d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,124 +1,90 @@ #spring.profiles.active=local spring.profiles.active=production -#For Server production -#assets.base-url=/gcc/assets/ -#For local test -#assets.base-url=/assets/ -# Spring properties -spring.application.name=gcc-portal +spring.application.name=Mobile Service -# Discovery Server Access -#eureka.client.serviceUrl.defaultZone=http://localhost:8061/eureka/ +# Enable live reload (default is true) +spring.devtools.livereload.enabled=true -spring.datasource.hikari.connection-timeout=30000 - -spring.jackson.time-zone=Asia/Kolkata - -# Maximum file size -spring.servlet.multipart.max-file-size=20MB - -# Maximum request size (including all files) -spring.servlet.multipart.max-request-size=20MB +# Enable restart (default is true) +spring.devtools.restart.enabled=true # HTTP Server -server.port = 8064 -#server.servlet.context-path=/gccoffice -server.error.include-stacktrace= on_param -# Hibernate logging -#logging.level.org.hibernate.SQL=DEBUG -#logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE - -# Enable CORS globally for all endpoints -spring.webmvc.cors.enabled=true - -# Comma-separated list of allowed origins -spring.webmvc.cors.allowed-origins=http://gccservices.chennaicorporation.gov.in:8064,http://chennaicorporation.gov.in:8064,http://117.232.67.158:8064,http://localhost:8064 - -# Comma-separated list of allowed HTTP methods -spring.webmvc.cors.allowed-methods=GET,POST,PUT,DELETE - -# Whether to include credentials such as cookies in CORS requests -spring.webmvc.cors.allow-credentials=true - -# Maximum age (in seconds) of the CORS response cache -spring.webmvc.cors.max-age=3600 - -server.servlet.session.tracking-modes=COOKIE - -#server.servlet.session.cookie.domain=chennaicorporation.gov.in - -#logging.level.root=DEBUG - -file.upload.directory=${user.dir}/gccoffice_uploads/ - -file.upload.directory.mobile=${user.dir}/gcc_mobile_service_uploads/ +server.port = 8067 -server.address=0.0.0.0 - -server.servlet.session.timeout=-1 -server.servlet.session.cookie.name= GCCONEPORTALSESSION -server.servlet.session.cookie.max-age=-1 -server.servlet.session.cookie.http-only=true -server.servlet.session.cookie.secure=true - -#server.servlet.session.timeout:5m -#server.servlet.session.cookie.name: MYSESSIONID -#server.servlet.session.cookie.max-age: 10m - -#///////// For Mayor Petition ////////// -mp_ackno_prefix=MP -mp_ackno = 10000000 -mp_foldername = m_petition -mp_action_Foldername = m_action_file - -#///////// For Councillor Petition ////////// -cp_ackno_prefix=CP -cp_ackno = 10000000 -cp_foldername = c_petition -cp_action_Foldername = c_action_file +server.error.include-stacktrace= on_param -#///////// For Councillor Petition ////////// -com_ackno_prefix=COM -com_ackno = 10000000 -com_foldername = com_petition -com_action_Foldername = com_action_file +# Hibernate logging +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE -#///////// For Circular Petition ////////// -cir_ackno_prefix=CP -cir_ackno = 10000000 -cir_foldername = circular +spring.jackson.time-zone=Asia/Kolkata -#///////// For Zero Hours Petition ////////// -zh_ackno_prefix=ZH -zh_ackno = 10000000 -zh_foldername = zh_petition -zh_action_Foldername = zh_action_file +# Maximum file size +spring.servlet.multipart.max-file-size=20MB -#//////// NULM Staff ///////////// +# Maximum request size (including all files) +spring.servlet.multipart.max-request-size=120MB + +spring.mvc.favicon.enabled=false + +file.upload.directory=${user.dir}/gcc_mobile_service_uploads/ +file.upload.directory.web=${user.dir}/gccoffice_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/ +hoardings_foldername = hoardings_activity/ +toilets_foldername = toilets_activity/ +c_d_waste_foldername = c_d_waste_activity/ +mosquito_foldername = mosquito_activity/ +works_task_foldername = works_activity/ +street_vendor_foldername=street_vendor_files/ +gcceducation_foldername=education_schools_files/ +busshelter_foldername=bus_shelter_files/ +domestic_waste_foldername=domestic_waste_images/ +private_toilets_foldername=private_toilets_activity/ +pothole_foldername=pothole_images/ +roadcut_foldername=roadcut_activity/ +construction_guidelines_foldername=construction_guidelines_images/ +speedbrake_foldername=speedbrake_images/ +busshelter_renovation_foldername=bus_shelter_renovation_files/ +view_cutter_foldername = view_cutter_files/ +buildingdemolition_foldername = building_demolition_files/ +roadwar_foldername = roadwar_register_files/ +manhole_foldername = manhole_activity/ +disposalpoint_foldername=disposalpoint_activity/ +StreetCleaning_foldername=streetcleaning_activity/ +pump_foldername=pump_activity/ +vehicle_foldername=special_vehicle_activity/ +scp_foldername=scp_activity/ +sluicepoint_foldername=sluicepoint_activity/ +culvert_foldername=railway_culvert_activity/ +fooddistribution_foldername = food_distribution_file/ +flagpole_foldername=flagpole_images/ +healthcamp_folder=healthcamp_images/ +homeless_foldername=homeless_survey/ +abandonedvehicle_foldername=abandoned_vehicle/ +greencommittee_foldername=greencommittee/ +thooimaimission_foldername=thooimai_mission/ +illegalDebrisVehicle_foldername=illegal_debris_vehicle/ nulm_foldername = nulm_ordercopy +parksstaffverification_foldername=parks_staff_verification_images/ +ie_complaint_foldername = ie_complaint_images/ +gcc_cattlesurvey_foldername=gcc_cattlesurvey_images/ +# for election polling person updation images saving folder +polling_person_images_foldername=polling_person_updation_request_images/ +tenement_image_foldername = tenement_images/ +homelesssurvey_document_foldername = homeless_survey_documents/ +ragpickersurvey_document_foldername = ragpicker_survey_documents/ +nightshelterinspection_document_foldername = night_shelter_inspection_documents/ + +roadwarweb_foldername = road_war_web_files/ -#/////////// For 1913 campaign //////////// -campaign.foldername = campaign_uploads - -#/////////// For SOS //////////// -sos_activity_foldername= sos_rescue_activity_images - -#/////////// For Works //////////// -gcc_works = gcc_works_files - -#/////////// For Ward Sabha //////////// -minutes_files = gcc_minutes_files_uploads - -#/////////// For Vtrack (jtrack) -> WhatsApp Msg //////////// -vtrack_foldername = gcc_vtrack_uploads - -education.foldername = school_aadhar_uploads - -street_vendor_foldername=street_vendor_files - -green_committee_foldername=green_committee_files - -socialmedia_1913_regcomp_foldername=socialmedia_1913_regcompfiles - -bulk_waste_foldername=bulk_waste_files \ No newline at end of file diff --git a/src/main/resources/static/.DS_Store b/src/main/resources/static/.DS_Store index 23468030..b0a128b5 100644 Binary files a/src/main/resources/static/.DS_Store and b/src/main/resources/static/.DS_Store differ diff --git a/src/main/resources/static/assets/.DS_Store b/src/main/resources/static/assets/.DS_Store index 6bafd534..2f8f17d3 100644 Binary files a/src/main/resources/static/assets/.DS_Store and b/src/main/resources/static/assets/.DS_Store differ diff --git a/src/main/resources/templates/.DS_Store b/src/main/resources/templates/.DS_Store index d1b6c938..a163f95c 100644 Binary files a/src/main/resources/templates/.DS_Store and b/src/main/resources/templates/.DS_Store differ diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html index 1855e034..695d407d 100644 --- a/src/main/resources/templates/error.html +++ b/src/main/resources/templates/error.html @@ -1,57 +1,172 @@ - - - - - - - -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    - Greater Chennai Corporation -
    -

    Greater Chennai Corporation

    - -
    -
    -

    - 500 Error -

    -

    - Internal Server Error -

    -

    - The server encountered an internal error or misconfiguration and was unable to complete your request -

    - - Back - -
    -
    - -
    -
    -
    + + + + + + + + + GCC Feedback + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + +
    + +
    +
    +
    +
    +

    The Greater Chennai Corporation

    +

    பெருநகர சென்னை மாநகராட்சி

    +
    +

    GCC Official App

    +
    +
    +
    + + +
    +
    + +
    +
    - - - - - +
    +
    + + + + +
    +
    +
    +
    +
    + Error +
    +
    +
    Invalid Url
    +
    +
    +
    +
    +
    + +
    + +
    + + + + + + +
    + + + + + + \ No newline at end of file