Browse Source

New Module Added

New module updated
main
Balaji 1 year ago
parent
commit
adfcec0f2a
  1. BIN
      .DS_Store
  2. BIN
      bin/target/gccoffice-0.0.1.jar
  3. BIN
      gccoffice_uploads/.DS_Store
  4. BIN
      gccoffice_uploads/app_uploads/.DS_Store
  5. BIN
      gccoffice_uploads/com_petition/.DS_Store
  6. BIN
      gccoffice_uploads/gcc_minutes_files_uploads/.DS_Store
  7. BIN
      gccoffice_uploads/gcc_works_files/.DS_Store
  8. BIN
      gccoffice_uploads/gcc_works_files/2025/.DS_Store
  9. BIN
      gccoffice_uploads/gcc_works_files/works/.DS_Store
  10. BIN
      gccoffice_uploads/gcc_works_files/works/erp/.DS_Store
  11. BIN
      gccoffice_uploads/gcc_works_files/works/nonerp/.DS_Store
  12. BIN
      gccoffice_uploads/gcc_works_files/works/projectStatus/.DS_Store
  13. BIN
      gccoffice_uploads/gcc_works_files2025/.DS_Store
  14. BIN
      gccoffice_uploads/m_petition/.DS_Store
  15. BIN
      gccoffice_uploads/m_petition/m_action_file/.DS_Store
  16. BIN
      gccoffice_uploads/zh_petition/.DS_Store
  17. 8
      pom.xml
  18. 84
      src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/Petition.java
  19. 17
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentAssignAPIController.java
  20. 181
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/AgentsAPIController.java
  21. 521
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignAPIController.java
  22. 29
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignDropdownApiController.java
  23. 100
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CampaignReportAPIController.java
  24. 229
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/CategoryAPIController.java
  25. 57
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/controller/MainController.java
  26. 246
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AddcategoryServices.java
  27. 119
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentAssignService.java
  28. 403
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/AgentsService.java
  29. 29
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignDropdownApiService.java
  30. 494
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignReportService.java
  31. 492
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenter/service/CampaignService.java
  32. 36
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceApiController.java
  33. 71
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/AttendanceMainController.java
  34. 441
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintController.java
  35. 31
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ComplaintStatusMainController.java
  36. 10
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/FollowUpController.java
  37. 10
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/InprogresscallController.java
  38. 136
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java
  39. 10
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/PublicFollowUpController.java
  40. 118
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAPIController.java
  41. 208
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsApiController.java
  42. 47
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAdminSettingsMainController.java
  43. 15
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentAssignAPIController.java
  44. 18
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentsAPIController.java
  45. 30
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcCallsController.java
  46. 26
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcPgrComplaintsMainController.java
  47. 6
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java
  48. 58
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/ReportsMainController.java
  49. 349
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaApiController.java
  50. 41
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/SocialMediaMainController.java
  51. 10
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java
  52. 14
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/FollowUpService.java
  53. 6
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/InprogresscallService.java
  54. 24
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java
  55. 73
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentAssignService.java
  56. 16
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAgentsService.java
  57. 22
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java
  58. 218
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcService.java
  59. 57
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcTaskListService.java
  60. 16
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java
  61. 60
      src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/StatusCountService.java
  62. 174
      src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/DumpRegistrationAPIController.java
  63. 75
      src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/controller/MainController.java
  64. 161
      src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/OfficerService.java
  65. 40
      src/main/java/in/gov/chennaicorporation/gccoffice/cdwaste/service/SMSService.java
  66. 44
      src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/controller/APIController.java
  67. 104
      src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/Petition.java
  68. 1
      src/main/java/in/gov/chennaicorporation/gccoffice/configuration/AppConfig.java
  69. 91
      src/main/java/in/gov/chennaicorporation/gccoffice/configuration/DataSourceConfig.java
  70. 2
      src/main/java/in/gov/chennaicorporation/gccoffice/configuration/SecurityConfig.java
  71. 22
      src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java
  72. 1
      src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemAccessEntity.java
  73. 12
      src/main/java/in/gov/chennaicorporation/gccoffice/entity/SubMenuItemEntity.java
  74. 13
      src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/controller/APIController.java
  75. 194
      src/main/java/in/gov/chennaicorporation/gccoffice/m_petition/service/Petition.java
  76. 57
      src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java
  77. 77
      src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmController.java
  78. 139
      src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java
  79. 56
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/CompletedApiController.java
  80. 241
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DashboardApiController.java
  81. 129
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentForwardApiController.java
  82. 720
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentMainController.java
  83. 176
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DepartmentReceivedApiController.java
  84. 189
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptAuditApiController.java
  85. 110
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DeptPartiallyCompApiController.java
  86. 46
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/DropdownApiController.java
  87. 120
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingApiController.java
  88. 60
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/FileClosingMainController.java
  89. 334
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/NewEntryAPIController.java
  90. 201
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PendencyAutoConversionApiController.java
  91. 134
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionAuditApiController.java
  92. 110
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionPartiallyCompApiController.java
  93. 94
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionReceivedApiController.java
  94. 625
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/PensionerMainController.java
  95. 145
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReceivedDeptProvisionalApiController.java
  96. 143
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReportApiController.java
  97. 129
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/controller/ReturnFromAuditApiController.java
  98. 229
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/scheduler/PendencyAutoConversionScheduler.java
  99. 180
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/CompletedService.java
  100. 402
      src/main/java/in/gov/chennaicorporation/gccoffice/pensioner/service/DashboardApiService.java

BIN
.DS_Store

BIN
bin/target/gccoffice-0.0.1.jar

BIN
gccoffice_uploads/.DS_Store

BIN
gccoffice_uploads/app_uploads/.DS_Store

BIN
gccoffice_uploads/com_petition/.DS_Store

BIN
gccoffice_uploads/gcc_minutes_files_uploads/.DS_Store

BIN
gccoffice_uploads/gcc_works_files/.DS_Store

BIN
gccoffice_uploads/gcc_works_files/2025/.DS_Store

BIN
gccoffice_uploads/gcc_works_files/works/.DS_Store

BIN
gccoffice_uploads/gcc_works_files/works/erp/.DS_Store

BIN
gccoffice_uploads/gcc_works_files/works/nonerp/.DS_Store

BIN
gccoffice_uploads/gcc_works_files/works/projectStatus/.DS_Store

BIN
gccoffice_uploads/gcc_works_files2025/.DS_Store

BIN
gccoffice_uploads/m_petition/.DS_Store

BIN
gccoffice_uploads/m_petition/m_action_file/.DS_Store

BIN
gccoffice_uploads/zh_petition/.DS_Store

8
pom.xml

@ -101,20 +101,20 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
-->
-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<!--
<!--
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
-->
-->
<dependency>
<groupId>in.gov.chennaicorporation</groupId>
<artifactId>Community-Hall-Booking</artifactId>

84
src/main/java/in/gov/chennaicorporation/gccoffice/c_petition/service/Petition.java

@ -535,44 +535,52 @@ public class Petition {
}
@Transactional(readOnly = true)
public List<Map<String,Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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)

17
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<Map<String, Object>> getcampaignbyid(@RequestParam int id)
{
return campaignmaster.getcampaignbyid(id);
}
// @GetMapping("/getcampaignbyid")
// public List<Map<String, Object>> getcampaignbyid(@RequestParam int id)
// {
// return campaignmaster.getcampaignbyid(id);
// }
@GetMapping("/getagentsfortask")
public List<Map<String, Object>> getagentsfortask(@RequestParam int id)
@ -57,7 +57,7 @@ public class AgentAssignAPIController
@PostMapping("/addagentsfortask")
public ResponseEntity<List<Map<String, Object>>> addagentsfortask(@RequestBody List<Map<String, Object>> requestList) {
System.out.println("Received POST request with data: " + requestList);
//System.out.println("Received POST request with data: " + requestList);
List<Map<String, Object>> insertedAgents = new ArrayList<>(); // To store successfully inserted agents
@ -104,4 +104,9 @@ public class AgentAssignAPIController
{
return campaignmaster.editagentsfortask(id);
}
@GetMapping("/getcampaignbyid")
public List<Map<String, Object>> getcampaignquestionbyid(@RequestParam int id){
return campaignmaster.getcampaignquestionbyid(id);
}
}

181
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<String> savecall(@RequestBody Map<String, Object> 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<String> updatecall(@RequestBody Map<String, Object> callData)
@ -177,5 +157,164 @@ public class AgentsAPIController {
public List<Map<String, Object>> getCompletedDataById(@RequestParam List<Integer> completedDataIds){
return agentsService.getCompletedDataById(completedDataIds);
}
@PostMapping("/furtherAssignedAgents")
public ResponseEntity<Map<String, String>> updateAgentAssigndata(
@RequestBody Map<String, Object> 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<String> selectedAgentsList = (List<String>) 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<Integer> 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<Map<String, Object>> 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<Map<String, Object>> getCampaignQuestions(
@RequestParam int categoryId,
@RequestParam int campaignId) {
return agentsService.getCampaignQuestions(categoryId, campaignId);
}
@GetMapping("/fetchAnswer")
public List<Map<String, Object>> fetchAnswer(
@RequestParam int campaignId,
@RequestParam int agentId,
@RequestParam int questionId,
@RequestParam int dataId) {
return agentsService.FetchAnswer(campaignId,agentId,questionId,dataId);
}
@PostMapping("/submitAnswers")
public ResponseEntity<String> submitAnswers(@RequestBody Map<String, List<Map<String, Object>>> requestData) {
List<Map<String, Object>> 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<Map<String, Object>> getCallStatus() {
//System.out.println("dropdown");
return agentsService.getCallStatus();
}
@GetMapping("/checkCounts")
public List<Map<String, Object>> checkCounts(
@RequestParam int campaignId,
@RequestParam int dataId) {
return agentsService.checkCounts(campaignId,dataId);
}
@PostMapping("/savecall")
public ResponseEntity<String> savecall(@RequestBody Map<String, Object> 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.");
}
}

521
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<String, Object> getCampaignDetailsById(@RequestParam("campaign_id") Long campaignId) {
@GetMapping("/getCampaignDetailsById")
public @ResponseBody List<Map<String, Object>> getCampaignDetailsById(@RequestParam("campaign_id") Long campaignId) {
return campaignService.getCampaignDetailsById(campaignId);
}
@PostMapping("/updateCampaign")
public ResponseEntity<String> updateCampaign(
@RequestBody Map<String, Object> requestData) {
@PostMapping("/updateCampaign")
public ResponseEntity<String> 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<Map<String, Object>> questionsData =
(List<Map<String, Object>>) 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<String, String> 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<String, Object> 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<Map<String, Object>> 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<String, Object> questionMap : questionsData) {
String category = (String) questionMap.get("category");
String question = (String) questionMap.get("question");
String answerType = (String) questionMap.get("answerType");
List<String> answers = (List<String>) 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<String, String> 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<String, String> 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<String> saveQuestions(@RequestBody List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> readExcelData(InputStream inputStream, List<String> categoryColumns) throws IOException {
List<Map<String, Object>> 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<String> 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<String, Object> 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<List<Map<String, Object>>> getExcelData(@RequestParam("filePath") String filePath) {
try {
// Read data from the uploaded Excel file
List<Map<String, Object>> excelData = readExcelData(new FileInputStream(filePath));
List<Map<String, Object>> 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<Map<String, String>> 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<Map<String, Object>> questionsDataList = new ArrayList<>();
List<String> selectedAgentsList = new ArrayList<>();
try {
if (questionsData != null) {
questionsDataList = new ObjectMapper().readValue(questionsData, new TypeReference<List<Map<String, Object>>>() {});
}
if (selectedAgents != null) {
selectedAgentsList = new ObjectMapper().readValue(selectedAgents, new TypeReference<List<String>>() {});
}
} 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<String, Object> 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<Integer> 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<String, Object> questionMap : questionsDataList) {
String question = (String) questionMap.get("question");
String answerType = (String) questionMap.get("answerType");
List<String> answers = (List<String>) 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<String, String> 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<String, Object> campaignDetails = new HashMap<>();
campaignDetails.put("campaign_name", name);
campaignDetails.put("category_id", category);
try {
// Get category-specific columns
List<Map<String, Object>> categoryColumns = addCategoryServices.getCategoryColumns(Integer.parseInt(category));
//System.out.println("categorycolmns: " + categoryColumns);
List<String> 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<String> fieldColumns = campaignService.getUploadDataFieldColumns();
//System.out.println("fieldColumns: " + fieldColumns);
// Read uploaded Excel data and extract headers
List<Map<String, Object>> excelData = readExcelData(file.getInputStream(), expectedHeaders);
// System.out.println("excedata: " + excelData );
List<String> 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<String, String> 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<String, String> 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<Map<String, Object>> excelDatas = readExcelDataupdated(new FileInputStream(excelUrl));
List<Map<String, Object>> excelDatas = readExcelData(new FileInputStream(excelUrl), uploadedHeaders);
//System.out.println("excelDatas:" + excelDatas);
for (Map<String, Object> row : excelDatas) {
campaignService.saveUploadData(category, lastId, row,expectedHeaders);
//System.out.println("exceldatas:" + excelDatas);
}
Map<String, String> response = new HashMap<>();
response.put("status", "success");
response.put("message", "Campaign and Excel saved successfully");
return response;
}
catch (IOException e) {
e.printStackTrace();
Map<String, String> response = new HashMap<>();
response.put("status", "error");
response.put("message", "Failed to save campaign details: "+ e.getMessage());
return response;
}
}
@GetMapping("/availableAgents")
public ResponseEntity<List<Map<String, Object>>> 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<Map<String, Object>> 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<Map<String, Object>> ongoingAgents = jdbcTemplate.queryForList(ongoingCampaignAgentsQuery);
//System.out.println("ongoingAgents" + ongoingAgents);
// Extract agent IDs from both lists
Set<Integer> ongoingAgentIds = ongoingAgents.stream()
.map(agent -> (Integer) agent.get("agent_id"))
.collect(Collectors.toSet());
// Filter OUTBOUND agents who are NOT in ongoing agents
List<Map<String, Object>> 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<Map<String, Object>> response = campaignService.getQuestionAnswers(campaignId);
return ResponseEntity.ok(response);
}
//dizo campaignlist apicontroller
// Query Parameter Approach
@GetMapping("/statistics")
public ResponseEntity<Map<String, Object>> getCampaignStatisticsByQuery(@RequestParam int campaignId) {
Map<String, Object> statistics = campaignService.getCampaignStatistics(campaignId);
return ResponseEntity.ok(statistics);
}
@GetMapping("/assignagentid")
public ResponseEntity<List<Map<String, Object>>> getAllAgents() {
List<Map<String, Object>> assignAgentId = campaignService.getAllAgents();
return ResponseEntity.ok(assignAgentId);
}
@PostMapping("/close")
public ResponseEntity<String> 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<String> autoCloseExpiredCampaigns() {
int rowsUpdated = campaignService.autoCloseExpiredCampaigns();
if (rowsUpdated > 0) {
return ResponseEntity.ok(rowsUpdated + " expired campaigns closed successfully.");
} else {
return ResponseEntity.ok("No expired campaigns found.");
}
}
}

29
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<Map<String, Object>> getAnswerTypes() {
return dropdownApiService.getAnswerTypes();
}
}

100
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<Map<String, Object>> getCampaignData(
@RequestParam(required = false) String startDate,
@RequestParam(required = false) String endDate) {
List<Map<String, Object>> campaignData = campaignReportService.getCampaignData(startDate, endDate);
//System.out.println("Campaign Data: " + campaignData); // Debugging log
return campaignData;
}
@GetMapping("/getagentdatacount")
public List<Map<String, Object>> getAgentwiseData(@RequestParam String campaign_id) {
List<Map<String, Object>> agentData = campaignReportService.getAgentwiseData(campaign_id);
//System.out.println("Agent Data: " + agentData);
return agentData;
}
@GetMapping("/getReportCampaignid")
public ResponseEntity<?> getAgentReportCampaignId(@RequestParam String campaign_id) {
List<Map<String, Object>> 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<Map<String, Object>> 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();
}
}

229
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<String> saveCategoryDetails(@RequestBody Map<String, Object> 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<String> saveCategoryDetails(@RequestBody Map<String, Object> 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<String> saveCategoryDetails(@RequestBody Map<String, Object> 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<String, Object> 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<Map<String, Object>> deleteCategoryColumnById(@RequestParam("columnId") int columnId) {
boolean updated = addCategoryServices.removeColumnById(columnId);
Map<String, Object> response = new HashMap<>();
response.put("success", updated);
return ResponseEntity.ok(response);
}
@PostMapping("/updateCategoryColumns")
public ResponseEntity<Map<String, Object>> updateCategoryColumnsById(@RequestBody Map<String, Object> requestData) {
try {
Map<String, Object> 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<Map<String, Object>> columns = (List<Map<String, Object>>) requestData.get("columns");
boolean allUpdated = true;
for (Map<String, Object> 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<String, Object> 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<Map<String, Object>> addNewCategoryColumnsById(@RequestBody Map<String, Object> requestData) {
try {
int categoryId = (int) requestData.get("categoryId");
List<Map<String, Object>> columns = (List<Map<String, Object>>) requestData.get("columns");
boolean allUpdated = true;
for (Map<String, Object> column : columns) {
String columnName = (String) column.get("name");
boolean updated = addCategoryServices.addnewupdateColumn(categoryId, columnName);
if (!updated) {
allUpdated = false;
}
}
Map<String, Object> 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<String> updateCategory(
public ResponseEntity<String> updateCategoryWithColumns(
@PathVariable("categoryId") int categoryId,
@RequestParam String categoryName) {
@RequestBody Map<String, Object> 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<String> columns = (List<String>) 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<String, Object> 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<String> updateCategoryWithColumns(
// @PathVariable("categoryId") int categoryId,
// @RequestBody Map<String, Object> payload) {
//
// String categoryName = (String) payload.get("categoryName");
// List<String> columns = (List<String>) 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<String, Object> 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<String> 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<Map<String, Object>> getcategory()
{
public List<Map<String, Object>> getcategory(){
return addCategoryServices.getcategory();
}
// Get category-specific columns based on category_id
@GetMapping("/getCategoryColumns")
public List<Map<String, Object>> getCategoryColumns(@RequestParam int category_id) {
return addCategoryServices.getCategoryColumns(category_id);
}
@GetMapping("/getcampaignbycategory")
public List<Map<String, Object>> getcampaignbycategory(@RequestParam int id)
@ -120,9 +276,6 @@ public class CategoryAPIController {
return addCategoryServices.getcampaignbycategory(id);
}
}

57
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<Map<String, Object>> 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<Map<String, Object>> campaigns = campaignService.getCampaignDetails();
System.out.println("campaignlist:"+campaigns);
model.addAttribute("campaigns", campaigns);
/*
* List<Map<String, Object>> 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<Map<String, Object>> agentsCampaigns=agentsService.getAgentsALLCampaigns(userId);
List<Map<String, Object>> agentsCampaignsList=agentsService.getAgentsALLCampaignsList(userId);
List<Map<String, Object>> agentsCampaignsList1=agentsService.getAgentsALLCampaignsList1(userId);
//List<Map<String, Object>> 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,

246
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<String, Object> 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<String, Object> 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<String> columns = (List<String>) 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<Map<String, Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(SqlQuery);
return result;
}
public Map<String, Object> showCategory(int categoryId) {
String categorySql = "SELECT category_id, category_name FROM category WHERE category_id = ? AND isactive = 1 AND isdelete = 0";
Map<String, Object> 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<Map<String,Object>> columns = jdbcTemplate.queryForList(columnsSql,categoryId);
category.put("columns", columns);
return category;
}
@Transactional
public int updateCategoryWithColumns(int categoryId, String categoryName, List<String> 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<String> 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<String, Object> 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<String, Object> 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<String, Object> 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<String> 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<String> 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<Map<String, Object>> getcategory() {
String sqlQuery = "SELECT category_id,category_name FROM category where isactive='1' and isdelete='0'";
return jdbcTemplate.queryForList(sqlQuery);
}
public List<Map<String, Object>> 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<Map<String, Object>> 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;
}
}

119
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<Integer> 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<Map<String, Object>> checkcampaigninassignedtable(int id)
@ -92,6 +150,65 @@ public class AgentAssignService
}
@Transactional
public List<Map<String, Object>> 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<Map<String, Object>> queryResult = jdbcTemplate.queryForList(sqlQuery, id);
// Map to group answers by question_id
Map<Integer, Map<String, Object>> groupedData = new LinkedHashMap();
for (Map<String, Object> 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<String, Object> newRow = new LinkedHashMap<>(row);
newRow.remove("campaign_answer"); // Remove individual answer
newRow.put("campaign_answers", new ArrayList<String>()); // Initialize answer list
groupedData.put(questionId, newRow);
}
// Only add answers if they are not null
if (campaignAnswer != null) {
((List<String>) groupedData.get(questionId).get("campaign_answers")).add(campaignAnswer);
}
}
// Convert grouped data to a list
return new ArrayList<>(groupedData.values());
}
}

403
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<Map<String, Object>> 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<Map<String, Object>> 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<Integer> 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<Map<String, Object>> getFilteredFields(int categoryId, int agentId, int dataId) {
List<Map<String, Object>> 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<String> 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<Map<String, Object>> orderedFieldsList = jdbcTemplate.queryForList(query1, dataId);
if (orderedFieldsList.isEmpty()) {
throw new RuntimeException("No data found for data_id: " + dataId);
}
Map<String, Object> 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<String> 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<Object> 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<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> questions = jdbcTemplate.queryForList(questionQuery, categoryId, campaignId);
// Iterate over each question and fetch answers
for (Map<String, Object> 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<Map<String, Object>> answers = jdbcTemplate.queryForList(answerQuery, questionId);
// Extract answer values and add to the question map
List<String> answerList = answers.stream()
.map(a -> (String) a.get("campaign_answer"))
.collect(Collectors.toList());
question.put("answers", answerList);
}
return questions;
}
@Transactional
public List<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> 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<Map<String, Object>> getCallStatus() {
String sqlQuery = "SELECT * FROM gcc_1913_campaign.calls_status ";
//System.out.println("dropdown l");
return jdbcTemplate.queryForList(sqlQuery);
}
@Transactional
public List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> getCallCategories()
// {
// String query = "SELECT id,call_status FROM gcc_1913_campaign.calls_status WHERE isactive=1 AND isdelete=0";
// return jdbcTemplate.queryForList(query);
// }
}

29
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<Map<String,Object>> getAnswerTypes(){
String sql = "SELECT answer_type_id,type_name FROM answer_type";
return jdbcTemplate.queryForList(sql);
}
}

494
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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sql, campaignId);
Map<Integer, Map<String, Object>> responseMap = new LinkedHashMap<>();
for (Map<String, Object> row : result) {
int questionId = (int) row.get("question_id");
if (!responseMap.containsKey(questionId)) {
Map<String, Object> questionData = new HashMap<>();
questionData.put("question_id", questionId);
questionData.put("questions", row.get("questions"));
questionData.put("answers", new ArrayList<>());
responseMap.put(questionId, questionData);
}
Map<String, Object> 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<Map<String, Object>>) responseMap.get(questionId).get("answers")).add(answerData);
}
return new ArrayList<>(responseMap.values());
}
//
// public void generateCSV(int categoryId, int campaignId, PrintWriter writer) {
// List<Map<String, Object>> 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<String> 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<Map<String, Object>> 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<String> 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<Integer, String> agentMap = jdbcTemplate.query(fetchAgentSQL, rs -> {
// Map<Integer, String> 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<Integer, String> questionsMap = jdbcTemplate.query(fetchQuestionsQuery, rs -> {
// Map<Integer, String> 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<Integer, Map<Integer, String>> answersMap = jdbcTemplate.query(fetchAnswersQuery, rs -> {
// Map<Integer, Map<Integer, String>> 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<String, Object> orderedFields : orderedFieldsList) {
// List<Object> 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<String, Object> 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<Integer, String> currentAnswers = answersMap.getOrDefault(dataId, new HashMap<>());
// for (Map.Entry<Integer, String> 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<String, Object> rowData : resultList) {
// List<String> 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<Map<String, Object>> 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<String> 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<Map<String, Object>> 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<String> 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<Integer, String> agentMap = jdbcTemplate.query(fetchAgentSQL, rs -> {
Map<Integer, String> 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<Integer, String> questionsMap = jdbcTemplate.query(fetchQuestionsQuery, rs -> {
Map<Integer, String> 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<Integer, Map<Integer, String>> answersMap = jdbcTemplate.query(fetchAnswersQuery, rs -> {
Map<Integer, Map<Integer, String>> 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<String, Object> orderedFields : orderedFieldsList) {
List<Object> 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<String, Object> 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<Integer, String> currentAnswers = answersMap.getOrDefault(dataId, new HashMap<>());
for (Map.Entry<Integer, String> 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<String, Object> rowData : resultList) {
List<String> values = rowData.values().stream()
.map(value -> escapeCsvValue(value != null ? value.toString() : ""))
.collect(Collectors.toList());
writer.println(String.join(",", values));
}
}
}

492
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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String> 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<Map<String, Object>> questionsData) {
for (Map<String, Object> 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<String> answers = (List<String>) 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<String> 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<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> rowData, List<String> expectedHeaders) {
int fieldCount = rowData.size();
List<String> 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<Object> 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<String, Object> 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<String> 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<Object> 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<Map<String, Object>> 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<String, Object> getCampaignStatistics(int campaignId) {
Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> results = jdbcTemplate.queryForList(sql, campaign_id);
// Group answers by question_id
Map<Long, Map<String, Object>> groupedData = new LinkedHashMap();
for (Map<String, Object> 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<String> 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<String> answers = (List<String>) 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<Map<String, Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sql, campaignId);
Map<Integer, Map<String, Object>> responseMap = new LinkedHashMap<>();
for (Map<String, Object> row : result) {
int questionId = (int) row.get("question_id");
if (!responseMap.containsKey(questionId)) {
Map<String, Object> questionData = new HashMap<>();
questionData.put("question_id", questionId);
questionData.put("questions", row.get("questions"));
questionData.put("answers", new ArrayList<>());
responseMap.put(questionId, questionData);
}
Map<String, Object> 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<Map<String, Object>>) 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(); }
*/
}

36
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<String> responseEntity = restTemplate.getForEntity(apiUrl, String.class);
return responseEntity.getBody();
}
}

71
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<Map<String, Object>> 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<String> 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<String, Object> 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";
}
}

441
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<String> 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<String, String> 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<String, String> 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<String, Object> 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"));
}
}
}

31
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";
}
}

10
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<String, Object> complaintDetails = qaqcCallsService.getComplaintDetails(dataId);

10
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")) {

136
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/MainController.java

@ -67,7 +67,7 @@ public class MainController {
List<Map<String,Object>> previousday=agentsService.getPreviousDayDashboardCounts();
model.addAttribute("previousday", previousday);
System.out.println(previousday);
//System.out.println(previousday);
List<Map<String,Object>> 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<Map<String, Object>> Counts=adminService.getAdminSettingCounts();
model.addAttribute("Counts", Counts);
List<Map<String, Object>> 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<Map<String, Object>> 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";
}
}

10
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<String, Object> complaintDetails = qaqcCallsService.getComplaintDetails(dataId);

118
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<String, Object> 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<String, Object> GetUnattendedComplaints(@RequestParam int ucount)
{
Map<String, Object> response = new HashMap<>();
try {
// Logging input parameters
//System.out.println("Received Data: " + ucount);
// Fetch unattended complaints
List<Map<String, Object>> 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<Map<String, Object>> closeUnattendedComplaints(@RequestBody Map<String, Object> request) {
Map<String, Object> response = new HashMap<>();
try {
// Extract values from request map
String userId = (String) request.get("userId");
String remarks = (String) request.get("remarks");
List<String> complaintNumbers = (List<String>) 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<String> completedComplaints = new ArrayList<>();
List<String> 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);
}
}
}

208
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<Map<String, String>> saveproductivity(@RequestParam int productivity_count)
{
Map<String, String> 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<Map<String, String>> updateProductivityById(@RequestBody Map<String, Integer> requestData)
{ Map<String, String> 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<Map<String, Object>> getadminsettingcounts()
{
return adminService.getAdminSettingCounts();
}
@GetMapping("/assigncallingtype")
public List<Map<String, Object>> assigncallingtype()
{
return adminService.getAgentsForCallingtype();
}
@PostMapping("/updateCallType") // Bulk update endpoint
public ResponseEntity<Map<String, String>> updateCallType(@RequestBody List<Map<String, Object>> selectedAgents) {
Map<String, String> response = new HashMap<>();
try {
int rowsUpdated = 0;
// Loop through each selected agent and update their calling_type
for (Map<String, Object> 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<Map<String, String>> updateAgentnameById(@RequestBody Map<String, String> requestData){
Map<String, String> 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);
}
}
}

47
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<Map<String, Object>> Counts=adminService.getAdminSettingCounts();
model.addAttribute("Counts", Counts);
List<Map<String, Object>> agents=adminService.getAgentsForCallingtype();
model.addAttribute("Agents", agents);
return "modules/callcenterqaqc/qaqcadminsettings";
}
}

15
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<productivity_count) {
filteredAgents.add(Map.of(
@ -86,12 +85,12 @@ public class QaqcAgentAssignAPIController {
"campaignPendingCount", campaignPendingCount,
"todayCount",todayCount
));
System.out.println("Agent added to filteredAgents: " + agentName);
//System.out.println("Agent added to filteredAgents: " + agentName);
}
}
System.out.println("Filtered Agents Size: " + filteredAgents.size());
//System.out.println("Filtered Agents Size: " + filteredAgents.size());
if (filteredAgents.isEmpty()) {
@ -130,10 +129,10 @@ public class QaqcAgentAssignAPIController {
"campaignPendingCount", campaignPendingCount,
"calls_per_agent", calls_per_agent + additionalCalls
));
System.out.println("Agent added to final======filteredAgents: " + agentName);
// System.out.println("Agent added to final======filteredAgents: " + agentName);
}
}
System.out.println("Final Filtered Agents Size: " + finalFilteredAgents.size());
//System.out.println("Final Filtered Agents Size: " + finalFilteredAgents.size());
if (finalFilteredAgents.isEmpty()) {
response.put("status", "error");
@ -171,10 +170,10 @@ public class QaqcAgentAssignAPIController {
"campaignPendingCount", campaignPendingCount,
"calls_per_agent", calls_per_agent2 + additionalCalls1
));
System.out.println("Agent added to Lastfinal======LastfinalFilteredAgents: " + agentName);
// System.out.println("Agent added to Lastfinal======LastfinalFilteredAgents: " + agentName);
}
}
System.out.println("Filtered Agents Size: " + LastfinalFilteredAgents.size());
//System.out.println("Filtered Agents Size: " + LastfinalFilteredAgents.size());
if (LastfinalFilteredAgents.isEmpty()) {
response.put("status", "error");

18
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcAgentsAPIController.java

@ -96,9 +96,9 @@ public class QaqcAgentsAPIController {
@RequestParam(required = false) String endDate) {
List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> getAgentTaskwiseData(@RequestParam String agentId) {
public List<Map<String, Object>> getAgentTaskwiseData(@RequestParam String agentId,@RequestParam String startDate,@RequestParam String endDate) {
// Call the service to fetch agent task-wise data
List<Map<String, Object>> agentTaskwiseData = agentsService.getAgentTaskwiseData(agentId);
System.out.println("Agent Task Wise Data: " + agentTaskwiseData);
List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> agentAttendedData = agentsService.getAttendedComplainthistory(startDate, endDate, complaintNumber, complaintMobileNumber);
System.out.println("Agent attended Data: " + agentAttendedData);
//System.out.println("Agent attended Data: " + agentAttendedData);
return agentAttendedData;
}

30
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<String,Object> 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<String, Object> resultMap = new HashMap<>();
List<Map<String, Object>> 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

26
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";
}
}

6
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/QaqcTaskListAPIController.java

@ -39,7 +39,7 @@ public class QaqcTaskListAPIController {
@RequestParam(required = false) String endDate) {
List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> getAgentwiseData(@RequestParam String qaqc_id)
{
List<Map<String, Object>> agentwisedata = tasklist.getAgentwiseData(qaqc_id);
System.out.println("agentdata "+agentwisedata);
//System.out.println("agentdata "+agentwisedata);
return agentwisedata;
}

58
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";
}
}

349
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<String> 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<String, Object> 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<String, Object> getDetailsByComplaintNumber(String complaintNumber) {
Map<String, Object> 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<String> 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<String, Object> viewSocialMediaData(
@RequestParam String startDate,
@RequestParam String endDate,
@RequestParam String status,
@RequestParam String group,
@RequestParam String type,
@RequestParam String zone) {
Map<String, Object> 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<String> 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("(?<![,{])\"R", "\"R"); // Example: Fix missing commas
}
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> responseMap = objectMapper.readValue(rawResponse, Map.class);
List<Map<String, Object>> details = (List<Map<String, Object>>) 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<String, Object> viewSocialMediaCompletedData(
@RequestParam String startDate,
@RequestParam String endDate, @RequestParam String status,
@RequestParam String zone) {
System.out.printf("==================="+startDate,endDate,zone);
Map<String, Object> 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<Map<String, Object>> 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;
}
}

41
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";
}
}

10
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/controller/StatusCountController.java

@ -27,16 +27,18 @@ public class StatusCountController {
}
@GetMapping("/dashboard")
public ResponseEntity<Map<String, String>> getDashboardData(
public ResponseEntity<Map<String, Object>> 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<String, String> counts = statusCountService.fetchComplaintCounts(fromDate, toDate, compType, zoneName, compMode, compGroup);
System.out.println("counts:" + counts);
Map<String, Object> counts = statusCountService.fetchComplaintCounts(fromDate, toDate, compType, zoneName, compMode, compGroup,region);
//System.out.println("counts:" + counts);
//System.out.println("group:" + compGroup);
return ResponseEntity.ok(counts);
}

14
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<String, Object> 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);
}
}

6
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<Map<String, Object>> 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);
}

24
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcAdminSettingService.java

@ -95,11 +95,29 @@ public class QaqcAdminSettingService {
@Transactional
public List<Map<String, Object>> 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);
}
}

73
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<Map<String, Object>> agents = (List<Map<String, Object>>) 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<Map<String, Object>> 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<String, Object> 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<Map<String, Object>> agents,String status,List<Map<String, Object>> 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<String, Object> 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<Map<String, Object>> 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

16
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<Map<String, Object>> getAgentTaskwiseData(String agentId) {
public List<Map<String, Object>> 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);
}

22
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/QaqcCallsService.java

@ -53,7 +53,7 @@ public class QaqcCallsService {
@Transactional
public int uploadComplaintDetailsInLogs(Map<String, Object> 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<String, Object> 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<String,Object> 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);
}

218
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<Map<String, Object>> 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<Map<String, Object>> 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<String> 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<String> completedComplaints,String remarks,String userId) {
int totalUpdated = 0;
int rowsUpdated=0;
for (String cnum : completedComplaints) {
List<Map<String,Object>>details=getComplaintsLatestDetails(cnum);
if(!details.isEmpty()) {
for (Map<String, Object> 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<Map<String,Object>> getComplaintsLatestDetails(String complaint_number){
String query = "SELECT * FROM qaqc_upload_data_history WHERE complaint_number = ? ORDER BY created_date DESC LIMIT 1";
List<Map<String,Object>> getCompNumber = jdbcTemplate.queryForList(query, complaint_number);
return getCompNumber;
}
}

57
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<Map<String, Object>> 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";

16
src/main/java/in/gov/chennaicorporation/gccoffice/callcenterqaqc/service/SocialMediaService.java

@ -27,7 +27,7 @@ public class SocialMediaService {
@Transactional
public int uploadComplaintDetailsInLogs(Map<String, Object> 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<Map<String, Object>> 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;
}

60
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<String, String> fetchComplaintCounts(String fromDate, String toDate, String compType, String zoneName, String compMode, String compGroup) {
public Map<String, Object> 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 += "&region=" + region;
}
Map<String, String> counts = new HashMap<>();
Map<String, Object> 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<String> response1 = restTemplate.getForEntity(url, String.class);
String rawResponse = response1.getBody();
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> responseMap = objectMapper.readValue(rawResponse, Map.class);
List<Map<String, Object>> details = (List<Map<String, Object>>) 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();
}

174
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<String> 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<String> params = new ArrayList<>();
if (mobileNo != null) {
params.add("mobileNo=" + mobileNo);
}
if (refId != null) {
params.add("refId=" + refId);
}
apiUrl.append(String.join("&", params));
try {
ResponseEntity<String> 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<String> getpaymentcharges() {
String apiUrl = appConfig.dumpregister + "/dumpregistration/dropdown/api/getallcharges";
try {
ResponseEntity<String> 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<String> saveWasteRequest(@RequestBody Map<String, Object> 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<String> getWasteCollectorLess1TonList() {
StringBuilder apiUrl = new StringBuilder(appConfig.dumpregister + "/dumpregistration/api/getless1tonlist");
try {
ResponseEntity<String> 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<String> 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<String> 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<Map<String, Object>> 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<Map<String, Object>> getwastequantity() {
return officerService.getAllwastequantity();
}
//fetch all zones
@GetMapping("/getzones")
public ResponseEntity<?> getAllZones() {
try {
List<Map<String, Object>> 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()));
}
}
}

75
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";
}
}

161
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<String, Object> 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<Map<String, Object>> 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<Object> 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<Map<String, Object>> getAllwastequantity() {
String sql = " SELECT id,quantity FROM quantity_master where is_active = 1 ";
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getZonesList() {
String sql = " SELECT id,zone_name from zones where is_active = 1 ";
return jdbcTemplate.queryForList(sql);
}
}

40
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;
}
}

44
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<Map<String, Object>> 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<String, Object> 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
}
}

104
src/main/java/in/gov/chennaicorporation/gccoffice/com_petition/service/Petition.java

@ -553,44 +553,52 @@ public class Petition {
}
@Transactional(readOnly = true)
public List<Map<String,Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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";
}
}

1
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

91
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() {

2
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
}

22
src/main/java/in/gov/chennaicorporation/gccoffice/controller/MenuController.java

@ -55,7 +55,6 @@ public class MenuController {
return "";
}
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
@ -101,7 +100,16 @@ public class MenuController {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/gcc/"+subMenuItem.getUrl()+"\" class=\"menu-item\"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if(subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML+"<a href=\""+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
else {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/gcc/"+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
}
if(subSubMenuHTML.equals(""))
{
@ -126,7 +134,15 @@ public class MenuController {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(menuItem.getId(),checkSubMenuId);
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/gcc/"+subMenuItem.getUrl()+"\" class=\"menu-item\"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if(subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML+"<a href=\""+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
else {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/gcc/"+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
}
subMenuHTML = subMenuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0);\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i>"+menuItem.getName()+"</a><div class=\"submenu-content\">"+subSubMenuHTML+"</div></div>";
}

1
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;
}
}

12
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;
}
}

13
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")

194
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<Map<String,Object>> getPetitionList() {
try {
String sqlQuery = "SELECT * FROM petition WHERE (`isactive`=1 AND `isdelete`=0)";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
Base64Util.encodeBase64(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> 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<String, Object> 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<Map<String,Object>> getUnmapPetitionList() {
@ -451,7 +458,10 @@ public class Petition {
}
@Transactional(readOnly = true)
public List<Map<String,Object>> getComplaintList(String loginId) {
public List<Map<String,Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery,datePattern);
// Iterate over the list of maps
for (Map<String, Object> map : result) {
@ -539,45 +551,53 @@ public class Petition {
}
@Transactional(readOnly = true)
public List<Map<String,Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
// Iterate over the list of maps
for (Map<String, Object> 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<Map<String,Object>> 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();

57
src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java

@ -494,7 +494,7 @@ public class NulmAPIController {
List<Map<String, Object>> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, inchargeName, enrollmentIds);
return ResponseEntity.ok(staffList);
}
/*
@PostMapping("/salaryDetailUpdate")
public ResponseEntity<String> addSalaryDetails(@RequestBody List<Map<String, Object>> 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<String> addSalaryDetails(@RequestBody List<Map<String, Object>> requestList) {
System.out.println("Received POST request with data: " + requestList);
try {
for (Map<String, Object> 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) {

77
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<Map<String, Object>> 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<Map<String, List<String>>> 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<Map<String, Object>> 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<Map<String, Object>> salaryNotInitiatedReport = new ArrayList<>();
if (month != null && year != null) {
salaryNotInitiatedReport = nulmService.getSalaryNotInitiatedReport(month, year, groupName);
}
model.addAttribute("salaryNonInitiatedReport", salaryNotInitiatedReport);
return "modules/nulm/salary-nonInitiatedreport";
}
}

139
src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java

@ -376,7 +376,7 @@ public class NulmService {
}
public List<Map<String, Object>> 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<Map<String, Object>> results = jdbcTemplate.queryForList(sql.toString(), params.toArray());
//List<Map<String, Object>> results = nulmJdbcTemplate.queryForList(sql.toString());
//List<Map<String, Object>> 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<Map<String, Object>> 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<Object> 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<Map<String, Object>> results = jdbcTemplate.queryForList(sql.toString(), params.toArray());
return results;
}
public Map<String, List<String>> fetchAttendanceDates(String enrollmentId, String fromdate, String todate, String type) { //newly added
Map<String, List<String>> 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<Map<String, Object>> getSelfHelpGroupDetails() { // newly added
String sql = "select * from suyaudavi_kuzhu where isactive = 1 and isdelete =0 order by group_name asc";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql);
return results;
}
public List<Map<String, Object>> 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<Object> 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<Integer> 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);
}
}

56
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<Map<String, Object>> 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.");
}
}
}

241
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<Map<String, Object>> getDashboardData() {
return dashboardApiService.fetchCategoryCounts();
}
/*@GetMapping("/dashboardsearch")
@ResponseBody
public List<Map<String, Object>> 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<Map<String, Object>> getCategoryCounts() {
return dashboardApiService.fetchCategoryCounts();
}
@GetMapping("/getEmpNoByFileName")
public List<Map<String, Object>> getEmployeeDetails(@RequestParam("file_id") String FileId) {
System.out.println("before fetch");
return dashboardApiService.getEmployeeDetails(FileId);
}
@GetMapping("/stageWiseCounts")
public ResponseEntity<List<Map<String, Object>>> getStageWiseCounts() {
List<Map<String, Object>> stageWiseCounts = dashboardApiService.getStageWiseCounts();
return ResponseEntity.ok(stageWiseCounts);
}*/
@GetMapping("/getDepartments")
@ResponseBody
public List<Map<String, Object>> getDepartment() {
return dashboardApiService.getDepartment();
}
@GetMapping("/getEmpNoByFileName")
public List<Map<String, Object>> getEmployeeDetails(@RequestParam("file_id") String FileId) {
System.out.println("before fetch");
return dashboardApiService.getEmployeeDetails(FileId);
}
//department
@GetMapping("/deparmentdashboard")
@ResponseBody
public List<Map<String, Object>> getDepartmentDashboardData(@RequestParam(required = false) String deptId) {
System.out.println("deptid"+ deptId);
return dashboardApiService.DepartmenfetchCategoryCounts(deptId);
}
/* @GetMapping("/deparmentcategoryCounts")
public List<Map<String, Object>> getDepartmenCategoryCounts(@RequestParam(required = false) String deptId) {
return dashboardApiService.DepartmenfetchCategoryCounts(deptId);
}
//DepartmentstageWiseCounts
@GetMapping("/DepartmentstageWiseCounts")
public ResponseEntity<List<Map<String, Object>>> getDepartmentStageWiseCounts(@RequestParam(required = false) String deptId) {
List<Map<String, Object>> stageWiseCounts = dashboardApiService.getDepartmentStageWiseCounts(deptId);
return ResponseEntity.ok(stageWiseCounts);
}*/
@GetMapping("/stageWiseCounts")
public ResponseEntity<List<Map<String, Object>>> 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<Map<String, Object>> stageWiseCounts = dashboardApiService.getStageWiseCounts(deptId, startDate, endDate);
return ResponseEntity.ok(stageWiseCounts);
}
@GetMapping("/categoryCounts")
public List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> getPensionDashboardData(@RequestParam(required = false) String deptId) {
System.out.println("deptid"+ deptId);
return dashboardApiService.DepartmenfetchCategoryCounts(deptId);
}
/* @GetMapping("/pensiondashboardsearch")
@ResponseBody
public List<Map<String, Object>> 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<Map<String, Object>> 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<List<Map<String, Object>>> 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<Map<String, Object>> stageWiseCounts = dashboardApiService.getDepartmentStageWiseCounts(deptId, startDate, endDate);
return ResponseEntity.ok(stageWiseCounts);
}*/
@GetMapping("/fetchEmpDetails")
public List<Map<String, Object>> getEmpDetails(@RequestParam(required = false) String Empcode) {
System.out.println("checking");
System.out.println(Empcode);
return dashboardApiService.getEmpDetails(Empcode);
}
@GetMapping("/fetchPensionEmpDetails")
public List<Map<String, Object>> getPensionEmpDetails(@RequestParam(required = false) String Empcode) {
System.out.println("checking");
System.out.println(Empcode);
return dashboardApiService.getPensionEmpDetails(Empcode);
}
@GetMapping("/fetchTempDetails")
public List<Map<String, Object>> getTempEmpDetails(@RequestParam(required = false) String tempId) {
System.out.println("checking");
System.out.println(tempId);
return dashboardApiService.getTempEmpDetails(tempId);
}
}

129
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<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateForwardFamilyPension(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateForwardPendency(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

720
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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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";
}
}

176
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<String> updateRetirementEmployeeDetailsCompleted(@RequestBody Map<String, Object> 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<Map<String, Object>> emp_details = deptAuditService.fetchEmployeeById(tempId);
System.out.println("emp_details:==:" + emp_details);
// Fetch pension benefits details
List<Map<String, Object>> 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<String, Object> 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<String> updateRetirementEmployeeDetailsPending(@RequestBody Map<String, Object> 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<Map<String, Object>> emp_details = deptAuditService.fetchEmployeeById(tempId);
System.out.println("emp_details:==:" + emp_details);
// Fetch pension benefits details
List<Map<String, Object>> 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<String> updateRetirementEmployeeDetailsReturn(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

189
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<Map<String, Object>> getEmployeedetailsbyCode(
@RequestParam String tempId) {
List<Map<String, Object>> employeeDetails = deptAuditService.fetchEmployeeById(tempId);
System.out.println("employeeDetails==="+employeeDetails);
return employeeDetails;
}
@GetMapping("/getemployeedetailscps")
public List<Map<String, Object>> getEmployeedetailsbyCodeCps(
@RequestParam String tempId) {
List<Map<String, Object>> employeeDetails = deptAuditService.fetchEmployeeByIdCps(tempId);
System.out.println("employeeDetails==="+employeeDetails);
return employeeDetails;
}
@GetMapping("/getzonebenefitsdetails")
public List<Map<String, Object>> getdetailsWithZonebenefits(
@RequestParam String tempId) {
List<Map<String, Object>> zoneBenefitDetails = deptAuditService.fetchDetailsWithZoneBenefitsById(tempId);
System.out.println("zoneBenefitDetails==="+zoneBenefitDetails);
return zoneBenefitDetails;
}
@GetMapping("/getfilependingbenefits")
public List<Map<String, Object>> getAllBenefitsDetails(
@RequestParam String tempId) {
List<Map<String, Object>> allBenefitDetails = deptAuditService.fetchFilePendingBenefits(tempId);
System.out.println("allBenefitDetails==="+allBenefitDetails);
return allBenefitDetails;
}
@GetMapping("/getpartialdetails")
public List<Map<String, Object>> getAllPartialDetails(
@RequestParam String tempId) {
List<Map<String, Object>> partialDetails = deptAuditService.fetchPartialCompleted(tempId);
System.out.println("partialDetails==="+partialDetails);
return partialDetails;
}
@GetMapping("/fileMovementhistory")
public List<Map<String, Object>> getFileMovementHistory(@RequestParam String tempId) {
List<Map<String, Object>> fileHistory = deptAuditService.fetchFileMovementHistory(tempId);
return fileHistory;
}
@PostMapping("/updateEmployeeDetails")
public ResponseEntity<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateFamilyPensionDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updatePendencyDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

110
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<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> emp_details=deptAuditService.fetchPartialCompleted(tempId);
System.out.println("emp_details:==:"+emp_details);
List<Map<String, Object>> zone_benefits=pensionReceivedService.fetchZonebenefitsById(tempId);
System.out.println("zone_benefits:==:"+zone_benefits);
List<Map<String, Object>> 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<String, Object> 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.");
}
}
}

46
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<Map<String, Object>> getRetrimentTypes() {
return dropdownService.getRetrimentTypes();
}
@GetMapping("/getCategoryTypes")
@ResponseBody
public List<Map<String, Object>> getCategoryTypes() {
return dropdownService.getCategoryTypes();
}
@GetMapping("/getProvisionalReasonTypes")
@ResponseBody
public List<Map<String, Object>> getProvisionalReasonTypes() {
return dropdownService.getProvisionalReasonTypes();
}
@GetMapping("/getGisEntryTypes")
@ResponseBody
public List<Map<String, Object>> getGisEntryTypes() {
return dropdownService.getGisEntryTypes();
}
}

120
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<Map<String, Object>> 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<Map<String, Object>> employeeDetails = fileClosingService.fetchEmployeeByTempId(tempId);
System.out.println("employeeDetails==="+employeeDetails);
return employeeDetails;
}
@GetMapping("/getemployeedetails")
public List<Map<String, Object>> getEmployeedetailsbyCode(
@RequestParam String tempId) {
System.out.println("temporary==="+tempId);
List<Map<String, Object>> employeeDetails = fileClosingService.fetchEmployeeById(tempId);
System.out.println("employeeDetails==="+employeeDetails);
return employeeDetails;
}
@PostMapping("/updateDetails")
public ResponseEntity<String> updateDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> getClosedEmployeedetails(){
List<Map<String, Object>> employeeDetails = fileClosingService.fetchClosingEmployee();
System.out.println("employeeDetails==="+employeeDetails);
return employeeDetails;
}
}

60
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";
}
}

334
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<String, Object> 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<String, Object> 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<String, Object> datalist = newEntryService.fetchEmplyeeDetails(formattedFromDate, formattedToDate, deptId);
System.out.println("datalist="+datalist);
List<String> 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<String> 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<Map<String, Object>> filteredList = ((List<Map<String, Object>>) 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<Map<String, Object>> getEmployeedetailsbyCode(
@RequestParam String empCode) {
Map<String, Object> datalistbycode = newEntryService.fetchEmplyeeDetailsbyCode(empCode);
return ResponseEntity.ok(datalistbycode);
}
@PostMapping("/saveEmployeeDetails")
public ResponseEntity<String> saveRetirementEmployeeDetails(@RequestBody Map<String, Object> 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<String> saveFamilyPensionDetails(@RequestBody Map<String, Object> 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<String> savePendecnyDetails(@RequestBody Map<String, Object> 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<String> saveEmployeeDetailsingis(@RequestBody Map<String, Object> 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<String> saveEmployeeDetailsProvisionalretirement(@RequestBody Map<String, Object> 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<String> saveEmployeeDetailspensionscheme(@RequestBody Map<String, Object> 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<Map<String, Boolean>> checkEmployeeExists(@RequestParam String empCode) {
boolean exists = newEntryService.doesEmployeeExist(empCode);
Map<String, Boolean> response = new HashMap<>();
response.put("exists", exists);
return ResponseEntity.ok(response);
}
@GetMapping("/cpsexists")
public ResponseEntity<Map<String, Boolean>> checkEmployeeExistsCps(@RequestParam String empCode) {
boolean exists = newEntryService.doesEmployeeExistgis(empCode);
Map<String, Boolean> response = new HashMap<>();
response.put("exists", exists);
return ResponseEntity.ok(response);
}
@GetMapping("/prexists")
public ResponseEntity<Map<String, Boolean>> checkEmployeeExistsRpr(@RequestParam String empCode) {
boolean exists = newEntryService.doesEmployeeExistRPR(empCode);
Map<String, Boolean> response = new HashMap<>();
response.put("exists", exists);
return ResponseEntity.ok(response);
}
@GetMapping("/familypensionexists")
public ResponseEntity<Map<String, Boolean>> checkEmployeeExistsfp(@RequestParam String empCode) {
boolean exists = newEntryService.doesEmployeeExistfp(empCode);
Map<String, Boolean> response = new HashMap<>();
response.put("exists", exists);
return ResponseEntity.ok(response);
}
}

201
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<Map<String, Object>> covertList = pendencyAutoConversionService.getConvertingTempIds();
// System.out.println("covertList===" + covertList);
//
// if (!covertList.isEmpty()) {
// for (Map<String, Object> 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<Map<String, Object>> 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<String, Object> 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<String, Object> GetRecordsUpdatePendencyDuration() {
Map<String, Object> response = new HashMap<>();
// Lists to store tempIds based on update success or failure
List<String> successfulUpdates = new ArrayList<>();
List<String> failedUpdates = new ArrayList<>();
String sqlQuery = "SELECT * FROM pensioner_details WHERE file_category=3 AND pending_duration='yes' AND file_status < 11";
List<Map<String, Object>> details = jdbcTemplate.queryForList(sqlQuery);
for (Map<String, Object> 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;
}
}

134
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<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateFamilyPensionDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updatePendencyDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

110
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<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> emp_details=deptAuditService.fetchPartialCompleted(tempId);
System.out.println("emp_details:==:"+emp_details);
List<Map<String, Object>> zone_benefits=pensionReceivedService.fetchZonebenefitsById(tempId);
System.out.println("zone_benefits:==:"+zone_benefits);
List<Map<String, Object>> 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<String, Object> 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.");
}
}
}

94
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<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> emp_details=deptAuditService.fetchEmployeeById(tempId);
System.out.println("emp_details:==:"+emp_details);
List<Map<String, Object>> 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<String> updateEmployeeDetailsGis(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

625
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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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<Map<String, Object>>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";
}
}

145
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<String> updateEmployeeDetailsCompleted(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateEmployeeDetailsReturn(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateEntryDetailsSenttoPension(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

143
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<Map<String, Object>> 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<Map<String, Object>> getReportData(@RequestParam String startDate,
@RequestParam String endDate,
@RequestParam String deptId
) {
return reportApiService.getReportData(startDate, endDate, deptId);
}
@GetMapping("/getReportDetails")
@ResponseBody
public List<Map<String, Object>> getReportDetails(@RequestParam String startDate,
@RequestParam String endDate,
@RequestParam Integer deptId,
@RequestParam Integer fileCatId,
@RequestParam(required = false) List<String> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> getReportDetailspension(@RequestParam String startDate,
@RequestParam String endDate,
@RequestParam List<String> deptIds,
@RequestParam Integer fileCatId,
@RequestParam(required = false) List<String> 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<Map<String, Object>> getDepartmentpending(@RequestParam int file_category ) {
return reportApiService.getDepartmentpending(file_category);
}
}

129
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<String> updateEmployeeDetails(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updateReturnFamilyPension(@RequestBody Map<String, Object> 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<Map<String, Object>> 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<String> updatePendencyPension(@RequestBody Map<String, Object> 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<Map<String, Object>> 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.");
}
}
}

229
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<Map<String, Object>> 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<String, Object> 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<String, Object> 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<String, Object> GetRecordsUpdatePendencyDuration() {
Map<String, Object> response = new HashMap<>();
// Lists to store tempIds based on update success or failure
List<String> successfulUpdates = new ArrayList<>();
List<String> failedUpdates = new ArrayList<>();
List<Map<String, Object>> details = pendencyAutoConversionService.getPendencyUpdatingDuration();
List<Map<String, Object>> prdetails = pendencyAutoConversionService.getProvisionalNoPendingDuration();
if(!prdetails.isEmpty()) {
for (Map<String, Object> 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<Map<String, Object>> 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<String, Object> 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;
}
}

180
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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> fetchDetailsProvisionalDepartmentPensionside(Integer file_cat) {
String query = "SELECT * " +
"FROM pensioner_details " +
"WHERE file_category=? and file_status=11";
return jdbcTemplate.queryForList(query,file_cat);
}
}

402
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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> getDepartment() {
String sql = "SELECT dept_id,dept_name FROM department_master WHERE dept_id <> 2000";
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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<Map<String, Object>> 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"; */

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save