diff --git a/.DS_Store b/.DS_Store index 5f53e9a..7c63999 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/bin/target/gccoffice-0.0.1.jar b/bin/target/gccoffice-0.0.1.jar deleted file mode 100644 index 3069bc4..0000000 Binary files a/bin/target/gccoffice-0.0.1.jar and /dev/null differ diff --git a/gccoffice_uploads/.DS_Store b/gccoffice_uploads/.DS_Store index d980238..abb0984 100644 Binary files a/gccoffice_uploads/.DS_Store and b/gccoffice_uploads/.DS_Store differ diff --git a/gccoffice_uploads/app_uploads/.DS_Store b/gccoffice_uploads/app_uploads/.DS_Store index d81bc8f..f60c07e 100644 Binary files a/gccoffice_uploads/app_uploads/.DS_Store and b/gccoffice_uploads/app_uploads/.DS_Store differ diff --git a/gccoffice_uploads/com_petition/.DS_Store b/gccoffice_uploads/com_petition/.DS_Store index 58520db..1af56a4 100644 Binary files a/gccoffice_uploads/com_petition/.DS_Store and b/gccoffice_uploads/com_petition/.DS_Store differ diff --git a/gccoffice_uploads/gcc_minutes_files_uploads/.DS_Store b/gccoffice_uploads/gcc_minutes_files_uploads/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/gccoffice_uploads/gcc_minutes_files_uploads/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files/.DS_Store b/gccoffice_uploads/gcc_works_files/.DS_Store new file mode 100644 index 0000000..dbeae8e Binary files /dev/null and b/gccoffice_uploads/gcc_works_files/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files/2025/.DS_Store b/gccoffice_uploads/gcc_works_files/2025/.DS_Store new file mode 100644 index 0000000..fb8a620 Binary files /dev/null and b/gccoffice_uploads/gcc_works_files/2025/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files/works/.DS_Store b/gccoffice_uploads/gcc_works_files/works/.DS_Store new file mode 100644 index 0000000..435d569 Binary files /dev/null and b/gccoffice_uploads/gcc_works_files/works/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files/works/erp/.DS_Store b/gccoffice_uploads/gcc_works_files/works/erp/.DS_Store new file mode 100644 index 0000000..fc6ce5a Binary files /dev/null and b/gccoffice_uploads/gcc_works_files/works/erp/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files/works/nonerp/.DS_Store b/gccoffice_uploads/gcc_works_files/works/nonerp/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/gccoffice_uploads/gcc_works_files/works/nonerp/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files/works/projectStatus/.DS_Store b/gccoffice_uploads/gcc_works_files/works/projectStatus/.DS_Store new file mode 100644 index 0000000..581457a Binary files /dev/null and b/gccoffice_uploads/gcc_works_files/works/projectStatus/.DS_Store differ diff --git a/gccoffice_uploads/gcc_works_files2025/.DS_Store b/gccoffice_uploads/gcc_works_files2025/.DS_Store new file mode 100644 index 0000000..25886ff Binary files /dev/null and b/gccoffice_uploads/gcc_works_files2025/.DS_Store differ diff --git a/gccoffice_uploads/m_petition/.DS_Store b/gccoffice_uploads/m_petition/.DS_Store index 8e55c9e..cd760e3 100644 Binary files a/gccoffice_uploads/m_petition/.DS_Store and b/gccoffice_uploads/m_petition/.DS_Store differ diff --git a/gccoffice_uploads/m_petition/m_action_file/.DS_Store b/gccoffice_uploads/m_petition/m_action_file/.DS_Store deleted file mode 100644 index ed0dc14..0000000 Binary files a/gccoffice_uploads/m_petition/m_action_file/.DS_Store and /dev/null differ diff --git a/gccoffice_uploads/zh_petition/.DS_Store b/gccoffice_uploads/zh_petition/.DS_Store index f4d1ecc..ec1dd92 100644 Binary files a/gccoffice_uploads/zh_petition/.DS_Store and b/gccoffice_uploads/zh_petition/.DS_Store differ diff --git a/pom.xml b/pom.xml index 56e4b6a..4cdee00 100644 --- a/pom.xml +++ b/pom.xml @@ -101,20 +101,20 @@ spring-security-test test - --> - + --> org.apache.poi poi-ooxml 5.2.2 - + --> in.gov.chennaicorporation Community-Hall-Booking 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 index 9c06f6b..fd39086 100644 --- 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 @@ -535,44 +535,52 @@ public class Petition { } @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` " - + " FROM " - + " `petition` p,`petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " 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 - } + 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) 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 index 840d834..313a6cb 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentAssignAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentAssignAPIController.java @@ -43,11 +43,11 @@ public class AgentAssignAPIController return campaignmaster.getcampaignbycategory(id); } - @GetMapping("/getcampaignbyid") - public List> getcampaignbyid(@RequestParam int id) - { - return campaignmaster.getcampaignbyid(id); - } +// @GetMapping("/getcampaignbyid") +// public List> getcampaignbyid(@RequestParam int id) +// { +// return campaignmaster.getcampaignbyid(id); +// } @GetMapping("/getagentsfortask") public List> getagentsfortask(@RequestParam int id) @@ -57,7 +57,7 @@ public class AgentAssignAPIController @PostMapping("/addagentsfortask") public ResponseEntity>> addagentsfortask(@RequestBody List> requestList) { - System.out.println("Received POST request with data: " + requestList); + //System.out.println("Received POST request with data: " + requestList); List> insertedAgents = new ArrayList<>(); // To store successfully inserted agents @@ -104,4 +104,9 @@ public class AgentAssignAPIController { 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 index 61d8dda..1f0a735 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentsAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentsAPIController.java @@ -69,27 +69,7 @@ public class AgentsAPIController { return agentsService.getPendingDataByIds(ids); } - @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 = (int) callData.get("data_id"); - int agent_id=(int) callData.get("agent_id"); - int campaign_id=(int) callData.get("campaign_id"); - - // 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); - - agentsService.saveInLogsTable(campaign_id, agent_id, data_id,call_status,remarks); - - return ResponseEntity.ok("Data Inserted successfully."); - } + // @PostMapping("/updatecall") // public ResponseEntity updatecall(@RequestBody Map callData) @@ -177,5 +157,164 @@ public class AgentsAPIController { 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/CampaignAPIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java index 5aaa949..61d0cf6 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java @@ -1,10 +1,14 @@ package in.gov.chennaicorporation.gccoffice.callcenter.controller; import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; + 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; @@ -13,24 +17,32 @@ 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.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.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") @@ -39,6 +51,15 @@ 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; @@ -54,86 +75,63 @@ public class CampaignAPIController { // Endpoint to get campaign details by ID - @GetMapping("/getCampaignDetailsbyId") - public Map getCampaignDetailsById(@RequestParam("campaign_id") Long campaignId) { + @GetMapping("/getCampaignDetailsById") + public @ResponseBody List> getCampaignDetailsById(@RequestParam("campaign_id") Long campaignId) { return campaignService.getCampaignDetailsById(campaignId); } + + + @PostMapping("/updateCampaign") + public ResponseEntity updateCampaign( + @RequestBody Map requestData) { - @PostMapping("/updateCampaign") - public ResponseEntity updateCampaign(@RequestParam Long campaign_id, - @RequestParam String campaign_name, - @RequestParam String start_date, - @RequestParam String end_date, - @RequestParam Integer no_of_agents, - @RequestParam Integer calls_per_agent, - @RequestParam String description) { - if (campaign_id == null) { + 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 { - campaignService.updateCampaign(campaign_id, campaign_name, start_date, end_date, no_of_agents, calls_per_agent, description); - return ResponseEntity.ok("Campaign updated successfully."); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error updating campaign."); - } - } - - - @PostMapping("/save") - public Map saveCampaignDetails( - @RequestParam("name") String campaignName, - @RequestParam("category") String categoryId, - @RequestParam("eventstartdate") String startDate, - @RequestParam("eventenddate") String endDate, - @RequestParam("no_of_agent") int noOfAgents, - @RequestParam("no_of_calls") int callsPerAgent, - @RequestParam("description") String description, - @RequestParam("file") MultipartFile file) { - - // Creating a Map to store the form data with DB field names - Map campaignDetails = new HashMap<>(); - campaignDetails.put("campaign_name", campaignName); - campaignDetails.put("category_id", categoryId); - campaignDetails.put("start_date", startDate); - campaignDetails.put("end_date", endDate); - campaignDetails.put("no_of_agents", noOfAgents); - campaignDetails.put("calls_per_agent", callsPerAgent); - campaignDetails.put("description", description); try { - // Handle file upload - String fileUrl = saveFile(file); - campaignDetails.put("excel_url", fileUrl); + // Update campaign details + campaignService.updateCampaign(campaign_id, end_date); - // Read data from the uploaded Excel file - List> excelData = readExcelData(file.getInputStream()); - - // Log the campaign details and Excel data to the console - System.out.println("Campaign Details: " + campaignDetails); // Print campaign details - System.out.println("Excel Data: " + excelData); // Print Excel data + // 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"); - // Optionally, you can process the excelData here or save it to the database + if (category != null && question != null && answerType != null) { + campaignService.saveQuestionsAndAnswers( + category, + String.valueOf(campaign_id), // Corrected data type + question, + answerType, + answers + ); + } + } - // Save campaign details - campaignService.saveCampaignDetails(campaignDetails); + return ResponseEntity.ok("Campaign updated successfully."); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Error updating campaign: " + e.getMessage()); + } + } - // Returning success response - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("message", "Campaign details saved successfully"); - response.put("category_id", categoryId); // Include the category_id in the response - return response; - } catch (IOException e) { - e.printStackTrace(); - Map response = new HashMap<>(); - response.put("status", "error"); - response.put("message", "Failed to save campaign details"); - - return response; - } + + //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 { @@ -158,17 +156,32 @@ public class CampaignAPIController { return filePath.toAbsolutePath().toString(); } - - //Read excel data method - private List> readExcelData(InputStream inputStream) throws IOException { + //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); // Get the first sheet + 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 = ""; @@ -180,7 +193,12 @@ public class CampaignAPIController { if (DateUtil.isCellDateFormatted(cell)) { cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue()); } else { - cellValue = String.valueOf(cell.getNumericCellValue()); + // 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: @@ -190,8 +208,10 @@ public class CampaignAPIController { cellValue = "Unknown"; break; } - dataMap.put("column" + cell.getColumnIndex(), cellValue); + // Map cell data to correct column name + dataMap.put(excelHeaders.get(cell.getColumnIndex()), cellValue); } + if (!dataMap.isEmpty()) { dataList.add(dataMap); } @@ -200,13 +220,17 @@ public class CampaignAPIController { 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)); + List> excelData = readExcelData(new FileInputStream(filePath), null); // Return data as JSON return ResponseEntity.ok(excelData); @@ -243,5 +267,348 @@ public class CampaignAPIController { } + + + + @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()); + + // System.out.println("expectedheaders: " + expectedHeaders); + + + // 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()); + + 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 new file mode 100644 index 0000000..0e7d09e --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignDropdownApiController.java @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000..b702dbe --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignReportAPIController.java @@ -0,0 +1,100 @@ +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 index a853302..793e256 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CategoryAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CategoryAPIController.java @@ -1,5 +1,6 @@ package in.gov.chennaicorporation.gccoffice.callcenter.controller; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,19 +28,31 @@ 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()); - } - } +// @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") @@ -47,47 +60,185 @@ public class CategoryAPIController { return addCategoryServices.getAllCategories(); } - // Endpoint to get a category by its ID @GetMapping("/showcategoryId") - public ResponseEntity showCategoryId(@RequestParam("category_id") int categoryId) { + 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 { - 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"); + 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.INTERNAL_SERVER_ERROR) - .body("Error retrieving category: " + e.getMessage()); + 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 updateCategory( + public ResponseEntity updateCategoryWithColumns( @PathVariable("categoryId") int categoryId, - @RequestParam String categoryName) { + @RequestBody Map payload) { - // Validate input - if (categoryName == null || categoryName.trim().isEmpty()) { - return ResponseEntity.badRequest().body("Category name cannot be empty"); - } + String categoryName = (String) payload.get("categoryName"); + List columns = (List) payload.get("columns"); 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"); - } + 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}") @@ -108,11 +259,16 @@ public class CategoryAPIController { //hari category api populate @GetMapping("/getcategory") - public List> 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) @@ -120,9 +276,6 @@ public class CategoryAPIController { 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 index 1065826..48d3adc 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/MainController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/MainController.java @@ -1,4 +1,4 @@ -package in.gov.chennaicorporation.gccoffice.callcenter.controller; + package in.gov.chennaicorporation.gccoffice.callcenter.controller; import java.util.ArrayList; @@ -81,7 +81,7 @@ public class MainController { List> categories = addCategoryServices.getAllCategories(); - System.out.println(categories); + //System.out.println(categories); model.addAttribute("categories", categories); @@ -99,12 +99,14 @@ public class MainController { String UserRole = LoginUserInfo.getUserRole(); model.addAttribute("UserRole", UserRole); - List> campaigns = campaignService.getCampaignDetails(); - - - System.out.println("campaignlist:"+campaigns); - - model.addAttribute("campaigns", campaigns); + /* + * 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) @@ -129,19 +131,7 @@ public class MainController { return "modules/callcenter/campaignlist"; } - @GetMapping("/admin/assignagents") - public String viewAssignAgents(Model model) - { - String LoginUserId = LoginUserInfo.getLoginUserId(); - model.addAttribute("LoginUserId",LoginUserId); - - String UserRole = LoginUserInfo.getUserRole(); - model.addAttribute("UserRole", UserRole); - - return "modules/callcenter/assignagents"; - } - - + @GetMapping("/agentscampaign") public String targetPage(Model model) { @@ -156,11 +146,36 @@ public class MainController { 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, 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 index 5098368..0eff7be 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AddcategoryServices.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AddcategoryServices.java @@ -1,7 +1,9 @@ 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; @@ -11,9 +13,16 @@ 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 { @@ -25,66 +34,235 @@ private JdbcTemplate jdbcTemplate; } +// 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 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"); + List columns = (List) categoryData.get("columns"); - // 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); + 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;"; + 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) { - String sql = "SELECT category_id, category_name FROM category WHERE category_id = ?"; - return jdbcTemplate.queryForMap(sql, categoryId); - } +// // 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 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 = "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 @@ -95,5 +273,31 @@ private JdbcTemplate jdbcTemplate; 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 index 72d13eb..6454519 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentAssignService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentAssignService.java @@ -1,5 +1,8 @@ package in.gov.chennaicorporation.gccoffice.callcenter.service; +import java.util.ArrayList; + +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -8,6 +11,7 @@ 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; @@ -42,7 +46,7 @@ public class AgentAssignService 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 = ? " + + "WHERE cr.category_id = ? AND campaign_status='PENDING' " + "AND cr.isactive = '1' "; return jdbcTemplate.queryForList(sqlQuery,id); } @@ -71,6 +75,60 @@ public class AgentAssignService 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) @@ -92,6 +150,65 @@ public class AgentAssignService } + + @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 index 5d324ee..ffd5b1d 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentsService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentsService.java @@ -9,6 +9,7 @@ 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; @@ -21,6 +22,7 @@ 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; @@ -168,50 +170,52 @@ public class AgentsService { //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> 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); +// } + + @@ -228,11 +232,11 @@ public class AgentsService { } @Transactional - public void saveCallLogs(String call_status,String remarks ,int data_id) + public void saveCallLogs(String call_status,String remarks ,int data_id,int agent_id) { - String SqlQuery = "UPDATE gcc_1913_campaign.upload_data SET field_14 = ?,field_15=?, updated_date = NOW() WHERE (data_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,data_id); + jdbcTemplate.update(SqlQuery,call_status, remarks,agent_id,data_id); } @Transactional @@ -241,7 +245,7 @@ public class AgentsService { 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); + //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 @@ -346,4 +350,307 @@ public class AgentsService { 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()); + + 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/CampaignDropdownApiService.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignDropdownApiService.java new file mode 100644 index 0000000..c68d88e --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignDropdownApiService.java @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000..36fde34 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignReportService.java @@ -0,0 +1,494 @@ +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 " + + "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); + + 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)); + } + } + + +} + + 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 index 7e86069..3419a53 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignService.java @@ -4,10 +4,15 @@ 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; @@ -16,8 +21,14 @@ 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 { @@ -38,43 +49,177 @@ public class CampaignService { 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 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 void saveCampaignDetails(Map campaignDetails) { - String sql = "INSERT INTO gcc_1913_campaign.campaign_request (campaign_name, category_id, start_date, end_date, no_of_agents, calls_per_agent, description, excel_url) " + - "VALUES (:campaign_name, :category_id, :start_date, :end_date, :no_of_agents, :calls_per_agent, :description, :excel_url)"; + 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, campaignDetails); + namedJdbcTemplate.update(sql, campaignDetailsExcel); + + // Return the category to use in the next step + return campaignDetailsExcel.get("category_id").toString(); + } - - public Map getCampaignDetailsById(Long campaign_id) { - String sql = "SELECT * FROM gcc_1913_campaign.campaign_request WHERE campaign_id = ?"; - return jdbcTemplate.queryForMap(sql, campaign_id); + // 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."); + } } + - public void updateCampaign(Long campaign_id, String campaign_name, String start_date, String end_date, Integer no_of_agents, Integer calls_per_agent, String description) { - String sql = "UPDATE gcc_1913_campaign.campaign_request SET campaign_name = ?, start_date = ?, end_date = ?, no_of_agents = ?, calls_per_agent = ?, description = ? WHERE campaign_id = ?"; - jdbcTemplate.update(sql, campaign_name, start_date, end_date, no_of_agents, calls_per_agent, description, campaign_id); - } + //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() { @@ -107,12 +252,36 @@ public class CampaignService { 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,c.category_name,cr.campaign_name,cr.no_of_agents,cr.calls_per_agent,(cr.no_of_agents)*(cr.calls_per_agent) as total_calls\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'"; + 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); } @@ -219,10 +388,10 @@ public class CampaignService { 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\r\n" + 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='0'"; + + "where cr.isactive='1' and cr.campaign_status IN ('ONGOING', 'CLOSED') Order by cr.campaign_id desc"; return jdbcTemplate.queryForList(sqlQuery); } @@ -269,4 +438,267 @@ public class CampaignService { 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(", ")); + + 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/callcenterqaqc/controller/AttendanceApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceApiController.java new file mode 100644 index 0000000..bb52183 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceApiController.java @@ -0,0 +1,36 @@ +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 new file mode 100644 index 0000000..7ffa7b7 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceMainController.java @@ -0,0 +1,71 @@ +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 index 927b96f..e9b71f8 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintController.java @@ -14,6 +14,9 @@ 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; @@ -29,9 +32,13 @@ 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; @@ -76,7 +83,7 @@ public class ComplaintController { } @PostMapping("/register") - public ResponseEntity registerComplaint( + public ResponseEntity registerComplaint( @RequestParam(value = "ComplainantName", required = false) String complainantName, @RequestParam(value = "ComplainantAddr", required = false) String complainantAddr, @RequestParam(value = "MobileNo", required = false) String mobileNo, @@ -141,7 +148,16 @@ public class ComplaintController { reader.close(); // Return the response from the external API - return ResponseEntity.status(responseCode).body(response.toString()); + //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(); @@ -158,8 +174,8 @@ public class ComplaintController { String userType = "Public"; - System.out.println("message:-" + message + "\n UserType:-" + userType + "\n Status:-" + status); - System.out.println(compImage == null); + //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 { @@ -167,7 +183,7 @@ public class ComplaintController { String base64Image = null; if (compImage != null && !compImage.isEmpty()) { base64Image = compressAndEncodeToBase64(compImage); - System.out.println("imageee" + base64Image); + //System.out.println("imageee" + base64Image); } // Construct the POST body with parameters @@ -238,5 +254,420 @@ public class ComplaintController { // 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/external/mobileservice?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 new file mode 100644 index 0000000..3766977 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintStatusMainController.java @@ -0,0 +1,31 @@ +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/FollowUpController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java index 9bbafa3..203dc5f 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java @@ -37,12 +37,12 @@ public class FollowUpController { @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); +// 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); +// System.out.println("updated_agent: " + updated_agent); Map complaintDetails = qaqcCallsService.getComplaintDetails(dataId); 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 index e156409..f356c9f 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/InprogresscallController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/InprogresscallController.java @@ -46,12 +46,12 @@ public class InprogresscallController { @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); +// 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); +// System.out.println("updated_agent: " + updated_agent); //to insert incorrect office mobile number details in table if (action.equals("MOBILE_NUM")) { 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 index 60d7678..827c6c2 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java @@ -67,7 +67,7 @@ public class MainController { List> previousday=agentsService.getPreviousDayDashboardCounts(); model.addAttribute("previousday", previousday); - System.out.println(previousday); + //System.out.println(previousday); List> agentcount=agentsService.getAgentPreviousDayCount(); model.addAttribute("agentcount", agentcount); @@ -107,60 +107,25 @@ public class MainController { return "modules/callcenterqaqc/qaqcfollowuplist"; } - @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); + @GetMapping("/admin/unattendedcomplaints") + public String viewAdminUnattendedClose(Model model) { - return "modules/callcenterqaqc/qaqcagentperformance"; - } - - @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); - + 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/qaqcadminsettings"; + return "modules/callcenterqaqc/unattendedclosing"; } + + + + @GetMapping("/agent/agentgrievancedashboard") public String viewAgentGrievenceDashboardpage( @RequestParam(required = false) String startDate, @@ -194,7 +159,7 @@ public class MainController { List> tasks = agentsService.getAgentTaskDetails(userId, startDate, endDate); model.addAttribute("tasks", tasks); - System.out.println("tasks: "+tasks); + //System.out.println("tasks: "+tasks); return "modules/callcenterqaqc/agentgrievancedashboard"; } @@ -401,74 +366,5 @@ public class MainController { return "modules/callcenterqaqc/agentqaqcpublicfollowupcalls"; } - @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"; - } - - @GetMapping("/pgrcomplaint") - public String viewPGRpage(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/pgrcomplaints"; - } - - @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"; - } - - //callcenterqaqc/socialmediacomplaints - - @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"; - } - } 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 index 2402829..2a68c04 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/PublicFollowUpController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/PublicFollowUpController.java @@ -41,12 +41,12 @@ public class PublicFollowUpController { @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); +// 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); +// System.out.println("updated_agent: " + updated_agent); Map complaintDetails = qaqcCallsService.getComplaintDetails(dataId); 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 index 532ea75..87de00b 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAPIController.java @@ -4,6 +4,7 @@ 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; @@ -84,7 +85,7 @@ public class QaqcAPIController { if (responseEntity.getStatusCode().is2xxSuccessful()) { String responseBody = responseEntity.getBody(); - System.out.println("Response Body: " + responseBody); + //System.out.println("Response Body: " + responseBody); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(responseBody); @@ -92,7 +93,7 @@ public class QaqcAPIController { JsonNode complaintDetails = rootNode.path(0).path("ComplaintListHistory").path(0); String registerDate=complaintDetails.path("complaintopendate").asText("N/A"); - System.out.println("registerdate====="+registerDate); + //System.out.println("registerdate====="+registerDate); String formattedDate = "N/A"; // Default value if parsing fails @@ -103,7 +104,7 @@ public class QaqcAPIController { Date date = inputFormat.parse(registerDate); // Format the date to dd-MM-yyyy - SimpleDateFormat outputFormat = new SimpleDateFormat("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 @@ -172,7 +173,7 @@ public class QaqcAPIController { resultMap.put("userimages", userImagesList); - System.out.println("Image URL from API: " + mediaLink); + // System.out.println("Image URL from API: " + mediaLink); } } else { resultMap.put("error", "Failed to retrieve complaint details."); @@ -205,9 +206,9 @@ public class QaqcAPIController { } // Print debug info - System.out.println("Received callStatus: " + callStatus); - System.out.println("From Date: " + fromDate); - System.out.println("To Date: " + toDate); +// 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); @@ -240,7 +241,8 @@ public class QaqcAPIController { @RequestParam String group, @RequestParam String type, @RequestParam String mode, - @RequestParam String zone) { + @RequestParam String zone, + @RequestParam String region) { Map response = new HashMap<>(); try { @@ -250,7 +252,7 @@ public class QaqcAPIController { 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/external/mobileservice?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/external/mobileservice?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(); @@ -287,5 +289,103 @@ public class QaqcAPIController { 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 new file mode 100644 index 0000000..ad28d8d --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsApiController.java @@ -0,0 +1,208 @@ +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 new file mode 100644 index 0000000..b84583a --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsMainController.java @@ -0,0 +1,47 @@ +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 index fa49a52..0273cbe 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentAssignAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentAssignAPIController.java @@ -76,8 +76,7 @@ public class QaqcAgentAssignAPIController { 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); + //System.out.println("Agent ID: " + agentId + ", Today Count: " + todayCount +", Campaign Pending Count: " + campaignPendingCount + ", Pending Counts: " + pendingCounts); if(pendingCounts> counts = agentsService.getAgentPerformanceCount(startDate, endDate); - System.out.println("fromdates: " + startDate); - System.out.println("todate: " + endDate); - System.out.println("overallcounts: " + counts ); +// System.out.println("fromdates: " + startDate); +// System.out.println("todate: " + endDate); +// System.out.println("overallcounts: " + counts ); return counts; } @@ -111,15 +111,15 @@ public class QaqcAgentsAPIController { List> agentPerformanceData = agentsService.getAgentPerformanceList(startDate, endDate); // Log or return the data - System.out.println("Agent Performance Data: " + agentPerformanceData); + //System.out.println("Agent Performance Data: " + agentPerformanceData); return agentPerformanceData; } @GetMapping("/agenttaskwise") - public List> getAgentTaskwiseData(@RequestParam String agentId) { + 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); - System.out.println("Agent Task Wise Data: " + agentTaskwiseData); + List> agentTaskwiseData = agentsService.getAgentTaskwiseData(agentId, startDate, endDate); + //System.out.println("Agent Task Wise Data: " + agentTaskwiseData); return agentTaskwiseData; } @@ -131,7 +131,7 @@ public class QaqcAgentsAPIController { @RequestParam(required = false) String complaintMobileNumber){ List> agentAttendedData = agentsService.getAttendedComplaintStatus(startDate, endDate, complaintNumber, complaintMobileNumber); - System.out.println("Agent attended Data: " + agentAttendedData); + //System.out.println("Agent attended Data: " + agentAttendedData); return agentAttendedData; } @@ -143,7 +143,7 @@ public class QaqcAgentsAPIController { @RequestParam(required = false) String complaintMobileNumber){ List> agentAttendedData = agentsService.getAttendedComplainthistory(startDate, endDate, complaintNumber, complaintMobileNumber); - System.out.println("Agent attended Data: " + agentAttendedData); + //System.out.println("Agent attended Data: " + agentAttendedData); return agentAttendedData; } 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 index 0244cad..7e1c02b 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcCallsController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcCallsController.java @@ -57,12 +57,12 @@ public class QaqcCallsController { @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); +// 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); +// System.out.println("updated_agent: " + updated_agent); // Map followUpComplaint = @@ -134,7 +134,7 @@ public class QaqcCallsController { if (responseEntity.getStatusCode().is2xxSuccessful()) { String responseBody = responseEntity.getBody(); - System.out.println("Response Body: " + responseBody); + //System.out.println("Response Body: " + responseBody); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(responseBody); @@ -146,7 +146,7 @@ public class QaqcCallsController { String ReopenDate = complaintDetails.path("REOPENDDATE").asText("N/A"); String FinalcloseDate = complaintDetails.path("FINALCLOSEDDATE").asText("N/A"); - System.out.println("registerdate=====" + registerDate); + //System.out.println("registerdate=====" + registerDate); String formattedDate = "N/A"; // Default value if parsing fails @@ -157,7 +157,7 @@ public class QaqcCallsController { Date date = inputFormat.parse(registerDate); // Format the date to dd-MM-yyyy - SimpleDateFormat outputFormat = new SimpleDateFormat("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 @@ -244,7 +244,7 @@ public class QaqcCallsController { userImagesList.add(imageMap); resultMap.put("userimages", userImagesList); - System.out.println("Image URL from API: " + mediaLink); + //System.out.println("Image URL from API: " + mediaLink); } } else { resultMap.put("error", "Failed to retrieve complaint details."); @@ -262,10 +262,10 @@ public class QaqcCallsController { @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); +// 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<>(); @@ -290,8 +290,8 @@ public class QaqcCallsController { endDate = LocalDate.parse(endDate, inputFormatter).format(outputFormatter); // Debug logs (optional) - System.out.println("Formatted Start Date: " + startDate); - System.out.println("Formatted End Date: " + endDate); +// System.out.println("Formatted Start Date: " + startDate); +// System.out.println("Formatted End Date: " + endDate); String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getComplaintListWithImg&From_date=" + startDate + "&To_date=" + endDate 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 new file mode 100644 index 0000000..bdeb694 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcPgrComplaintsMainController.java @@ -0,0 +1,26 @@ +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/callcenterqaqccomplaintsregistration") +@Controller("callCenterQaQcComplaintsRegistrationController") +public class QaqcPgrComplaintsMainController { + + @GetMapping("/pgrcomplaint") + public String viewPGRpage(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/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 index 7022d79..a422329 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java @@ -39,7 +39,7 @@ public class QaqcTaskListAPIController { @RequestParam(required = false) String endDate) { List> counts = tasklist.getComplaintAndCallStatusCounts(startDate, endDate); - System.out.println("overallcounts:" + counts); + //System.out.println("overallcounts:" + counts); return counts; } @@ -50,7 +50,7 @@ public class QaqcTaskListAPIController { @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) { List> taskdata = tasklist.getTaskwiseData(startDate, endDate); - System.out.println("taskdata "+ taskdata); + //System.out.println("taskdata "+ taskdata); return taskdata; } @@ -60,7 +60,7 @@ public class QaqcTaskListAPIController { public List> getAgentwiseData(@RequestParam String qaqc_id) { List> agentwisedata = tasklist.getAgentwiseData(qaqc_id); - System.out.println("agentdata "+agentwisedata); + //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 new file mode 100644 index 0000000..50c6b3a --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ReportsMainController.java @@ -0,0 +1,58 @@ +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/SocialMediaApiController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaApiController.java new file mode 100644 index 0000000..d746efb --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaApiController.java @@ -0,0 +1,349 @@ +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 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 + ) { + 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("updated_agent: " + updated_agent); + 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); + 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/external/mobileservice?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"); + 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) { + 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/external/mobileservice?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/external/mobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+mode+"&Zoneid="+zone; + + 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("/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; + } + +} 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 new file mode 100644 index 0000000..ae08fd2 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaMainController.java @@ -0,0 +1,41 @@ +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"; + } + +} 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 index 078410b..b5b9f2f 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java @@ -27,16 +27,18 @@ public class StatusCountController { } @GetMapping("/dashboard") - public ResponseEntity> getDashboardData( + 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 = "dropdown4", required = false, defaultValue = "") String compGroup, + @RequestParam(value = "regiondropdown", required = false, defaultValue = "") String region) { + - Map counts = statusCountService.fetchComplaintCounts(fromDate, toDate, compType, zoneName, compMode, compGroup); - System.out.println("counts:" + counts); + 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); } 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 index 4c5c56a..1711ef1 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/FollowUpService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/FollowUpService.java @@ -65,12 +65,12 @@ public class FollowUpService { int rowsUpdated = jdbcTemplate.update(query, action, remarks,updated_agent, dataId,complaintNumber); - System.out.println("Rows Updated in upload data: " + rowsUpdated); + //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); + //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(); @@ -98,7 +98,7 @@ public class FollowUpService { + "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); + //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, " @@ -108,7 +108,7 @@ public class FollowUpService { 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); + //System.out.println("Rows Updated in qaqc_call_logs : " + rowsAffected1); return rowsAffected + rowsAffected1; @@ -120,7 +120,7 @@ public class FollowUpService { + "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); + //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) " @@ -130,7 +130,7 @@ public class FollowUpService { personMobNo, cType, cMode, department, cGroup, officialName, officialMobileNum, callStatus, remarks, isProcessed,updated_agent); - System.out.println("Rows Updated in qaqc_call_logs: " + rowsAffected1); + //System.out.println("Rows Updated in qaqc_call_logs: " + rowsAffected1); return rowsAffected + rowsAffected1; } @@ -166,7 +166,7 @@ public class FollowUpService { int rowsUpdated = jdbcTemplate.update(query, action, remarks, remainderDate, updated_agent,dataId, complaintNumber); - System.out.println("Rows Updated in upload history: " + rowsUpdated); + //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 index 6e01081..649558e 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/InprogresscallService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/InprogresscallService.java @@ -65,13 +65,13 @@ public class InprogresscallService { int rowsUpdated = jdbcTemplate.update(query, action, remarks,updated_agent, dataId,complaintNumber); - System.out.println("Rows Updated in upload data: " + rowsUpdated); + //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); + //System.out.println("Rows Updated: " + rowsUpdated); } public List> getInprogressSubmitDetails(int userId) { @@ -95,7 +95,7 @@ public class InprogresscallService { int rowsUpdated = jdbcTemplate.update(query, action, remarks, remainderDate,updated_agent, dataId, complaintNumber); - System.out.println("Rows Updated in upload data history: " + rowsUpdated); + //System.out.println("Rows Updated in upload data history: " + rowsUpdated); } 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 index b2b9989..e57d89e 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java @@ -95,11 +95,29 @@ public class QaqcAdminSettingService { @Transactional public List> getAgentsForCallingtype() { - String sqlQuery = "select agent_id,agent_name,mobile_number,calling_type\r\n" - + "from agents_list\r\n" - + "where isactive='1' and isdelete='0';"; + 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 index 2c80a30..22720cd 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentAssignService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentAssignService.java @@ -32,6 +32,8 @@ 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 @@ -55,7 +57,9 @@ public class QaqcAgentAssignService { @Transactional public Integer getCampaignPendingCountForAgent(int agentId) { - String countQuery = "SELECT COUNT(data_id) FROM gcc_1913_campaign.upload_data WHERE agent_id = ? AND field_14 IS NULL"; + 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); } @@ -101,16 +105,17 @@ public class QaqcAgentAssignService { 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); + //System.out.println("closedCount====="+closedCount); List> agents = (List>) requestData.get("agents"); - System.out.println("agents====="+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); @@ -120,12 +125,12 @@ public class QaqcAgentAssignService { 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); + //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); + int rowsInserted = savetaskid(taskId, formattedFromDate, formattedToDate, description, status, closedCount,group,type,mode,zone,region); if (rowsInserted <= 0) { throw new RuntimeException("Failed to create task"); @@ -141,31 +146,31 @@ public class QaqcAgentAssignService { List> assignedIDList = new ArrayList<>(); - System.out.println("Before shuffle: " + agents); + //System.out.println("Before shuffle: " + agents); // Shuffle the agents list Collections.shuffle(agents); - System.out.println("After 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); + //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/external/mobileservice?serviceId=ms_dashboard_details&From_date="+formattedFromDate+"&To_date="+formattedToDate+"&jsonResp=Yes&Status="+status+"&isQcuser=Yes"+"&ComplaintType="+type+"&ComplaintGroupId="+group+"&compmode="+mode+"&Zoneid="+zone; - System.out.println(url); + String url="https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?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); @@ -263,7 +268,7 @@ public class QaqcAgentAssignService { if (generatedDataId != null) { long dataId = generatedDataId.longValue(); - System.out.println("followdataId=="+dataId); + //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) " + @@ -283,7 +288,7 @@ public class QaqcAgentAssignService { return false; } } - + @Transactional public boolean processAndSaveDetails(String url, int qaqc_id, List> agents,String status,List> assignedIDList, String mode) { try { @@ -327,7 +332,21 @@ public class QaqcAgentAssignService { 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()); + 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; @@ -351,7 +370,7 @@ public class QaqcAgentAssignService { //System.out.println(i +" "+index); String complaintNumber1 = (String) details.get(index).get("Complaint Number"); - System.out.println("complaintNumber = "+complaintNumber1); + //System.out.println("complaintNumber = "+complaintNumber1); Map result = followupData.stream() .filter(map -> complaintNumber1.equals(map.get("complaint_number"))) @@ -405,14 +424,15 @@ public class QaqcAgentAssignService { ps.setString(10, complaintGroup); ps.setString(11, officerName); ps.setString(12, officerMobileNumber); - ps.setInt(13, currentAgentId); + 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); + + //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) " + @@ -430,7 +450,7 @@ public class QaqcAgentAssignService { } } else { - System.out.println("else complaintNumber = "+complaintNumber1); + //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"); @@ -467,7 +487,7 @@ public class QaqcAgentAssignService { if (generatedDataId != null) { long dataId2 = generatedDataId.longValue(); - System.out.println("dataId2 else=="+dataId2); + //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) " + @@ -508,7 +528,7 @@ public class QaqcAgentAssignService { e.printStackTrace(); return false; } - } + } private List> getFollowupData() { @@ -549,7 +569,7 @@ public class QaqcAgentAssignService { } } @Transactional - public int savetaskid(String taskid,String fromdate,String todate,String description,String status, int closedCount,String group, String type, String mode, String zone) { + 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()) { @@ -564,10 +584,13 @@ public class QaqcAgentAssignService { 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) " + - "VALUES (?,?,?,?,?,?,?,?,?,?)"; - int rowsInserted = jdbcTemplate.update(sql,taskid,fromdate,todate,description,status,closedCount,group,type,mode,zone); + 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 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 index 086a915..763e830 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentsService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentsService.java @@ -330,11 +330,11 @@ public class QaqcAgentsService { "( " + " SELECT " + " SUM(qr.total_data) AS total_data, " + - " COUNT(DISTINCT CONCAT(qcl.qaqc_id, '_', qcl.complaint_number)) AS completed_calls " + + " COUNT(CASE WHEN qcl.call_status IS NOT NULL THEN qcl.qaqc_id END) AS completed_calls" + " FROM " + " qaqc_request qr " + " LEFT JOIN " + - " qaqc_call_logs qcl " + + " qaqc_upload_data_history qcl " + " ON " + " qr.qaqc_id = qcl.qaqc_id " + " WHERE " + @@ -383,8 +383,8 @@ public class QaqcAgentsService { " 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(qaqc_id) AS TotalCompleted " + - " FROM qaqc_call_logs " + + " (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 " + @@ -394,7 +394,7 @@ public class QaqcAgentsService { " 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_call_logs " + + " 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" @@ -412,7 +412,7 @@ public class QaqcAgentsService { - public List> getAgentTaskwiseData(String agentId) { + public List> getAgentTaskwiseData(String agentId,String startDate, String endDate) { String query="WITH LatestCallLogs AS (\r\n" + " SELECT \r\n" @@ -445,12 +445,12 @@ public class QaqcAgentsService { + "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 = ?\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); + return jdbcTemplate.queryForList(query, agentId,startDate,endDate); } 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 index 2191a3c..35bb592 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java @@ -53,7 +53,7 @@ public class QaqcCallsService { @Transactional public int uploadComplaintDetailsInLogs(Map logDetails, String action, String complaintNumber, String remainderDate) { - System.out.println("Complaint Details: " + logDetails); + //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(); @@ -82,7 +82,7 @@ public class QaqcCallsService { 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); + //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) " @@ -91,7 +91,7 @@ public class QaqcCallsService { 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); + //System.out.println("Rows Inserted in qaqc_call_logs : " + rowsAffected1); return rowsAffected + rowsAffected1; @@ -105,7 +105,7 @@ public class QaqcCallsService { personMobNo, cType, cMode, department, cGroup, officialName, officialMobileNum, callStatus, remarks, isProcessed,updated_agent); - System.out.println("Rows Inserted in qaqc_call_logs: " + rowsAffected); + //System.out.println("Rows Inserted in qaqc_call_logs: " + rowsAffected); return rowsAffected; } @@ -120,7 +120,7 @@ public class QaqcCallsService { int rowsUpdated = jdbcTemplate.update(query, action, remarks,updated_agent, dataId,complaintNumber); - System.out.println("Rows Updated in upload data: " + rowsUpdated); + //System.out.println("Rows Updated in upload data: " + rowsUpdated); } public Map getComplaintDetails(int dataId) { @@ -320,11 +320,11 @@ public class QaqcCallsService { // Parse the response String response = responseBuilder.toString(); - System.out.println("Raw Response: " + response); + //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."); + //System.out.println("ResultStatus is true in the response."); return true; } else { System.out.println("ResultStatus is false or not present in the response."); @@ -340,7 +340,7 @@ public class QaqcCallsService { 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); + //System.out.println("Rows Updated: " + rowsUpdated); } public Map checkComplaintDetail(String complaintNumber) { @@ -354,12 +354,12 @@ public class QaqcCallsService { } public void updateFollowupCallLogs(String complaintNumber, String action, String remarks, int followupid) { - System.out.println(complaintNumber+action+remarks); + //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); + //System.out.println("Rows Updated in followup: " + rowsUpdated); } @@ -383,7 +383,7 @@ public class QaqcCallsService { int rowsUpdated = jdbcTemplate.update(query, action, remarks, remainderDate,updated_agent, dataId, complaintNumber); - System.out.println("Rows Updated in upload history: " + rowsUpdated); + //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 index 62c6dd5..a4f7d90 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcService.java @@ -1,7 +1,16 @@ 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; @@ -96,8 +105,8 @@ public class QaqcService { } // Final debugging: print the query and parameters - System.out.println("Final SQL Query: " + sql); - System.out.println("Query Parameters: " + params); + //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()); @@ -122,5 +131,210 @@ public class QaqcService { 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 index e4440d2..00017f6 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcTaskListService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcTaskListService.java @@ -118,11 +118,11 @@ public class QaqcTaskListService { .append("( ") .append(" SELECT ") .append(" SUM(qr.total_data) AS total_data, ") - .append(" COUNT(CASE WHEN qcl.qaqc_id IS NOT NULL THEN qcl.qaqc_id END) AS completed_calls ") + .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_call_logs qcl ") + .append(" qaqc_upload_data_history qcl ") .append(" ON ") .append(" qr.qaqc_id = qcl.qaqc_id "); @@ -215,18 +215,18 @@ public class QaqcTaskListService { " WHERE aa.qaqc_id = qr.qaqc_id" + " ) AS Assigned, " + " MAX(DATE(qr.created_date)) AS TaskCreatedDate, " + - " COUNT(CASE WHEN acl.qaqc_id IS NOT NULL THEN qr.qaqc_id END) AS TotalCompleted, " + + " 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.qaqc_id IS NOT NULL THEN qr.qaqc_id END) AS Pending, " + + " ) - 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_call_logs acl " + + "LEFT JOIN qaqc_upload_data_history acl " + "ON qr.qaqc_id = acl.qaqc_id " ); @@ -255,33 +255,32 @@ public class QaqcTaskListService { public List> getAgentwiseData(String qaqc_id) { - String query= "WITH LatestCallLogs AS (\r\n" - + " SELECT 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 qaqc_call_logs cl\r\n" - + ")\r\n" - + "SELECT DISTINCT al.agent_id,\r\n" - + " al.agent_name AS agentName,\r\n" - + " qr.taskid as taskId,\r\n" - + " qr.fromdate as fromdate,qr.todate as todate,qr.description as description,qr.call_category as call_category,\r\n" - + " qr.complaint_group as complaint_group,qr.complaint_type as complaint_type,qr.complaint_mode as complaint_mode,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.qaqc_id) AS callstaken,\r\n" - + " (aa.data_count - COUNT(lcl.qaqc_id)) AS pending,\r\n" - + " ROUND((COUNT(lcl.qaqc_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" + 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 LatestCallLogs lcl ON qr.qaqc_id = lcl.qaqc_id AND al.agent_id = lcl.agent_id AND lcl.row_num = 1\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"; 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 index 3cc3066..d1f52c0 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java @@ -27,7 +27,7 @@ public class SocialMediaService { @Transactional public int uploadComplaintDetailsInLogs(Map details,String action,String remarks,int updated_agent) { - System.out.println("Complaint Details: " + details); + //System.out.println("Complaint Details: " + details); // Extract other field values from complaintDetails String complaintNumber = details.get("complaintid").toString(); String complaintDate = details.get("complaintdate").toString(); @@ -52,7 +52,7 @@ public class SocialMediaService { int rowsAffected = jdbcTemplate.update(query, complaintNumber,zone, complaintDate,personName,remarksfield, personMobNo, cType, cMode, department, officialName, officialMobileNum,callStatus, currentDate,updated_by); - System.out.println("Rows Inserted in table : " + rowsAffected); + //System.out.println("Rows Inserted in table : " + rowsAffected); return rowsAffected; @@ -75,14 +75,14 @@ public class SocialMediaService { } // Log the query and parameters for debugging - System.out.println("Executing query: " + query.toString()); - System.out.println("With parameters: " + params); + //System.out.println("Executing query: " + query.toString()); + //System.out.println("With parameters: " + params); // Execute the query List> results = jdbcTemplate.queryForList(query.toString(), params.toArray()); // Log the results for debugging - System.out.println("Query results: " + results); + //System.out.println("Query results: " + results); return results.isEmpty() ? null : results; } @@ -92,8 +92,10 @@ public class SocialMediaService { String query="SELECT erp_username FROM gcc_1913_qaqc.agents_list\r\n" + "where calling_type='SOCIALMEDIA' and agent_id=?"; - System.out.println("query====="+query); - String erpUsername = jdbcTemplate.queryForObject(query,new Object[]{userId},String.class); + //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; } 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 index bf120f5..c1e4120 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/StatusCountService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/StatusCountService.java @@ -1,5 +1,7 @@ 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; @@ -29,7 +31,7 @@ public class StatusCountService { this.objectMapper = objectMapper; } - public Map fetchComplaintCounts(String fromDate, String toDate, String compType, String zoneName, String compMode, String compGroup) { + public Map fetchComplaintCounts(String fromDate, String toDate, String compType, String zoneName, String compMode, String compGroup, String region) { //https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=common_api&jsonResp=Yes&subService=dashboardAbs&fromDate=&toDate=&compType=&zoneName=&compMode=&compGroup= String apiUrl; if ("SOCIAL MEDIA".equalsIgnoreCase(compMode)) { @@ -65,35 +67,57 @@ public class StatusCountService { if (!compGroup.isEmpty()) { apiUrl += "&compGroup=" + compGroup; } + + if (!region.isEmpty()) { + apiUrl += "®ion=" + region; + } - Map counts = new HashMap<>(); + 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 + //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()) { - System.out.println("ListResult is null or empty"); - return counts; // Return empty map or default values - } - - 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("")); - } else { - System.out.println("ResultNode is null"); + + 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/external/mobileservice?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(); + + 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(); } 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 new file mode 100644 index 0000000..cd42e59 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/DumpRegistrationAPIController.java @@ -0,0 +1,174 @@ +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 new file mode 100644 index 0000000..e086376 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/MainController.java @@ -0,0 +1,75 @@ +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 new file mode 100644 index 0000000..9263538 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/OfficerService.java @@ -0,0 +1,161 @@ +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 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 new file mode 100644 index 0000000..a7e5a13 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/SMSService.java @@ -0,0 +1,40 @@ +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/com_petition/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/APIController.java index 85b37eb..135039b 100644 --- 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 @@ -1,6 +1,8 @@ package in.gov.chennaicorporation.gccoffice.com_petition.controller; import java.util.List; +import java.util.Map; + import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -157,4 +159,46 @@ public class APIController { 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 + } } 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 index 5ff2e56..7e2066d 100644 --- 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 @@ -553,44 +553,52 @@ public class Petition { } @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` " - + " FROM " - + " `petition` p,`petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " 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 - } + 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) @@ -716,4 +724,24 @@ public class Petition { } 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"; + } } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java index 2bafdef..83e380b 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java @@ -20,6 +20,7 @@ public class AppConfig { public String cdwastecollectors = "http://117.232.67.158:8071"; public String qaqcurl="https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?"; public String attendanceReport = "http://117.232.67.158:8076"; + public String dumpregister = "https://gccservices.in"; public String gccappsMysqlPassword = ""; @Bean diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java index 189bdb6..7589526 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java @@ -24,15 +24,14 @@ import java.util.Properties; @EnableTransactionManagement public class DataSourceConfig { - private static String host = "localhost:3306"; - - //private static String dbpassword = "gccroot"; + //private static String host = "localhost:3306"; + //private static String dbpassword = ""; + + // private static String dbpassword = "gccroot"; - private static String dbpassword = ""; // 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"; + 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 @@ -210,6 +209,17 @@ public class DataSourceConfig { 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() { @@ -254,6 +264,73 @@ public class DataSourceConfig { 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 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; + } + ////////////////////////////// ORACLE //////////////////////// @Bean(name = "oracleDataSource") public DataSource oracleDataSource() { diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java index 745b667..1397aa5 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java @@ -31,7 +31,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { public void configure(WebSecurity web) throws Exception { web .ignoring() - .antMatchers("/static/**", "/assets/**", "/api/**","/images/**","/gcc/static/**", "/gcc/assets/**", "/gcc/api/**","/gcc/images/**","/gcc/files/**"); + .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 } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java index 887c1c1..bc82455 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java @@ -55,7 +55,6 @@ public class MenuController { return ""; } - List getAppModuleAccessEntities; List getAppModuleEntities; if(LoginUserInfo.getUserRole().equals("ADMIN")) { @@ -101,7 +100,16 @@ public class MenuController { List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); String subSubMenuHTML = ""; for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; + 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("")) { @@ -126,7 +134,15 @@ public class MenuController { List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(menuItem.getId(),checkSubMenuId); String subSubMenuHTML = ""; for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; + 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+"
"; } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java index 5ce6560..19134c6 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java @@ -141,4 +141,5 @@ public class SubMenuItemAccessEntity { 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 index fdcb04e..dedd2f3 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemEntity.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemEntity.java @@ -50,6 +50,8 @@ public class SubMenuItemEntity { @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() { @@ -165,5 +167,13 @@ public class SubMenuItemEntity { 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/m_petition/controller/APIController.java b/src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/APIController.java index 7e77446..58658e7 100644 --- 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 @@ -42,8 +42,9 @@ public class APIController { } @GetMapping(value="/getPetitionList") - public List getPetitionList() { - return petition.getPetitionList(); + public List getPetitionList(@RequestParam("searchmonth") String month, + @RequestParam("searchyear") String year) { + return petition.getPetitionList(month,year); } @GetMapping(value="/getUnmapPetitionList") @@ -122,8 +123,12 @@ public class APIController { } @GetMapping(value="/getComplaintList") - public List getComplaintList(@RequestParam("loginId") String loginId) { - return petition.getComplaintList(loginId); + public List getComplaintList(@RequestParam("loginId") String loginId, + @RequestParam("searchmonth") String month, + @RequestParam("searchyear") String year + ) { + + return petition.getComplaintList(loginId,month,year); } @GetMapping(value="/getComplaintListByPetitionId") 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 index 3d6bd38..6a65d94 100644 --- 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 @@ -46,27 +46,27 @@ import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; @Service public class Petition { - private JdbcTemplate jdbcTemplate; - private JdbcTemplate jdbcOracleTemplate; - private final Environment environment; - private PetitionMaster petitionMaster; - private GetMappingUserDetails getMappingUserDetails; - @Autowired - public Petition(Environment environment,PetitionMaster petitionMaster) { - this.environment = environment; - this.petitionMaster = petitionMaster; - this.getMappingUserDetails = getMappingUserDetails; - } + private final GetMappingUserDetails getMappingUserDetails; + private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcOracleTemplate; + private final Environment environment; + private final PetitionMaster petitionMaster; - @Autowired - public void setDataSource( - @Qualifier("mysqlMayorPetitionDataSource") DataSource dataSource, - @Qualifier("oracleDataSource") DataSource oracleDataSource - ) { - this.jdbcTemplate = new JdbcTemplate(dataSource); - this.jdbcOracleTemplate = new JdbcTemplate(oracleDataSource); - } + + // 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() { @@ -103,30 +103,37 @@ public class Petition { } @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 - } - } + 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 * FROM petition WHERE (`isactive`=1 AND `isdelete`=0) AND DATE(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() { @@ -451,7 +458,10 @@ public class Petition { } @Transactional(readOnly = true) - public List> getComplaintList(String loginId) { + 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`, " @@ -466,18 +476,20 @@ public class Petition { + " 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.`petition_id` = pm.`petition_id`) " + + " AND DATE(p.cdate) LIKE ?" + " "; //if (officerMaster != null && !officerMaster.isEmpty() && loginId!='256') { - if (!loginId.equals("256") && !loginId.equals("1")) { + 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); + List> result = jdbcTemplate.queryForList(sqlQuery,datePattern); // Iterate over the list of maps for (Map map : result) { @@ -539,45 +551,53 @@ public class Petition { } @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` " - + " FROM " - + " `petition` p,`petition_mapping` pm, `petition_master`.`officer_master` om, `petition_master`.`complaint_types` ctype " - + " 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 - } - } + 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) { @@ -667,7 +687,7 @@ public class Petition { var year = DateTimeUtil.getCurrentYear(); var month = DateTimeUtil.getCurrentMonth(); - uploadDirectory = uploadDirectory + serviceFolderName + serviceActionFolderName;// + year + "/" + month; + uploadDirectory = uploadDirectory + serviceFolderName + "/" + serviceActionFolderName;// + year + "/" + month; // File name fileName = mapId + "_" + fileName + "_" + file.getOriginalFilename(); 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 index 52e468e..9cef3d6 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java @@ -494,7 +494,7 @@ public class NulmAPIController { List> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, inchargeName, enrollmentIds); return ResponseEntity.ok(staffList); } - + /* @PostMapping("/salaryDetailUpdate") public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { System.out.println("Received POST request with data: " + requestList); @@ -535,6 +535,61 @@ public class NulmAPIController { .body("Invalid request data: " + e.getMessage()); } } + */ + @PostMapping("/salaryDetailUpdate") + public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { + System.out.println("Received POST request with data: " + requestList); + try { + for (Map request : requestList) { + System.out.println("enrollment_id = " + request.get("enrollment_id").toString()); + int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); + int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); + int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); + int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); + String month = request.get("month").toString(); + int year = Integer.parseInt(request.get("year").toString()); + int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); + int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); + int groupId = Integer.parseInt(request.get("group_id").toString()); + int wageId = Integer.parseInt(request.get("wage_id").toString()); + int inchargeID = 0;//Integer.parseInt(""+request.get("incharge_id")); + + + // Check if the month and year are valid for salary initiation (past month) + if (isFutureOrCurrentMonth(month, year)) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("Salary cannot be initiated for the current or future months. Please select a past month."); + } + + String salaryStatus = "Initiated"; + + boolean checkexist = nulmService.checkSalaryDetails(enrollmentId, month, year); + + System.out.println("checkexist: " + checkexist); + + if (!checkexist) { + // Call the service method to insert the salary details + int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); + if (rowsAffected <= 0) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Failed to add salary details for enrollment ID: " + enrollmentId); + } + } else { + int rowsAffected = nulmService.updateSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); + if (rowsAffected <= 0) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Failed to update salary details for enrollment ID: " + enrollmentId); + } + } + } + return ResponseEntity.status(HttpStatus.CREATED) + .body("Salary details added successfully for all selected entries."); + } catch (Exception e) { + e.printStackTrace(); // Log the exception for debugging + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("Invalid request data: " + e.getMessage()); + } + } // Helper method to check if the month is future or current private boolean isFutureOrCurrentMonth(String month, int year) { 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 index 5db72a0..957b515 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmController.java @@ -1,12 +1,15 @@ 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 java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -204,4 +207,78 @@ public class NulmController { 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("/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)); + + } + + +@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"; + } } 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 index 57551d9..4a1eca2 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java @@ -376,7 +376,7 @@ public class NulmService { } public List> getSelfHelpGroups() { - String sql = "SELECT group_id AS groupId, group_name AS groupName FROM suyaudavi_kuzhu WHERE isactive = 1 AND isdelete = 0"; + 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); } @@ -523,7 +523,7 @@ public class NulmService { // Execute the query with the provided parameters List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - //List> results = nulmJdbcTemplate.queryForList(sql.toString()); + //List> results = jdbcTemplate.queryForList(sql.toString()); return results; } /* @@ -772,7 +772,7 @@ public class NulmService { ZoneWhare = " AND en.zone IN (0)"; } - 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, " + 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 " @@ -1768,4 +1768,137 @@ public class NulmService { return results; } */ + + public List> getConsolidatedAttendanceReport(String fromdate, String todate, String groupName, String zone, String division) { // newly added + String sql = "select \n" + + "et.emp_id, et.enrollment_id, et.name, " + + "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) AS total_days, " + + "count(distinct date(att.indatetime)) as totaldayspresent, " + + "count(distinct case when att.indatetime is null then date(att.oddatetime) end) as totaldaysod, " + + "count(distinct date(att.leavedatetime)) as totaldaysleave, " + + "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) - " + + "((count(distinct date(att.indatetime)) + " + + "count(distinct case when att.indatetime is null then date(att.oddatetime) end) + " + + "count(distinct date(att.leavedatetime)))) as totaldaysabsent, " + + "et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + + "et.division, et.department, sk.group_name from attendance att " + + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " + + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where " + + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + todate + "', '%Y-%m-%d') " + + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + todate + "', '%Y-%m-%d')" + + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + todate + "', '%Y-%m-%d')) " + + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") + + (division != null && !division.isEmpty() ? " and et.division = ? " : "") + + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : "") + + " group by et.emp_id, et.enrollment_id, et.name, et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + + " et.division, et.department, sk.group_name"; + + // Prepare the query parameters based on provided inputs + List params = new ArrayList<>(); + //params.add(fromdate); + //params.add(todate); + if (groupName != null && !groupName.isEmpty()) { + params.add(groupName); + } + if (zone != null && !zone.isEmpty()) { + params.add(zone); + } + if (division != null && !division.isEmpty()) { + params.add(division); + } + + + List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); + return results; + } + + +public Map> fetchAttendanceDates(String enrollmentId, String fromdate, String todate, String type) { //newly added + Map> attendanceData = new HashMap<>(); + + if (type.equals("present")) { + String presentQuery = "SELECT DISTINCT DATE_FORMAT(DATE(indatetime), '%d-%m-%Y') AS PresentDates " + + "FROM attendance WHERE enrollment_id = ? AND DATE(indatetime) BETWEEN STR_TO_DATE(? , '%Y-%m-%d') AND " + + "STR_TO_DATE(? , '%Y-%m-%d')"; + attendanceData.put("presentDates", jdbcTemplate.queryForList(presentQuery, String.class, enrollmentId, fromdate, todate)); + + } else if (type.equals("od")) { + String odQuery = "SELECT DISTINCT DATE_FORMAT(DATE(oddatetime), '%d-%m-%Y') AS OdDates " + + "FROM attendance WHERE enrollment_id = ? AND DATE(oddatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; + attendanceData.put("odDates", jdbcTemplate.queryForList(odQuery, String.class, enrollmentId, fromdate, todate)); + } else if (type.equals("leave")) { + String leaveQuery = "SELECT DISTINCT DATE_FORMAT(DATE(leavedatetime), '%d-%m-%Y') AS LeaveDates " + + "FROM attendance WHERE enrollment_id = ? AND DATE(leavedatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; + attendanceData.put("leaveDates", jdbcTemplate.queryForList(leaveQuery, String.class, enrollmentId, fromdate, todate)); + } else if (type.equals("absent")) { + String absentQuery = ""; + + } + + return attendanceData; + } + + + + public List> getSelfHelpGroupDetails() { // newly added + String sql = "select * from suyaudavi_kuzhu where isactive = 1 and isdelete =0 order by group_name asc"; + List> results = jdbcTemplate.queryForList(sql); + return results; + } + + + + public List> getSalaryNotInitiatedReport(String month, Integer year, String groupName) { + + String sql = "SELECT e.emp_id, e.name, e.designation, e.incharge_name, e.incharge_designation, e.incharge_phoneno, sk.group_name " + + "FROM enrollment_table e " + + "left join suyaudavi_kuzhu sk on e.group_id = sk.group_id " + + "WHERE NOT EXISTS ( SELECT 1 " + + " FROM salary_details s " + + " WHERE e.enrollment_id = s.enrollment_id " + + " AND s.month = ? " + + " AND s.year = ? )" + + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); + + 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); + } } \ No newline at end of file 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 new file mode 100644 index 0000000..99c08aa --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/CompletedApiController.java @@ -0,0 +1,56 @@ +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 new file mode 100644 index 0000000..5d08abb --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DashboardApiController.java @@ -0,0 +1,241 @@ +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.stereotype.Controller; +import org.springframework.ui.Model; +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 in.gov.chennaicorporation.gccoffice.pensioner.service.DashboardApiService; +@RestController +public class DashboardApiController { + @Autowired + private DashboardApiService dashboardApiService; + + @GetMapping("/dashboard") + @ResponseBody + public List> getDashboardData() { + + return dashboardApiService.fetchCategoryCounts(); + } + /*@GetMapping("/dashboardsearch") + @ResponseBody + public List> fetchDashboardData( + @RequestParam(required = false) String startdate, + @RequestParam(required = false) String enddate) { + System.out.println("Endpoint hit with startdate: " + startdate + ", enddate: " + enddate); + try { + return dashboardApiService.fetchCategorysearchCounts(startdate, enddate); + } catch (Exception e) { + e.printStackTrace(); // Print fetchCategoryCounts stack trace to the logs + throw e; // Rethrow the exception to propagate the 500 error + } + } + @GetMapping("/categoryCounts") + public List> getCategoryCounts() { + return dashboardApiService.fetchCategoryCounts(); + } + + + @GetMapping("/getEmpNoByFileName") + public List> getEmployeeDetails(@RequestParam("file_id") String FileId) { + System.out.println("before fetch"); + return dashboardApiService.getEmployeeDetails(FileId); + } + @GetMapping("/stageWiseCounts") + public ResponseEntity>> getStageWiseCounts() { + List> stageWiseCounts = dashboardApiService.getStageWiseCounts(); + return ResponseEntity.ok(stageWiseCounts); + }*/ + + @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("/deparmentdashboard") + @ResponseBody + public List> getDepartmentDashboardData(@RequestParam(required = false) String deptId) { + System.out.println("deptid"+ deptId); + return dashboardApiService.DepartmenfetchCategoryCounts(deptId); + } + + + /* @GetMapping("/deparmentcategoryCounts") + public List> getDepartmenCategoryCounts(@RequestParam(required = false) String deptId) { + return dashboardApiService.DepartmenfetchCategoryCounts(deptId); + } + //DepartmentstageWiseCounts + + @GetMapping("/DepartmentstageWiseCounts") + public ResponseEntity>> getDepartmentStageWiseCounts(@RequestParam(required = false) String deptId) { + List> stageWiseCounts = dashboardApiService.getDepartmentStageWiseCounts(deptId); + return ResponseEntity.ok(stageWiseCounts); + }*/ + + + @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("/pensiondashboardsearch") + @ResponseBody + public List> fetchpensionDashboardData( + @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.fetchDeparmentCategorysearchCounts(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 + } + }*/ + + + /* @GetMapping("/pensioncategoryCounts") + public List> getpensionCategoryCounts( + @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.DepartmenfetchDepartmentCategoryCounts(deptId, startDate, endDate); + }*/ + + + /* @GetMapping("/pensionstageWiseCounts") + public ResponseEntity>> getpensionStageWiseCounts( + @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.getDepartmentStageWiseCounts(deptId, startDate, endDate); + return ResponseEntity.ok(stageWiseCounts); + }*/ + + @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 new file mode 100644 index 0000000..05c6382 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentForwardApiController.java @@ -0,0 +1,129 @@ +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 new file mode 100644 index 0000000..01b4889 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentMainController.java @@ -0,0 +1,720 @@ +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 new file mode 100644 index 0000000..e9c40e2 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentReceivedApiController.java @@ -0,0 +1,176 @@ +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 new file mode 100644 index 0000000..d175d6b --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptAuditApiController.java @@ -0,0 +1,189 @@ +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 new file mode 100644 index 0000000..6960486 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptPartiallyCompApiController.java @@ -0,0 +1,110 @@ +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 new file mode 100644 index 0000000..396f36a --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DropdownApiController.java @@ -0,0 +1,46 @@ +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 new file mode 100644 index 0000000..e5eaa9c --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingApiController.java @@ -0,0 +1,120 @@ +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 new file mode 100644 index 0000000..22b4fae --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingMainController.java @@ -0,0 +1,60 @@ +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 new file mode 100644 index 0000000..e20d452 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/NewEntryAPIController.java @@ -0,0 +1,334 @@ +package in.gov.chennaicorporation.gccoffice.pensioner.controller; + +import java.time.LocalDate; + +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +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()); + + 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 new file mode 100644 index 0000000..272bfef --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PendencyAutoConversionApiController.java @@ -0,0 +1,201 @@ +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 new file mode 100644 index 0000000..62033b2 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionAuditApiController.java @@ -0,0 +1,134 @@ +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 new file mode 100644 index 0000000..ce2597f --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionPartiallyCompApiController.java @@ -0,0 +1,110 @@ +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 new file mode 100644 index 0000000..239c314 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionReceivedApiController.java @@ -0,0 +1,94 @@ +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 new file mode 100644 index 0000000..9684952 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionerMainController.java @@ -0,0 +1,625 @@ +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 new file mode 100644 index 0000000..77570cc --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReceivedDeptProvisionalApiController.java @@ -0,0 +1,145 @@ +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 new file mode 100644 index 0000000..85b502d --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReportApiController.java @@ -0,0 +1,143 @@ +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 new file mode 100644 index 0000000..7e78063 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReturnFromAuditApiController.java @@ -0,0 +1,129 @@ +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 new file mode 100644 index 0000000..31b1cf0 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/scheduler/PendencyAutoConversionScheduler.java @@ -0,0 +1,229 @@ +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 new file mode 100644 index 0000000..f938d5d --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/CompletedService.java @@ -0,0 +1,180 @@ +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 new file mode 100644 index 0000000..a96b3ab --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DashboardApiService.java @@ -0,0 +1,402 @@ +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 new file mode 100644 index 0000000..252f664 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentForwardService.java @@ -0,0 +1,221 @@ +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 new file mode 100644 index 0000000..9873dea --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DepartmentReceivedService.java @@ -0,0 +1,692 @@ +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(); + + file_entry_type="FILE_COMPLETED"; + } + 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 new file mode 100644 index 0000000..0cf552c --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptAuditService.java @@ -0,0 +1,306 @@ +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 new file mode 100644 index 0000000..25fe2e9 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DeptPartiallyCompService.java @@ -0,0 +1,363 @@ +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 new file mode 100644 index 0000000..f23e806 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DropdownService.java @@ -0,0 +1,45 @@ +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 new file mode 100644 index 0000000..74ff421 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/FileClosingService.java @@ -0,0 +1,200 @@ +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 new file mode 100644 index 0000000..73c0e75 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/GetFileStatusService.java @@ -0,0 +1,141 @@ +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 new file mode 100644 index 0000000..6620a57 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/NewEntryService.java @@ -0,0 +1,949 @@ +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 new file mode 100644 index 0000000..5961f4f --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PendencyAutoConversionService.java @@ -0,0 +1,280 @@ +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 new file mode 100644 index 0000000..1c1501e --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionAuditService.java @@ -0,0 +1,235 @@ +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 new file mode 100644 index 0000000..c7b3574 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionPartiallyCompService.java @@ -0,0 +1,335 @@ +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 new file mode 100644 index 0000000..a784dab --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/PensionReceivedService.java @@ -0,0 +1,388 @@ +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 new file mode 100644 index 0000000..e59336a --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReceivedDeptProvisionalService.java @@ -0,0 +1,241 @@ +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 new file mode 100644 index 0000000..a54b98f --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReportApiService.java @@ -0,0 +1,579 @@ +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 new file mode 100644 index 0000000..e4cdaac --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/ReturnFromAuditService.java @@ -0,0 +1,220 @@ +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").toString(); + 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/school/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/school/.DS_Store new file mode 100644 index 0000000..7e00811 Binary files /dev/null and b/src/main/java/in/gov/chennaicorporation/gccoffice/school/.DS_Store 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 new file mode 100644 index 0000000..37160aa --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/BuildingAssetController.java @@ -0,0 +1,624 @@ +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()); + + buildingAssetService.saveRoomDetails(room_type, room_num, building_id, floors_id, school_id); + return "Rooms Mapped Sucessfully"; + } 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()); + + 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"; + } + } + + + + // 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"); + 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 = 0; + int unMap = unMapped+mapped; + 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"); + 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 = 0; + int unMap = unMapped+mapped; + buildingAssetService.updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); + }*/ + 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); + + + if(!staffStrength.isEmpty()) { + return ResponseEntity.ok(Map.of("status", "OK","staffStrength", staffStrength)); + } + else { + return ResponseEntity.ok(Map.of("status", "NEW","staffStrength", staffStrength)); + } + + } 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 new file mode 100644 index 0000000..4924313 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/DropdownsController.java @@ -0,0 +1,499 @@ +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())); + } + } + +} 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 new file mode 100644 index 0000000..96d52de --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/MainController.java @@ -0,0 +1,127 @@ +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("/itassets") +// public String itassets(Model model) { +// +// System.out.println("okokokok==="); +// +// return "modules/school/itassets"; +// } + + @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"; + } +} \ 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 new file mode 100644 index 0000000..10ef794 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolPropertyController.java @@ -0,0 +1,716 @@ +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") Boolean 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("school_id") int school_id) { + + return schoolPropertyService.saveStudentStrength(total_students, total_girls, total_boys, others, 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("total_toiletBlocks") int total_toiletBlocks, + @RequestParam("total_male_urinals") int total_male_urinals, + @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_wc_male, total_wc_female, + total_diffAbled_toilet, is_napkins, school_id); + } + +// For Kitchen + @PostMapping(value = "/saveKitchen") + public String saveKitchen(@RequestParam(value = "is_cmbfs") Boolean is_cmbfs, + @RequestParam(value = "is_cmbfsIndividual", required = false) Boolean is_cmbfsIndividual, + @RequestParam(value = "is_noonmeal") Boolean is_noonmeal, + @RequestParam(value = "is_noonIndividual", required = false) Boolean is_noonIndividual, + @RequestParam(value = "is_vegGarden", required = false) Boolean is_vegGarden, + @RequestParam(value = "is_anganwadi") Boolean is_anganwadi, + @RequestParam(value = "anganwadi_unique", required = false) String anganwadi_unique, + @RequestParam(value = "is_anganwadiIndividual", required = false) Boolean is_anganwadiIndividual, + @RequestParam(value = "school_id") int school_id) { + + if (anganwadi_unique != null && anganwadi_unique.trim().isEmpty()) { + anganwadi_unique = null; + } + + return schoolPropertyService.saveKitchen(is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, + is_vegGarden, is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id); + } + +// 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); + } + } + + // 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("/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!"; + } + + // 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") Boolean 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("school_id") int school_id) { + System.out.println("Update Request => total: " + total_students + ", boys: " + total_boys + ", girls: " + + total_girls + ", others: " + others + ", school_id: " + school_id); + try { + return schoolPropertyService.updateStudentDetails(total_students, total_girls, total_boys, others, + 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 String updateKitchenDetails(@RequestParam(value = "is_cmbfs") Boolean is_cmbfs, + @RequestParam(value = "is_cmbfsIndividual", required = false) Boolean is_cmbfsIndividual, + @RequestParam(value = "is_noonmeal") Boolean is_noonmeal, + @RequestParam(value = "is_noonIndividual", required = false) Boolean is_noonIndividual, + @RequestParam(value = "is_vegGarden", required = false) Boolean is_vegGarden, + @RequestParam(value = "is_anganwadi") Boolean is_anganwadi, + @RequestParam(value = "anganwadi_unique", required = false) String anganwadi_unique, + @RequestParam(value = "is_anganwadiIndividual", required = false) Boolean is_anganwadiIndividual, + @RequestParam(value = "school_id") int school_id) { + try { + + return schoolPropertyService.updateKitchenDetails(is_cmbfs, is_cmbfsIndividual, is_noonmeal, + is_noonIndividual, is_vegGarden, is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id); + + } catch (Exception e) { + e.printStackTrace(); + return "Error"; + } + + } + + @GetMapping("/checkKitchenDetails") + public ResponseEntity checkKitchenDetails(@RequestParam int school_id) { + + Map kitchenDetails = schoolPropertyService.checkKitchenDetails(school_id); + + Map result = new HashMap<>(); + result.put("Message", "Success"); + result.put("Data", kitchenDetails); + + return ResponseEntity.ok(Collections.singletonList(result)); + } + + @PostMapping(value = "/updateStaffDetails") + public String updateStaffDetails(@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 school_id) { + try { + + return schoolPropertyService.updateStaffDetails(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); + + } catch (Exception e) { + e.printStackTrace(); + return "Error"; + } + + } + /* + * @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; + 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.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("total_toiletBlocks") int total_toiletBlocks, + @RequestParam("total_male_urinals") int total_male_urinals, + @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_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 master = qty + master_qty; + int unmapped = master_qty + unmapped_asset; + return schoolPropertyService.updateAssetMaster(assetMasterId, master, asset_id, unmapped); + + + } catch (Exception e) { + e.printStackTrace(); + return "Error"; + } + } + +} 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 new file mode 100644 index 0000000..7885101 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Controller/SchoolReportController.java @@ -0,0 +1,48 @@ +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); + } +} 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 new file mode 100644 index 0000000..93671dc --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/BuildingAssetService.java @@ -0,0 +1,1090 @@ +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.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 + public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(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(); + } + + } + + 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"); + 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 = 0; + int unMap = unMapped+mapped; + 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"); + 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 = 0; + int unMap = unMapped+mapped; + updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); + } + */ + 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); + + editRooms(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 editRooms(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"); + 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 = 0; + int unMap = unMapped+mapped; + 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"); + 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 = 0; + int unMap = unMapped+mapped; + updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType); + } + */ + 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, " + // ✅ 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.room_id = ? AND rd.is_active = 1 AND rd.is_delete = 0"; + + return jdbcTemplate.queryForMap(sql, roomId); + } + + @Transactional + public void editRoom(int room_type, String room_num, int building_id, int floors_id, int school_id, int room_id) { + String sql = "UPDATE room_details SET room_type = ?, room_num = ?, building_id = ?, floors_id = ?, school_id = ? WHERE room_id = ? "; + try { + jdbcTemplate.update(sql, room_type, room_num, building_id, floors_id, school_id, 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\r\n" + + "WHERE m.id = ?"; + 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(); + + } + } + + // checking for view + public List> getStudentStrengthBySchoolId(@RequestParam int schoolId) { + String sql = "SELECT total_boys, total_girls, others, total_students FROM student_strength WHERE school_id = ?"; + + return jdbcTemplate.queryForList(sql, schoolId); + } + + public List> getotherdetailsBySchoolId(@RequestParam int schoolId) { + String sql = "select*from school_buildup_area where school_id=?"; + + return jdbcTemplate.queryForList(sql, schoolId); + } + + public List> getStaffStrengthBySchoolId(@RequestParam int schoolId) { + String sql = "SELECT * FROM staff_strength_1 WHERE school_id = ?"; + + 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 { + return jdbcTemplate.queryForMap(sql, school_id, sub_asset_id); + } catch (Exception e) { + e.printStackTrace(); + return Map.of(); + } + } + */ + @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 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 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 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 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 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 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"; + } + } + + + + +} 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 new file mode 100644 index 0000000..1a6c32b --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/DropdownsService.java @@ -0,0 +1,188 @@ +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); + } + +} 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 new file mode 100644 index 0000000..6445db8 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolPropertyService.java @@ -0,0 +1,963 @@ +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.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); + } + + @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 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 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"; +// } +// } + + @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 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 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 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 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(); + } + } + + + @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 int saveDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell, + Integer borewell_count, Boolean is_storage, int school_id) { + String sql = "INSERT INTO drinking_water (is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id) 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); + 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(); + } + + } + + @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 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 ward) { + String sql = "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 = ?" + + " AND (? = '' OR s.udise = ?)" + + " AND (? = '' OR s.category = ?)" + + " AND (? = '' OR s.zone = ?)" + + " AND (? = '' OR s.division = ?)"; + + return jdbcTemplate.queryForList( + sql, + userId, + udise, udise, + category, category, + zone, zone, + ward, ward + ); + } + @Transactional + public String updateOtherDetails(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 = "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 school_id) { + String sql = "UPDATE student_strength SET total_students = ?, total_girls = ?, total_boys = ?, others = ? WHERE school_id = ? "; + try { + jdbcTemplate.update(sql, total_students, total_girls, total_boys, others, school_id); + return "Success"; + }catch (DataAccessException e) { + e.printStackTrace(); + return "Error"; + } + } + + @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(); + } + } + 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" +// + "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 = ?"; +// try { +// return jdbcTemplate.queryForList(sql, school_id); +// } catch (Exception e) { +// e.printStackTrace(); +// return List.of(); +// } +// } + + @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> checkEquipmentDetails(int school_id) { +// String sql = "select 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 = ?"; +// try { +// return jdbcTemplate.queryForList(sql, school_id); +// } catch (Exception e) { +// e.printStackTrace(); +// return List.of(); +// } +// } + //ajith + 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(); + } + } + +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(); + + } + + } + + @Transactional + public String updateKitchenDetails(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 = "UPDATE kitchen SET is_cmbfs = ?, is_cmbfsIndividual = ?, is_noonmeal = ?, is_noonIndividual = ?, is_vegGarden = ?, is_anganwadi = ?, anganwadi_unique = ?, is_anganwadiIndividual = ? WHERE school_id = ? "; + try { + jdbcTemplate.update(sql, is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden, + is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id); + return "Success"; + } catch (DataAccessException e) { + e.printStackTrace(); + return "Error"; + } + } + @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 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"; + } + } + @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 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 " + + " INNER JOIN " + + " water_supply ws ON dw.drinking_water_id = ws.drinking_water_id " + + " INNER JOIN " + + " source_water sw ON ws.source_water_id = sw.source_water_id " + + " 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 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) { + System.out.println("===================helooo================="); + + 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(); + + } + } + + @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(); + } + } + + + + @Transactional + public List> checkWaterStotage(int school_id) { + String sql = " select wst.water_storage_id, wst.capacity, wstm.storage_type" + + " FROM " + + " drinking_water dw " + + " INNER JOIN" + + " water_storage wst ON dw.drinking_water_id = wst.drinking_water_id " + + "INNER JOIN" + + " 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> 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 String updateToiletDetails(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 = "UPDATE toilet SET total_toiletBlocks = ?, total_male_urinals = ?, total_wc_male = ?, total_wc_female = ?, total_diffAbled_toilet = ?, is_napkins = ? WHERE school_id = ? "; + try { + jdbcTemplate.update(sql, total_toiletBlocks, total_male_urinals, 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 " + + " 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 " + + " 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"; + } + } + + + + +} 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 new file mode 100644 index 0000000..842d7d4 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/school/Service/SchoolReportService.java @@ -0,0 +1,290 @@ +package in.gov.chennaicorporation.gccoffice.school.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.dao.DataAccessException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +@Service +public class SchoolReportService { + private JdbcTemplate jdbcTemplate; + + @Autowired + public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(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 AS zone FROM school_list WHERE udise In(" + udise + ")"; + 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 = ?"; + 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); + } + } + 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()) { + 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(); + } + } +} diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java b/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java index 1d393c4..c7f79e4 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/service/GetMappingUserDetails.java @@ -37,8 +37,11 @@ public class GetMappingUserDetails { @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()) { @@ -51,6 +54,7 @@ public class GetMappingUserDetails { return officerMasterId != null ? officerMasterId.toString() : null; } } catch (DataAccessException e) { + e.printStackTrace(); return null; // Handle error appropriately } diff --git a/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/.DS_Store b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/.DS_Store new file mode 100644 index 0000000..005c9d2 Binary files /dev/null and b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/.DS_Store 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 new file mode 100644 index 0000000..5fa1bb0 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/MainController.java @@ -0,0 +1,38 @@ +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 new file mode 100644 index 0000000..3d222be --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/VehicleApiController.java @@ -0,0 +1,94 @@ +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 new file mode 100644 index 0000000..3ee13af --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/controller/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..3871804 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..3766624 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java @@ -0,0 +1,421 @@ +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; + + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + break; + default: + System.out.println("TempID ("+tempid+") is unknown"); + } + + if (!urlString.isBlank()) { + String response = sendWhatsAppMessage(urlString); + 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 new file mode 100644 index 0000000..0e75932 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..e75b544 Binary files /dev/null and b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/.DS_Store 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 new file mode 100644 index 0000000..184a45b --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/APIController.java @@ -0,0 +1,218 @@ +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 new file mode 100644 index 0000000..ff27e24 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/MainController.java @@ -0,0 +1,138 @@ +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 new file mode 100644 index 0000000..1e3a329 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/controller/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..927d807 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/ComplaintType.java @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000..8263f02 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/data/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..1440aeb --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/package-info.java @@ -0,0 +1,7 @@ +/** + * + */ +/** + * + */ +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 new file mode 100644 index 0000000..6ff2cde --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/Petition.java @@ -0,0 +1,782 @@ +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 new file mode 100644 index 0000000..18f567c --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/PetitionMaster.java @@ -0,0 +1,90 @@ +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 new file mode 100644 index 0000000..5d910b4 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_sabha/service/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..c763e4c Binary files /dev/null and b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/.DS_Store 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 new file mode 100644 index 0000000..f7ddcfc --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/APIController.java @@ -0,0 +1,201 @@ +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 new file mode 100644 index 0000000..77951a5 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/MainController.java @@ -0,0 +1,130 @@ +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 new file mode 100644 index 0000000..eed40c0 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/controller/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..4ff0c97 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/ComplaintType.java @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000..e7ec807 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/data/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..f6fade8 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/package-info.java @@ -0,0 +1,7 @@ +/** + * + */ +/** + * + */ +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 new file mode 100644 index 0000000..f76c202 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/Petition.java @@ -0,0 +1,309 @@ +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 new file mode 100644 index 0000000..4c9bbcc --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/ward_shaba/service/package-info.java @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..b7c592d Binary files /dev/null and b/src/main/java/in/gov/chennaicorporation/gccoffice/works/.DS_Store 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 new file mode 100644 index 0000000..558af51 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/APIContoller.java @@ -0,0 +1,904 @@ +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 index b648c22..1aa3336 100644 --- a/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/MainController.java +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/works/controller/MainController.java @@ -1,33 +1,225 @@ package in.gov.chennaicorporation.gccoffice.works.controller; -import java.util.List; +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 { - @GetMapping({"", "/", "/index", "/dashboard"}) - public String home(Model model) { - return "modules/works/index"; - } + 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); - @GetMapping("/erp-works-update") - public String CreateRequest(Model model) { + //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); - return "modules/works/erp-works-update"; + model.addAttribute("estid",estid); + return BasePath+"works_details_view_modal_page"; } - - @GetMapping("/nonerp-works-add") - public String nonErpCreateRequest(Model model) { + + @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 "modules/works/non-erp-works-add"; + + return BasePath+"project_status_update"; } + } 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 new file mode 100644 index 0000000..31535c7 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/ERPEstimateService.java @@ -0,0 +1,360 @@ +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=""; + + // Split the string using "_" + String[] parts = accessData.split("_"); + + if(!parts[0].equals("all")) { + where =" 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 + "`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 new file mode 100644 index 0000000..63eb477 --- /dev/null +++ b/src/main/java/in/gov/chennaicorporation/gccoffice/works/service/EstimateService.java @@ -0,0 +1,1693 @@ +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=""; + + // Split the string using "_" + String[] parts = accessData.split("_"); + + if(!parts[0].equals("all")) { + where =" ew.`ward` IN ("+parts[0]+") "; + } + if(!parts[1].equals("all")) { + if(!where.equals("")) + { + where = where + "AND ew.`department` IN ("+parts[1]+")"; + } + else { + where = where + "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/resources/application-local.properties b/src/main/resources/application-local.properties index e999929..e6efdd2 100644 --- a/src/main/resources/application-local.properties +++ b/src/main/resources/application-local.properties @@ -1 +1,3 @@ -assets.base-url=/assets/ \ No newline at end of file +assets.base-url=/assets/ + +fileBaseUrl=http://localhost:8064 diff --git a/src/main/resources/application-production.properties b/src/main/resources/application-production.properties index 964a916..6146ec0 100644 --- a/src/main/resources/application-production.properties +++ b/src/main/resources/application-production.properties @@ -1 +1,3 @@ -assets.base-url=/gcc/assets/ \ No newline at end of file +assets.base-url=/gcc/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 7a8e703..7b0618d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,5 +1,5 @@ -spring.profiles.active=local -#spring.profiles.active=production +#spring.profiles.active=local +spring.profiles.active=production #For Server production #assets.base-url=/gcc/assets/ #For local test @@ -102,3 +102,12 @@ 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 + diff --git a/src/main/resources/templates/fragments/modules/ward_sabha/modal-box.html b/src/main/resources/templates/fragments/modules/ward_sabha/modal-box.html new file mode 100644 index 0000000..38e0c8c --- /dev/null +++ b/src/main/resources/templates/fragments/modules/ward_sabha/modal-box.html @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/ward_sabha/petition_view_script.html b/src/main/resources/templates/fragments/modules/ward_sabha/petition_view_script.html new file mode 100644 index 0000000..5689940 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/ward_sabha/petition_view_script.html @@ -0,0 +1,293 @@ + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/ward_sabha/script.html b/src/main/resources/templates/fragments/modules/ward_sabha/script.html new file mode 100644 index 0000000..ca53ecf --- /dev/null +++ b/src/main/resources/templates/fragments/modules/ward_sabha/script.html @@ -0,0 +1,660 @@ + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/ward_sabha/search_form.html b/src/main/resources/templates/fragments/modules/ward_sabha/search_form.html new file mode 100644 index 0000000..e0f28b3 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/ward_sabha/search_form.html @@ -0,0 +1,19 @@ +
+
+
+ + + + + + + +
+
+
\ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/edit_stage_script.html b/src/main/resources/templates/fragments/modules/works/edit_stage_script.html new file mode 100644 index 0000000..98a867e --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/edit_stage_script.html @@ -0,0 +1,108 @@ + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/modal-box.html b/src/main/resources/templates/fragments/modules/works/modal-box.html new file mode 100644 index 0000000..5ff1ab1 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/modal-box.html @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/script.html b/src/main/resources/templates/fragments/modules/works/script.html new file mode 100644 index 0000000..d644483 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/script.html @@ -0,0 +1,185 @@ + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/search_form.html b/src/main/resources/templates/fragments/modules/works/search_form.html new file mode 100644 index 0000000..e0f28b3 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/search_form.html @@ -0,0 +1,19 @@ +
+
+
+ + + + + + + +
+
+
\ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/user_works_update_script.html b/src/main/resources/templates/fragments/modules/works/user_works_update_script.html new file mode 100644 index 0000000..d610397 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/user_works_update_script.html @@ -0,0 +1,239 @@ + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/user_works_view_script.html b/src/main/resources/templates/fragments/modules/works/user_works_view_script.html new file mode 100644 index 0000000..c37c4b3 --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/user_works_view_script.html @@ -0,0 +1,328 @@ + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/works/works_view_script.html b/src/main/resources/templates/fragments/modules/works/works_view_script.html new file mode 100644 index 0000000..bb2402e --- /dev/null +++ b/src/main/resources/templates/fragments/modules/works/works_view_script.html @@ -0,0 +1,120 @@ + + \ No newline at end of file diff --git a/src/main/resources/templates/modules/c_petition/complaint_list.html b/src/main/resources/templates/modules/c_petition/complaint_list.html index da824cc..1854c80 100644 --- a/src/main/resources/templates/modules/c_petition/complaint_list.html +++ b/src/main/resources/templates/modules/c_petition/complaint_list.html @@ -311,6 +311,17 @@ statusBadge = `${statusBadge}`; } var complaintRightBody = ""; + + var fileType_c = complaintDetails[0].file_type; + fileType_c = fileType_c.split("/").pop(); + var filetypeico_c = "file-lines"; + if(fileType_c=='pdf'){ + filetypeico_c = "file-pdf"; + } + else{ + filetypeico_c = "file-image"; + } + var complaintLeftBody = `

Complaint Details

@@ -348,6 +359,33 @@ + @@ -533,6 +571,7 @@ // Enable tooltips for all elements with data-toggle="tooltip" $('[data-toggle="tooltip"]').tooltip(); remove_loading(); // remove Loading + onSearchComplete(); } // Save New Action diff --git a/src/main/resources/templates/modules/callcenter/addcategory.html b/src/main/resources/templates/modules/callcenter/addcategory.html index 43c398c..e477a78 100644 --- a/src/main/resources/templates/modules/callcenter/addcategory.html +++ b/src/main/resources/templates/modules/callcenter/addcategory.html @@ -33,6 +33,18 @@ color: #fff; } +#addcategoryform .modal-body { + max-height: 500px; /* Set max height */ + overflow-y: auto; /* Enable vertical scrolling when content overflows */ +} + +#editCategoryModal .modal-body { + max-height: 500px; /* Set max height */ + overflow-y: auto; /* Enable vertical scrolling when content overflows */ +} + + + @@ -65,7 +77,7 @@
+ + + + + + + - - - - - - - + + @@ -249,13 +278,16 @@ className: 'btn btn-secondary' }, { - text: ' Add New Category', - className: 'btn btn-warning', - action: function () { - callAdd(); - } + + text: ' Add New Category', + className: 'btn btn-warning', + action: function () { + callAdd(); // Now it will work + } + + } - ]; + ]; $('#categoryDatatable').DataTable({ dom: 'Bftip', @@ -279,160 +311,601 @@ select: false, processing: false, }); + - // Function to show the modal and reset the form - function callAdd() { - // Reset the form inside the modal when opened - var form = $('#addCategoryForm'); - if (form.length) { - form[0].reset(); // Reset all form fields + // Show Modal + function callAdd() { + resetForm(); + $('#addcategoryform').modal({ backdrop: 'static', keyboard: false }); + $('#addcategoryform').modal('show'); } - // Show the modal with static backdrop and disabled keyboard close - $('#addcategoryform').modal({ - backdrop: 'static', - keyboard: false + // Reset Form + function resetForm() { + $('#addCategoryForm')[0].reset(); + $("#columnInputs .column-group:not(:first)").remove(); + $(".remove-column").hide(); + } + + //validateColumns + function validateColumns(columns) { + let columnSet = new Set(); + let regex = /^[A-Za-z0-9_ ]+$/; // Allow alphabets, numbers, underscores, and spaces + let invalidRegex = /^[_ ]+$/; // Match column names with only underscores and/or spaces + + for (let col of columns) { + if (!regex.test(col)) { + Swal.fire({ + title: "Validation Error", + text: "Column names must contain only alphabets (A-Z, a-z), numbers (0-9), underscores (_), and spaces.", + icon: "warning", + confirmButtonText: "OK" + }); + return false; + } + if (invalidRegex.test(col)) { + Swal.fire({ + title: "Validation Error", + text: "Column names cannot contain only spaces and underscores (_).", + icon: "warning", + confirmButtonText: "OK" + }); + return false; + } + let trimmedCol = col.trim().toLowerCase(); // Trim spaces for uniqueness check + if (columnSet.has(trimmedCol)) { + Swal.fire({ + title: "Validation Error", + text: "Duplicate column names are not allowed.", + icon: "warning", + confirmButtonText: "OK" + }); + return false; + } + columnSet.add(trimmedCol); + } + return true; +} + + + + + + // Add default fields on page load + /* var defaultFields = ` +
+
+ + + +
+
`; + $('#columnInputs').append(defaultFields); */ + + + var defaultFields = ` +
+
+ +
+
+
+
+ +
+
+ + `; + + $('#columnInputs').append(defaultFields); + + $('#addcategoryform').on('shown.bs.modal', function () { + $('#columnInputs').html(''); // Clear existing columns + $('#columnInputs').append(defaultFields); // Append default values }); - $('#addcategoryform').modal('show'); - } - // Handle the Create button click event - $('#createCategoryBtn').click(function () { - var categoryName = $('#categoryname').val().trim(); - - // Basic validation to ensure the category name is not empty - if (categoryName === '') { - Swal.fire({ - title: 'Validation Error', - text: 'Please enter a category name.', - icon: 'warning', - confirmButtonText: 'OK', - }); - return; - } - - // AJAX request to save the category - $.ajax({ - url: '/gcc/api/category/save', // Ensure the URL points to the correct endpoint - type: 'POST', - contentType: 'application/json', - data: JSON.stringify({ categoryname: categoryName }), // Ensure the key matches what backend expects - success: function (response) { - Swal.fire({ - title: 'Success', - text: 'Category saved successfully!', - icon: 'success', - confirmButtonText: 'OK', - }).then(function () { - $('#addcategoryform').modal('hide'); // Close the modal after successful save - location.reload(); // Reload the page to update the category list - }); - }, - error: function (error) { - Swal.fire({ - title: 'Error', - text: 'Error saving category: ' + error.responseText, - icon: 'error', - confirmButtonText: 'OK', - }); - } - }); - }); - - window.callEdit = function (categoryId) { - fetchCategoryDetails(categoryId); - return false; // Prevent default anchor click behavior - }; - - // Function to open the Edit Category Modal and populate it with current data - function fetchCategoryDetails(categoryId) { - // AJAX request to fetch category details by ID - $.ajax({ - url: '/gcc/api/category/showcategoryId', // Ensure this URL matches your API endpoint - type: 'GET', - data: { category_id: categoryId }, // Send the category ID as a request parameter - success: function (response) { - // Check if the response contains the category data - if (response) { - // Populate the form fields with the retrieved data - $('#categoryId').val(response.category_id); - $('#categoryName').val(response.category_name); - - // Show the edit modal - $('#editCategoryModal').modal({ - backdrop: 'static', - keyboard: false - }); - } else { - Swal.fire({ - title: 'Error', - text: 'Category not found.', - icon: 'error', - confirmButtonText: 'OK' - }); - } - }, - error: function (xhr, status, error) { - // Handle error if the API call fails - Swal.fire({ - title: 'Error', - text: 'Error fetching category details: ' + xhr.responseText, - icon: 'error', - confirmButtonText: 'OK' - }); - } - }); - - // Prevent the default action (if any) when the link is clicked - return false; - } + $('#addcategoryform').on('hidden.bs.modal', function () { + $('#categoryname').val(""); // Reset category name + $('#columnInputs').html(""); // Clear all columns + }); + $('#editCategoryModal').on('hidden.bs.modal', function () { + $('#editColumnInputs').html(''); // Clear all columns when modal is closed + $('#editaddColumnInputs').html(''); // Clear additional columns if applicable + }); + // Add More Column Fields + $('#addMoreColumn').click(function () { + + + var newColumnField = ` +
+
+ +
+
+ +
+
`; + $('#columnInputs').append(newColumnField); + $('.remove-column').show(); + }); - - // Event handler for the Save Changes button click in the edit modal - $('#updateCategoryButton').click(function () { - var categoryId = $('#categoryId').val(); - var categoryName = $('#categoryName').val().trim(); - - // Validate the input - if (categoryName === '') { - Swal.fire({ - title: 'Validation Error', - text: 'Please enter a category name.', - icon: 'warning', - confirmButtonText: 'OK' - }); - return; - } - - // AJAX request to update the category - $.ajax({ - url: '/gcc/api/category/update/' + categoryId, // Ensure this URL is correct and matches your API endpoint - type: 'PUT', - contentType: 'application/x-www-form-urlencoded', // Content type for form data - data: $.param({ categoryName: categoryName }), // Send category name as URL-encoded parameter - success: function (response) { - Swal.fire({ - title: 'Success', - text: 'Category updated successfully!', - icon: 'success', - confirmButtonText: 'OK' - }).then(function () { - $('#editCategoryModal').modal('hide'); // Hide the modal - location.reload(); // Reload the page to refresh the category list - }); - }, - error: function (xhr, status, error) { - Swal.fire({ - title: 'Error', - text: 'Error updating category: ' + xhr.responseText, - icon: 'error', - confirmButtonText: 'OK' - }); - } - }); - }); + // Remove Column Field + $(document).on('click', '.remove-column', function () { + $(this).closest('.column-group').remove(); + if ($('.column-group').length === 1) { + $('.remove-column').hide(); + } + }); + + $('#createCategoryBtn').click(function () { + var categoryName = $('#categoryname').val().trim(); + //var columnNames = $('.columnname').map(function () { + var columnNames = $('input[name="columns[]"]').map(function () { + return $(this).val().trim(); + }).get().filter(name => name !== ""); + + console.log("categoryName=", categoryName); + console.log("columnNames=", columnNames); + + if (categoryName === "") { + Swal.fire({ + title: "Validation Error", + text: "Please enter a category name.", + icon: "warning", + confirmButtonText: "OK" + }); + return; + } + + if (columnNames.length < 2) { + Swal.fire({ + title: "Validation Error", + text: "Please enter at least two column names.", + icon: "warning", + confirmButtonText: "OK" + }); + return; + } + + if (!validateColumns(columnNames)) { + return; + } + + $('#createCategoryBtn').prop('disabled', true).text('Processing...'); + + $.ajax({ + url: '/gcc/api/category/save', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify({ categoryname: categoryName, columns: columnNames }), + success: function (response) { + $('#createCategoryBtn').prop('disabled', false).text('Save Category'); + Swal.fire({ + title: "Success", + text: "Category saved successfully!", + icon: "success", + confirmButtonText: "OK" + }).then(function () { + $('#addcategoryform').modal('hide'); + $('#createCategoryBtn').prop('disabled', false).text('Save Category'); + location.reload(); + }); + }, + error: function (error) { + $('#createCategoryBtn').prop('disabled', false).text('Save Category'); + Swal.fire({ + title: "Error", + text: error.responseText, + icon: "error", + confirmButtonText: "OK" + }); + } + }); + }); + +/* $('#createCategoryBtn').click(function () { + var categoryName = $('#categoryname').val().trim(); + var columnNames = $('.columnname').map(function () { + return $(this).val().trim(); + }).get().filter(name => name !== ""); + console.log("categoryName=========="+categoryName); + console.log("columnNames=========="+columnNames); + // Validation: Ensure category name is not empty and at least two columns are provided + if (categoryName === "") { + Swal.fire({ + title: 'Validation Error', + text: 'Please enter a category name.', + icon: 'warning', + confirmButtonText: 'OK' + }); + return; + } + + if (columnNames.length < 2) { + Swal.fire({ + title: 'Validation Error', + text: 'Please enter at least two column names.', + icon: 'warning', + confirmButtonText: 'OK' + }); + return; + } + + + // Proceed with AJAX request if validation passes + $.ajax({ + url: '/gcc/api/category/save', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify({ categoryname: categoryName, columns: columnNames }), + success: function (response) { + Swal.fire({ + title: 'Success', + text: 'Category saved successfully!', + icon: 'success', + confirmButtonText: 'OK' + }).then(function () { + $('#addcategoryform').modal('hide'); + location.reload(); + }); + }, + error: function (error) { + Swal.fire({ + title: 'Error', + text: error.responseText, + icon: 'error', + confirmButtonText: 'OK' + }); + } + }); + }); */ + + // Function to fetch category details and populate the edit modal + window.callEdit = function (categoryId) { + fetchCategoryDetails(categoryId); + return false; + }; + + function fetchCategoryDetails(categoryId) { + $.ajax({ + url: '/gcc/api/category/showcategoryId', + type: 'GET', + data: { category_id: categoryId }, + success: function (response) { + if (response) { + $('#categoryId').val(response.category_id); + $('#showcategoryName').val(response.category_name); + + $('#editColumnInputs').empty(); + + $('#editaddColumnInputs').empty(); + + if (response.columns && response.columns.length > 0) { + response.columns.forEach(col => addEditColumnField(col.id, col.column_name)); + } else { + addEditColumnField(); + } + + $('#editCategoryModal').modal({ backdrop: 'static', keyboard: false }); + } else { + Swal.fire('Error', 'Category not found.', 'error'); + } + }, + error: function (xhr) { + Swal.fire('Error', 'Error fetching category details: ' + xhr.responseText, 'error'); + } + }); + } + + + + function addEditColumnField(id = "", value = "", containerId = "editColumnInputs") { + let removeButton = containerId === "editColumnInputs" + ? `` + : ``; + + let columnField = ` +
+ +
+ +
+
+ ${removeButton} +
+
`; + $('#' + containerId).append(columnField); + } + + + $('#addMoreEditColumn').click(function () { + addEditColumnField("", "", "editaddColumnInputs"); + }); + + $(document).ready(function () { + window.removeColumn = function (button, columnId) { + if (columnId) { + Swal.fire({ + title: "Are you sure?", + text: "This column will be permanently deleted!", + icon: "warning", + showCancelButton: true, + confirmButtonColor: "#d33", + cancelButtonColor: "#3085d6", + confirmButtonText: "Yes, delete it!" + }).then((result) => { + if (result.isConfirmed) { + $.ajax({ + url: '/gcc/api/category/deleteColumnById', + type: 'POST', + data: { columnId: columnId }, + success: function (response) { + if (response.success) { + $(button).closest('.column-group').remove(); + Swal.fire({ + title: "Deleted!", + text: "Column has been removed.", + icon: "success", + timer: 2000, // Auto-close after 2 seconds + showConfirmButton: false + }); + } else { + Swal.fire({ + title: "Error", + text: "Unable to delete column. Try again.", + icon: "error", + timer: 2000, // Auto-close after 2 seconds + showConfirmButton: false + }); + } + }, + error: function (xhr) { + Swal.fire("Error", "Something went wrong: " + xhr.responseText, "error"); + } + }); + } + }); + } else { + console.log("columnId=" + columnId); + Swal.fire("Error!", "Problem in columnId", "error"); + } + }; + }); + + + + // Event to remove column input dynamically + $(document).on('click', '.remove-column', function () { + $(this).closest('.column-group').remove(); + }); + + $('#updateCategoryButton').click(function () { + let categoryId = parseInt($('#categoryId').val(), 10); + + let existingColumns = []; + $('#editColumnInputs .column-group').each(function () { + let columnId = parseInt($(this).find('.showcolumnId').val(), 10); + let columnName = $(this).find('.showcolumnname').val(); + if (columnName.trim() !== "") { + existingColumns.push({ id: columnId, name: columnName }); + } + }); + + let newColumns = []; + $('#editaddColumnInputs .column-group').each(function () { + let columnName = $(this).find('.showcolumnname').val(); + if (columnName.trim() !== "") { + newColumns.push({ name: columnName }); + } + }); + + console.log("Category ID:", categoryId); + console.log("Existing Columns:", existingColumns); + console.log("New Columns:", newColumns); + + let allColumnNames = [...existingColumns.map(col => col.name), ...newColumns.map(col => col.name)]; + + console.log("allColumnNames="+allColumnNames); + + if ((existingColumns.length + newColumns.length) < 2) { + Swal.fire({ + title: "Info", + text: "You must have at least 2 columns!", + icon: "info", + confirmButtonText: "OK" + }); + return; + } + + if (!validateColumns(allColumnNames)) { + return; + } + + $('#updateCategoryButton').prop('disabled', true).text('Processing'); + + $.ajax({ + url: '/gcc/api/category/updateCategoryColumns', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify({ categoryId: categoryId, columns: existingColumns }), + success: function (response) { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + if (response.success) { + Swal.fire({ + title: "Success!", + text: "Category updated successfully!", + icon: "success", + showConfirmButton: false, + timer: 2000 + }).then(() => { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + location.reload(); + }); + } else { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + Swal.fire({ + title: "Error", + text: "Unable to update column. Try again.", + icon: "error", + showConfirmButton: true + }); + } + }, + error: function (xhr) { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + Swal.fire("Error", "Failed to update category: " + xhr.responseText, "error"); + } + }); + + if (newColumns.length > 0) { + $('#updateCategoryButton').prop('disabled', true).text('Processing'); + $.ajax({ + url: '/gcc/api/category/addNewColumns', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify({ categoryId: categoryId, columns: newColumns }), + success: function (response) { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + if (response.success) { + Swal.fire({ + title: "Success!", + text: "Category updated successfully!", + icon: "success", + showConfirmButton: false, + timer: 2000 + }).then(() => { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + location.reload(); + }); + } else { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + Swal.fire({ + title: "Error", + text: "Unable to update column. Try again.", + icon: "error", + showConfirmButton: true + }); + } + }, + error: function (xhr) { + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + Swal.fire("Error", "Failed to add new columns: " + xhr.responseText, "error"); + } + }); + $('#updateCategoryButton').prop('disabled', false).text('Save Changes'); + } + }); + + +/* $('#updateCategoryButton').click(function () { + let categoryId = parseInt($('#categoryId').val(), 10); + + // Collect existing columns + let existingColumns = []; + $('#editColumnInputs .column-group').each(function () { + let columnId = parseInt($(this).find('.showcolumnId').val(), 10); + let columnName = $(this).find('.showcolumnname').val(); + if (columnName.trim() !== "") { + existingColumns.push({ id: columnId, name: columnName }); + } + }); + + // Collect new columns + let newColumns = []; + $('#editaddColumnInputs .column-group').each(function () { + let columnName = $(this).find('.showcolumnname').val(); + if (columnName.trim() !== "") { + newColumns.push({ name: columnName }); + } + }); + + // Debugging: Log values before AJAX calls + console.log("Category ID:", categoryId); + console.log("Existing Columns:", existingColumns); + console.log("New Columns:", newColumns); + + if ((existingColumns.length + newColumns.length) < 2) { + Swal.fire({ + title: "Info", + text: "You must have at least 2 columns!", + icon: "info", + confirmButtonText: "OK" + }); + return; // Stop execution if condition fails + } + + // 1️⃣ Send existing columns update AJAX + $.ajax({ + url: '/gcc/api/category/updateCategoryColumns', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify({ categoryId: categoryId, columns: existingColumns }), + success: function (response) { + + if (response.success) { + + Swal.fire({ + title: "Success!", + text: "Category updated successfully!", + icon: "success", + showConfirmButton: false, + timer: 2000 // Show message for 2 seconds + }).then(() => { + location.reload(); // Reload the page after SweetAlert closes + }); + } else { + Swal.fire({ + title: "Error", + text: "Unable to update column. Try again.", + icon: "error", + showConfirmButton: true + }); + } + }, + error: function (xhr) { + Swal.fire("Error", "Failed to update category: " + xhr.responseText, "error"); + } + }); + + // 2️⃣ Send new columns addition AJAX (only if there are new columns) + if (newColumns.length > 0) { + $.ajax({ + url: '/gcc/api/category/addNewColumns', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify({ categoryId: categoryId, columns: newColumns }), + success: function (response) { + if (response.success) { + + Swal.fire({ + title: "Success!", + text: "Category updated successfully!", + icon: "success", + showConfirmButton: false, + timer: 2000 // Show message for 2 seconds + }).then(() => { + location.reload(); // Reload the page after SweetAlert closes + }); + } else { + Swal.fire({ + title: "Error", + text: "Unable to update column. Try again.", + icon: "error", + showConfirmButton: true + }); + } + }, + error: function (xhr) { + Swal.fire("Error", "Failed to add new columns: " + xhr.responseText, "error"); + } + }); + } + }); */ + + + window.openDeleteModal = function (categoryId) { @@ -440,7 +913,6 @@ fetchDeleteCategoryDetails(); return false; // Prevent default anchor click behavior }; - function fetchDeleteCategoryDetails() { Swal.fire({ @@ -492,8 +964,6 @@ }); } - - }); diff --git a/src/main/resources/templates/modules/callcenter/agentscampaign.html b/src/main/resources/templates/modules/callcenter/agentscampaign.html index 25159c5..72bbc3e 100644 --- a/src/main/resources/templates/modules/callcenter/agentscampaign.html +++ b/src/main/resources/templates/modules/callcenter/agentscampaign.html @@ -2,38 +2,51 @@ - - - -
- -
- - -
- -
- -
-
-
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
S.NoCategoryCampaignNameCalls AssignedCalls CompletedCalls Pending
+
-
- -
- - - - - - - - - - - - + + + +
+
+
+ + + +
+ + +
+
+ + +
+
+ +
+ +
+ +
+
+
S.NoCategoryCampaignNameCalls AssignedCalls PendingCalls CompletedFollow upsStart CallsFurther Calls
+ + + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - -
S.NoNameMobileNumberViewDetailsCallstatusRemarksSubmit
- - - - -
+ + + +
S.NoCategoryCampaignNameCalls AssignedCalls PendingCalls CompletedFollow upsStart CallsFurther Calls
-
- - - - - + + + + + - - - - -
+ + + + + + + + +
+ + + - - -
+ + + + + + + + +
+ + + + + + + - - - - - - + + + diff --git a/src/main/resources/templates/modules/callcenter/attendancereport.html b/src/main/resources/templates/modules/callcenter/attendancereport.html index cc58f84..5c65a74 100644 --- a/src/main/resources/templates/modules/callcenter/attendancereport.html +++ b/src/main/resources/templates/modules/callcenter/attendancereport.html @@ -54,7 +54,7 @@
-
+
@@ -209,7 +209,7 @@ function resetDate() { document.getElementById("toDate").value = ""; // Redirect to the endpoint without parameters to reset the page - window.location.href = "/gcc/callcenter/attendancereport"; + window.location.href = "/gcc/callcenterattendance/attendancereport"; } //Function to show the loader when the form is submitted diff --git a/src/main/resources/templates/modules/callcenter/campaignlist.html b/src/main/resources/templates/modules/callcenter/campaignlist.html index 7f6ca42..2c5d100 100644 --- a/src/main/resources/templates/modules/callcenter/campaignlist.html +++ b/src/main/resources/templates/modules/callcenter/campaignlist.html @@ -4,6 +4,20 @@ @@ -36,7 +50,7 @@
@@ -120,8 +134,8 @@ Category Event Date Description - Agents Performance - Status + Status + Action @@ -134,33 +148,33 @@ - - - - - - - + + + + + + Closed + + + + + + + + + + + + + + + + + - - - S.No - Name - Category - Event Date - Description - Agents Performance - Status - - - - +
@@ -171,126 +185,205 @@ + + +
- - -