Browse Source

first commit

master
yoganandhan 9 months ago
parent
commit
538a96515a
  1. 3
      .vscode/settings.json
  2. 9
      pom.xml
  3. 102
      src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java
  4. 34
      src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java
  5. 69
      src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java
  6. 48
      src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java
  7. 137
      src/main/java/com/gcc/election/admindataentry/service/BatchService.java
  8. 139
      src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java
  9. 59
      src/main/java/com/gcc/election/admindataentry/service/TrainingService.java
  10. 94
      src/main/java/com/gcc/election/configuration/DataSourceConfig.java
  11. 89
      src/main/java/com/gcc/election/configuration/SecurityConfig.java
  12. 31
      src/main/java/com/gcc/election/configuration/ThymeleafConfig.java
  13. 74
      src/main/java/com/gcc/election/configuration/WebMvcConfig.java
  14. 470
      src/main/java/com/gcc/election/controller/APIController.java
  15. 148
      src/main/java/com/gcc/election/controller/AdminController.java
  16. 37
      src/main/java/com/gcc/election/controller/MainController.java
  17. 167
      src/main/java/com/gcc/election/controller/MenuController.java
  18. 260
      src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java
  19. 108
      src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java
  20. 175
      src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java
  21. 214
      src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java
  22. 302
      src/main/java/com/gcc/election/dataentry/service/UpdationService.java
  23. 321
      src/main/java/com/gcc/election/interceptor/AppInterceptor.java
  24. 30
      src/main/java/com/gcc/election/repository/AppModuleRepository.java
  25. 34
      src/main/java/com/gcc/election/repository/SubMenuItemRepository.java
  26. 37
      src/main/java/com/gcc/election/service/Base64Util.java
  27. 6
      src/main/java/com/gcc/swm_services/SwmApplication.java
  28. 7
      src/main/java/com/gcc/swm_services/configuration/AppConfig.java
  29. 90
      src/main/java/com/gcc/swm_services/configuration/DataSourceConfig.java
  30. 9
      src/main/java/com/gcc/swm_services/configuration/JacksonConfiguration.java
  31. 93
      src/main/java/com/gcc/swm_services/configuration/SecurityConfig.java
  32. 33
      src/main/java/com/gcc/swm_services/configuration/ThymeleafConfig.java
  33. 71
      src/main/java/com/gcc/swm_services/configuration/WebMvcConfig.java
  34. 491
      src/main/java/com/gcc/swm_services/controller/APIController.java
  35. 157
      src/main/java/com/gcc/swm_services/controller/AdminController.java
  36. 60
      src/main/java/com/gcc/swm_services/controller/CustomErrorController.java
  37. 23
      src/main/java/com/gcc/swm_services/controller/DateTimeUtil.java
  38. 30
      src/main/java/com/gcc/swm_services/controller/FileController.java
  39. 36
      src/main/java/com/gcc/swm_services/controller/MainController.java
  40. 184
      src/main/java/com/gcc/swm_services/controller/MenuController.java
  41. 6
      src/main/java/com/gcc/swm_services/controller/login.java
  42. 62
      src/main/java/com/gcc/swm_services/entity/AppModuleAccessEntity.java
  43. 80
      src/main/java/com/gcc/swm_services/entity/AppModuleEntity.java
  44. 87
      src/main/java/com/gcc/swm_services/entity/AppUserEntity.java
  45. 62
      src/main/java/com/gcc/swm_services/entity/AppUserGroupEntity.java
  46. 70
      src/main/java/com/gcc/swm_services/entity/MenuItemAccessEntity.java
  47. 96
      src/main/java/com/gcc/swm_services/entity/MenuItemEntity.java
  48. 79
      src/main/java/com/gcc/swm_services/entity/SubMenuItemAccessEntity.java
  49. 104
      src/main/java/com/gcc/swm_services/entity/SubMenuItemEntity.java
  50. 16
      src/main/java/com/gcc/swm_services/entity/UserActivityLog.java
  51. 41
      src/main/java/com/gcc/swm_services/entity/UserInfoEntity.java
  52. 331
      src/main/java/com/gcc/swm_services/interceptor/AppInterceptor.java
  53. 28
      src/main/java/com/gcc/swm_services/modeldata/ErrorResponse.java
  54. 28
      src/main/java/com/gcc/swm_services/repository/AppModuleAccessRepository.java
  55. 28
      src/main/java/com/gcc/swm_services/repository/AppModuleRepository.java
  56. 10
      src/main/java/com/gcc/swm_services/repository/AppUserGroupRepository.java
  57. 18
      src/main/java/com/gcc/swm_services/repository/AppUserRepository.java
  58. 30
      src/main/java/com/gcc/swm_services/repository/MenuItemAccessRepository.java
  59. 20
      src/main/java/com/gcc/swm_services/repository/MenuItemRepository.java
  60. 34
      src/main/java/com/gcc/swm_services/repository/SubMenuItemAccessRepository.java
  61. 33
      src/main/java/com/gcc/swm_services/repository/SubMenuItemRepository.java
  62. 6
      src/main/java/com/gcc/swm_services/repository/UserActivityLogRepository.java
  63. 8
      src/main/java/com/gcc/swm_services/repository/UserInfoRepository.java
  64. 37
      src/main/java/com/gcc/swm_services/service/Base64Util.java
  65. 19
      src/main/java/com/gcc/swm_services/service/CustomUserDetails.java
  66. 81
      src/main/java/com/gcc/swm_services/service/CustomUserDetailsService.java
  67. 188
      src/main/java/com/gcc/swm_services/service/LoginUserInfo.java
  68. 8
      src/main/java/com/gcc/swm_services/service/UserActivityService.java
  69. 11
      src/main/java/com/gcc/swm_services/service/UserActivityTimelineService.java
  70. 163
      src/main/java/com/gcc/swm_services/swm/controller/AdminController.java
  71. 35
      src/main/java/com/gcc/swm_services/swm/controller/DropDownApiController.java
  72. 70
      src/main/java/com/gcc/swm_services/swm/controller/MainController.java
  73. 118
      src/main/java/com/gcc/swm_services/swm/controller/SwmAdminApiController.java
  74. 193
      src/main/java/com/gcc/swm_services/swm/controller/SwmApiController.java
  75. 362
      src/main/java/com/gcc/swm_services/swm/service/AddDetailsService.java
  76. 37
      src/main/java/com/gcc/swm_services/swm/service/DropDownService.java
  77. 2
      src/main/resources/application-dev.properties
  78. 2
      src/main/resources/application-prod.properties
  79. 4
      src/main/resources/application.properties
  80. 14
      src/main/resources/templates/fragments/modules/base/footer.html
  81. 1541
      src/main/resources/templates/fragments/modules/base/head.html
  82. 68
      src/main/resources/templates/fragments/modules/base/header.html
  83. 1543
      src/main/resources/templates/fragments/modules/base/login-head.html
  84. 644
      src/main/resources/templates/fragments/modules/base/script.html
  85. 301
      src/main/resources/templates/index.html
  86. 236
      src/main/resources/templates/login.html
  87. 529
      src/main/resources/templates/modules/admin/user-group-access.html
  88. 448
      src/main/resources/templates/modules/admin/user-list.html
  89. 209
      src/main/resources/templates/modules/dataentry/batchbyid.html
  90. 322
      src/main/resources/templates/modules/dataentry/batches.html
  91. 43
      src/main/resources/templates/modules/dataentry/dashboard.html
  92. 1025
      src/main/resources/templates/modules/dataentry/newentry.html
  93. 43
      src/main/resources/templates/modules/dataentry/notices.html
  94. 1191
      src/main/resources/templates/modules/dataentry/updateform.html
  95. 582
      src/main/resources/templates/modules/dataentry/updation.html
  96. 875
      src/main/resources/templates/modules/dataentry/verification.html
  97. 43
      src/main/resources/templates/modules/dataentry_admin/attendance.html
  98. 412
      src/main/resources/templates/modules/dataentry_admin/batches.html
  99. 43
      src/main/resources/templates/modules/dataentry_admin/dashboard.html
  100. 43
      src/main/resources/templates/modules/dataentry_admin/others.html

3
.vscode/settings.json

@ -0,0 +1,3 @@
{
"java.configuration.updateBuildConfiguration": "interactive"
}

9
pom.xml

@ -10,9 +10,9 @@
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
<groupId>com.gcc</groupId> <groupId>com.gcc</groupId>
<artifactId>election</artifactId>
<artifactId>rdo_login</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>election</name>
<name>rdo_login</name>
<description>Project for Allocating polling persons</description> <description>Project for Allocating polling persons</description>
<url/> <url/>
<licenses> <licenses>
@ -101,11 +101,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>in.gov.chennaicorporation</groupId>
<artifactId>gccoffice</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

102
src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java

@ -1,102 +0,0 @@
package com.gcc.election.admindataentry.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.election.admindataentry.service.BatchService;
@RestController
@RequestMapping("/election/api/dataentryadmin")
public class BatchApiController {
@Autowired
private BatchService batchService;
@GetMapping("/getalldepartments")
public List<Map<String, Object>> getDepartments() {
return batchService.getAllDepartment();
}
@GetMapping("/getallofficenames")
public List<Map<String, Object>> getofficebydept(@RequestParam int deptId) {
return batchService.getAllOfficenames(deptId);
}
// save the batch creation details
@PostMapping("/savebatchdeatils")
public ResponseEntity<String> saveBatch(
@RequestParam String receivedate,
@RequestParam int department,
@RequestParam int officename,
@RequestParam int noofapplication,
@RequestParam String userid) {
try {
String response = batchService.saveBatchDetails(receivedate, department, officename, noofapplication,userid);
return ResponseEntity.ok(response);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error saving data: " + e.getMessage());
}
}
// using data table
@GetMapping("/getallbatches")
public List<Map<String, Object>> getAllBatches() {
return batchService.getAllBatches();
}
// modal box data
@GetMapping("/getbatchbyId")
public ResponseEntity<?> getBatchById(@RequestParam int id) {
Map<String, Object> batch = batchService.getBatchById(id);
System.out.println("batch" + batch);
return ResponseEntity.ok(batch);
}
// update the batch details
@PostMapping("/updatebatch")
public ResponseEntity<?> updatebatch(
@RequestParam int id,
@RequestParam int noofapplication,
@RequestParam String userId) {
try {
batchService.updateBatch(id, noofapplication,userId);
return ResponseEntity.ok("Updated Successfully");
}
catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error updating batch: " + e.getMessage());
}
}
}

34
src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java

@ -1,34 +0,0 @@
package com.gcc.election.admindataentry.controller;
import com.gcc.election.admindataentry.service.ChecklistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/election/api/checklistadmin")
public class ChecklistApiController {
@Autowired
private ChecklistService checklistService;
@GetMapping("/getApplicants")
public ResponseEntity<?> getApplicants(@RequestParam(value = "batchNo", required = true) String batchNo,
@RequestParam(value = "fromSLno", required = true) String fromSLno,
@RequestParam(value = "toSLno", required = true) String toSLno,
@RequestParam(value = "mobileNo", required = true) String mobileNo,
@RequestParam(value = "category", required = true) String category,
@RequestParam(value = "officeName", required = true) String officeName,
@RequestParam(value = "notExist", required = true) String notExist){
return checklistService.getApplicants(batchNo, fromSLno, toSLno, mobileNo, category, officeName, notExist);
}
@PostMapping("/verifyApplicants")
public ResponseEntity<?> verifyApplicants(@RequestParam List<Integer> id) {
return checklistService.verifyApplicants(id);
}
}

69
src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java

@ -1,69 +0,0 @@
package com.gcc.election.admindataentry.controller;
import com.gcc.election.service.LoginUserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/election/dataentryadmin")
@Controller("electionDataentryAdminController")
public class Maincontroller {
@GetMapping("/dashboard")
public String dashboard(Model model) {
return "modules/dataentry_admin/dashboard";
}
@GetMapping("/batches")
public String batches(Model model) {
String loginUserId = LoginUserInfo.getLoginUserId();
if (loginUserId != null && !loginUserId.isEmpty()) {
System.out.println("String UserID: " + loginUserId);
}
model.addAttribute("loginUserId",loginUserId);
return "modules/dataentry_admin/batches";
}
@GetMapping("/updation")
public String updation(Model model) {
return "modules/dataentry_admin/updation";
}
@GetMapping("/verification")
public String verification(Model model) {
return "modules/dataentry_admin/verification";
}
@GetMapping("/training")
public String training(Model model) {
return "modules/dataentry_admin/training";
}
@GetMapping("/attendance")
public String attendance(Model model) {
return "modules/dataentry_admin/attendance";
}
@GetMapping("/others")
public String others(Model model) {
return "modules/dataentry_admin/others";
}
}

48
src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java

@ -1,48 +0,0 @@
package com.gcc.election.admindataentry.controller;
import com.gcc.election.admindataentry.service.TrainingService;
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.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/election/api/trainingadmin")
public class TrainingApiController {
@Autowired
private TrainingService trainingService;
@GetMapping("getAllConstituency")
public List<Map<String, Object>> getAllConstituency() {
return trainingService.getAllConstituency();
}
@GetMapping("getAllCentre")
public List<Map<String, Object>> getAllCentre() {
return trainingService.getAllCentre();
}
@GetMapping("getAddressByCode")
public List<Map<String, Object>> getAddressByCode(int code) {
return trainingService.getAddressByCode(code);
}
@GetMapping("getAllCategory")
public List<Map<String, Object>> getAllCategory() {
return trainingService.getAllCategory();
}
}

137
src/main/java/com/gcc/election/admindataentry/service/BatchService.java

@ -1,137 +0,0 @@
package com.gcc.election.admindataentry.service;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
@Service
public class BatchService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getAllDepartment() {
String sql = " SELECT * FROM dept_master where is_active = '1' AND is_delete = '0' ORDER BY dept_name ASC ";
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAllOfficenames(Integer deptId) {
String sql = " SELECT id,office_name FROM office_details where dept_id = ? ";
return jdbcTemplate.queryForList(sql,deptId);
}
// batch creation service
public String saveBatchDetails(String receivedate, int department, int officename, int noofapplication,String userid) throws IOException {
String sql = "INSERT INTO batch_master " +
"(rec_date, dept_id, office_id, noof_application,created_by) " +
"VALUES (?, ?, ?, ?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
int result = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, receivedate);
ps.setInt(2, department);
ps.setInt(3, officename);
ps.setInt(4, noofapplication);
ps.setString(5,userid);
return ps;
}, keyHolder);
if (result > 0) {
int generatedId = keyHolder.getKey().intValue();
String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String refId = prefix + generatedId;
String updateSQL = "UPDATE batch_master SET batch_ref_id = ? WHERE id = ?";
jdbcTemplate.update(updateSQL, refId, generatedId);
return refId;
}
return "error";
}
public List<Map<String, Object>> getAllBatches() {
String sql = "select bm.id,DATE_FORMAT(bm.rec_date, '%d-%m-%Y') AS rec_date,bm.noof_application,od.office_name,dm.dept_name " +
" from batch_master bm " +
" LEFT JOIN dept_master dm ON dm.dept_id = bm.dept_id " +
" LEFT JOIN office_details od ON od.id = bm.office_id ";
System.out.println("sql " + sql);
return jdbcTemplate.queryForList(sql);
}
public Map<String, Object> getBatchById(int id) {
String sql = "SELECT bm.id, DATE_FORMAT(bm.rec_date, '%Y-%m-%d') AS rec_date, bm.noof_application,DATE_FORMAT(bm.rec_date, '%d-%m-%Y') AS received_date,om.id as office_id,dm.dept_id as dept_id, "
+ "dm.dept_name, "
+ "om.office_name "
+ "FROM batch_master bm "
+ "LEFT JOIN dept_master dm ON dm.dept_id = bm.dept_id "
+ "LEFT JOIN office_details om ON om.id = bm.office_id "
+ "WHERE bm.id = ?";
return jdbcTemplate.queryForMap(sql, id);
}
// update batch api
public void updateBatch(int id, int noofapplication,String userId) {
String insertHistorySql =
"INSERT INTO batch_master_log " +
"(batch_id,batch_ref_id, rec_date, dept_id, office_id, noof_application, from_slno, to_slno, dataentry_dt, " +
" photo_scanned_dt, noofphoto_missing, cklist_dt,cdate ,update_date, status,created_by) " +
"SELECT id, batch_ref_id, rec_date, dept_id, office_id, noof_application, from_slno, to_slno, dataentry_dt, " +
" photo_scanned_dt, noofphoto_missing, cklist_dt, cdate,update_date, status,created_by " +
"FROM batch_master WHERE id = ?";
System.out.println("insertHistorySql"+insertHistorySql);
jdbcTemplate.update(insertHistorySql, id);
String updateSql = "UPDATE batch_master SET noof_application = ? , updated_by = ? WHERE id = ?";
jdbcTemplate.update(updateSql, noofapplication, userId,id);
}
}

139
src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java

@ -1,139 +0,0 @@
package com.gcc.election.admindataentry.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ChecklistService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Transactional
public ResponseEntity<?> getApplicants(String batchNo, String fromSLno, String toSLno, String mobileNo, String category, String officeName, String notExist) {
Map<String, Object> result = new HashMap<>();
try {
StringBuilder sql = new StringBuilder("SELECT " +
" ppn.*, " +
" dm.*, " +
" d.*, " +
" od.*, " +
" CONCAT( " +
" COALESCE(od.address1, ''), " +
" ' ', " +
" COALESCE(od.address2, ''), " +
" ' ', " +
" COALESCE(od.address3, ''), " +
" ' ', " +
" COALESCE(od.pincode, '') " +
" ) AS address, " +
" ac_native.ac_name AS native_constituency, " +
" ac_reside.ac_name AS residential_constituency, " +
" ac_elector.ac_name AS elector_constituency, " +
" ac_work.ac_name AS working_constituency "+
"FROM poll_person_new ppn " +
"LEFT JOIN dept_master dm " +
" ON ppn.dept = dm.dept_id " +
"LEFT JOIN designation d " +
" ON ppn.designation_id = d.desig_id " +
"LEFT JOIN office_details od " +
" ON ppn.office_id = od.id " +
" LEFT JOIN ac_list_all ac_native " +
" ON ac_native.ac_no = ppn.native_ac_no " +
" LEFT JOIN ac_list_all ac_reside " +
" ON ac_reside.ac_no = ppn.reside_ac_no " +
"LEFT JOIN ac_list_all ac_elector " +
" ON ac_elector.ac_no = ppn.elector_ac_no " +
"LEFT JOIN ac_list_all ac_work " +
" ON ac_work.ac_no = od.work_ac_no " +
"WHERE 1=1 ");
List<Object> params = new ArrayList<>();
if(!batchNo.isEmpty()){
sql.append(" AND batch_no = ? ");
params.add(batchNo);
}
if (!fromSLno.isEmpty() && toSLno.isEmpty()) {
sql.append(" AND slno = ? ");
params.add(fromSLno);
}
if (!fromSLno.isEmpty() && !toSLno.isEmpty()) {
sql.append(" AND slno BETWEEN ? AND ? ");
params.add(fromSLno);
params.add(toSLno);
}
if (!mobileNo.isEmpty()) {
sql.append(" AND r_mobile_no = ? ");
params.add(mobileNo);
}
if (!category.isEmpty()) {
sql.append(" AND category_id = ? ");
params.add(category);
}
if (!officeName.isEmpty()) {
sql.append(" AND office_id = ? ");
params.add(officeName);
}
if (!notExist.isEmpty()) {
if(notExist.equalsIgnoreCase("voterid")) {
sql.append(" AND (elector_epic_no IS NULL OR elector_epic_no = '') ");
} else if (notExist.equalsIgnoreCase("mobile")) {
sql.append(" AND (r_mobile_no IS NULL OR r_mobile_no = '') ");
} else if (notExist.equalsIgnoreCase("both")) {
sql.append(" AND (r_mobile_no IS NULL OR r_mobile_no = '') AND (elector_epic_no IS NULL OR elector_epic_no = '') ");
}
}
List<Map<String, Object>> data = jdbcTemplate.queryForList(sql.toString(), params.toArray());
if (!data.isEmpty()) {
result.put("message", "success");
result.put("data", data);
} else {
result.put("message", "No Data Found");
result.put("data", "No Data Found");
}
return ResponseEntity.ok(result);
} catch (Exception e) {
e.printStackTrace();
result.put("Message", "Error");
result.put("Error", "Failed to fetch Checklist data: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
// verification of applicants
public ResponseEntity<String> verifyApplicants(List<Integer> ids) {
String sql = "UPDATE poll_person_new SET poll_person_verify = 1 WHERE id = ?";
for (Integer id : ids) {
jdbcTemplate.update(sql, id);
}
return ResponseEntity.ok("success");
}
}

59
src/main/java/com/gcc/election/admindataentry/service/TrainingService.java

@ -1,59 +0,0 @@
package com.gcc.election.admindataentry.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
@Service
public class TrainingService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getAllConstituency() {
String sql = " SELECT * FROM ac_list_all where dist_no = '2' ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAllCentre() {
String sql = " SELECT c_code,c_name FROM trgcen ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAddressByCode(int code) {
String sql = " SELECT c_address FROM trgcen where c_code=? ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql,code);
}
public List<Map<String, Object>> getAllCategory() {
String sql = " select distinct(category) from designation ORDER BY " +
" LENGTH(category)," +
" category; ";
System.out.println("sql"+sql);
return jdbcTemplate.queryForList(sql);
}
}

94
src/main/java/com/gcc/election/configuration/DataSourceConfig.java

@ -1,94 +0,0 @@
package com.gcc.election.configuration;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
private static String host = "localhost:3306";
private static String dbpassword = "root";
// 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";
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "appEntityManagerFactory",
transactionManagerRef = "appTransactionManager",
basePackages = {"com.gcc.election.repository"})
public static class MysqlAppDataSourceConfig {
@Primary
@Bean(name = "mysqlAppDataSource")
public DataSource mysqlAppDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://"+host+"/gcc_election_apps");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
/*
@Bean(name = "mysqlAppJdbcTemplate")
public JdbcTemplate mysqlAppJdbcTemplate(@Qualifier("mysqlAppDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
*/
@Primary
@Bean(name="appEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier("mysqlAppDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("com.gcc.election.entity");
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
@Primary
@Bean(name = "appTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("appEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
//////////////////////////////(For GCC Election) ////////////////////////
@Bean(name = "mysqlGccElectionDataSource")
public DataSource mysqlMayorPetitionDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://"+host+"/gcc_election");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
}

89
src/main/java/com/gcc/election/configuration/SecurityConfig.java

@ -1,89 +0,0 @@
package com.gcc.election.configuration;
import javax.persistence.Basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.gcc.election.service.CustomUserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private final CustomUserDetailsService customUserDetailsService;
@Autowired
public SecurityConfig(CustomUserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**", "/assets/**", "/api/**","/images/**","/election/static/**", "/election/assets/**", "/election/api/**","/election/images/**","/election/files/**");
//.antMatchers("/election/static/**", "/election/assets/**", "/election/api/**","/election/images/**");
//.antMatchers("/assets/**", "/css/**", "/js/**", "/images/**", "/fonts/**"); // Add the paths to your static resources here
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
// Configure authorization (URL-based access control)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and() // Enable CORS
.csrf().disable() // Disable CSRF protection for simplicity (Enable if needed)
.authorizeRequests()
.antMatchers("/election/error").permitAll()
.antMatchers("/election/login").permitAll() // Add the login URL
.antMatchers("/election/admin/**").hasRole("ADMIN") // Add the admin URLs
.antMatchers("/election/**").hasAnyRole("ADMIN","USER") // Add other URLs
//.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/election/login") // Customize the login page URL
.defaultSuccessUrl("/election") // Include the success URL
.permitAll()
.and()
.logout()
.logoutUrl("/election/logout") // Include the logout URL
.logoutSuccessUrl("/election/login") // Include the success logout URL
.permitAll()
.and()
.sessionManagement()
.sessionFixation()
.migrateSession(); // or .none(), .newSession()
/*
// Print role values
http.authorizeRequests().anyRequest().authenticated().and().formLogin().successHandler((request, response, authentication) -> {
System.out.println("User Roles: ");
authentication.getAuthorities().forEach(authority -> System.out.println(authority.getAuthority()));
System.out.println();
response.sendRedirect("/election");
});
*/
}
@Basic
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

31
src/main/java/com/gcc/election/configuration/ThymeleafConfig.java

@ -1,31 +0,0 @@
package com.gcc.election.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
//@Configuration
//public class ThymeleafConfig {
//
// @Bean
// public ITemplateResolver templateResolver() {
// SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
// templateResolver.setPrefix("classpath:/templates/"); // Set your Thymeleaf templates prefix here
// templateResolver.setSuffix(".html");
// templateResolver.setTemplateMode(TemplateMode.HTML);
// templateResolver.setCacheable(false); // Disable template caching for development environment
// return templateResolver;
// }
//
// @Bean
// public SpringTemplateEngine templateEngine() {
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setTemplateResolver(templateResolver());
// return templateEngine;
// }
//
//}

74
src/main/java/com/gcc/election/configuration/WebMvcConfig.java

@ -1,74 +0,0 @@
package com.gcc.election.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.interceptor.AppInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
private final String uploadDirectory;
private AppModuleAccessRepository appModuleAccessRepository;
private MenuItemAccessRepository menuItemAccessRepository;
private SubMenuItemAccessRepository subMenuItemAccessRepository;
private AppModuleRepository appModuleRepository;
private MenuItemRepository menuItemRepository;
private SubMenuItemRepository subMenuItemRepository;
private final Environment environment;
@Autowired
public WebMvcConfig(
@Value("${file.upload.directory}") String uploadDirectory,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
Environment environment) {
this.uploadDirectory = uploadDirectory;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.environment = environment;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppInterceptor(
appModuleAccessRepository,
menuItemAccessRepository,
subMenuItemAccessRepository,
appModuleRepository,
menuItemRepository,
subMenuItemRepository,
environment));
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadDirectory +"/");
}
}

470
src/main/java/com/gcc/election/controller/APIController.java

@ -1,470 +0,0 @@
package com.gcc.election.controller;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.AppUserRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.repository.UserActivityLogRepository;
import com.gcc.election.service.LoginUserInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@RequestMapping("/election/api")
@RestController
public class APIController {
List<AppUserEntity> getAppUserEntities;
@Autowired
private HttpServletRequest request;
@Autowired
private AppUserRepository appUserRepository;
@Autowired
private LoginUserInfo loginUserInfo;
List<UserActivityLog> getActivityLogs;
@Autowired
private UserActivityLogRepository userActivityLogRepository;
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<MenuItemAccessEntity> getMenuItemAccessEntities;
List<SubMenuItemAccessEntity> getSubMenuItemAccessEntities;
@Autowired
private AppModuleAccessRepository appModuleAccessRepository;
@Autowired
private MenuItemAccessRepository menuItemAccessRepository;
@Autowired
private SubMenuItemAccessRepository subMenuItemAccessRepository;
List<AppModuleEntity> getAppModuleEntities;
List<MenuItemEntity> getMenuItemEntities;
List<SubMenuItemEntity> getSubMenuItemEntities;
@Autowired
private AppModuleRepository appModuleRepository;
@Autowired
private MenuItemRepository menuItemRepository;
@Autowired
private SubMenuItemRepository subMenuItemRepository;
@Autowired
public APIController(
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
UserActivityLogRepository userActivityLogRepository) {
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.userActivityLogRepository = userActivityLogRepository;
}
// Encode to Base64
@GetMapping(value="/encodeBase64")
public static String encodeBase64(@RequestParam String string) {
String value=string;
byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes());
return new String(encodedBytes);
}
// Decode from Base64
@GetMapping(value="/decodeBase64")
public static String decodeBase64(@RequestParam String string) {
String encodedValue=string;
byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
return new String(decodedBytes);
}
@GetMapping(value="/getAccessTree")
public String getAccessTreeHTML(@RequestParam String groupId,@RequestParam String groupName) {
getAppModuleEntities = appModuleRepository.showAll();
String accessHTML = "";
String accessTableHTML = "";
//String MenuHTML = "";
String isSelected = "";
//String subMenuHTML = "";
String groupNameHTML = "<span class=\"badge badge-pill badge-primary mb-1\">"+groupName+"</span>";
for (AppModuleEntity moduleName : getAppModuleEntities) {
// ID to check
Integer desiredId = moduleName.getId();
// Check if the ID exists in the list of entities
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId,desiredId.toString());
// Check Module Id Access
if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; }
accessHTML = accessHTML+"<li><input id=\"m"+moduleName.getId()+"\" type=\"checkbox\" data-type=\"parent\" value=\"m_"+desiredId+"\" "+isSelected+"/>&nbsp;<label for=\"m"+moduleName.getId()+"\" style=\"background-color:#000;color:#fff;\">&nbsp;&nbsp;<i class=\""+moduleName.getIcon()+"\"></i> "+moduleName.getName()+"&nbsp;&nbsp;</label>";
getMenuItemEntities = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItemEntities) {
String mmid = desiredId+"_"+menuItem.getId();
// Check if the ID exists in the list of entities
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString());
// Check Module Id Access
if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; }
if(menuItem.getHasSub()) {
getSubMenuItemEntities = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getSubMenuItemEntities) {
String isSelected2 = "";
String smid = desiredId+"_"+menuItem.getId()+"_"+subMenuItem.getId();
// Check if the ID exists in the list of entities
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString(),subMenuItem.getId().toString());
// Check Module Id Access
if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { isSelected2 = "checked"; } else { isSelected2 = ""; }
subSubMenuHTML = subSubMenuHTML+"<li><input id=\"sm"+subMenuItem.getId()+"\" type=\"checkbox\" data-type=\"sub-child\" value=\"sm_"+smid+"\" "+isSelected2+"/>&nbsp;<label for=\"sm"+subMenuItem.getId()+"\"><i class=\""+subMenuItem.getIcon()+"\"></i> "+subMenuItem.getName()+"</label></li>";
}
if(subSubMenuHTML.equals(""))
{
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" value=\"mm_"+mmid+"\" "+isSelected+"/>&nbsp;<label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" value=\"mm_"+mmid+"\" "+isSelected+"/>&nbsp;<label for=\"mm"+menuItem.getId()+"\">&nbsp;<i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label> <ul>"+subSubMenuHTML+"</ul></li>";
}
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" value=\"mm_"+mmid+"\" "+isSelected+"/>&nbsp;<label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
}
accessHTML = accessHTML+"<ul>"+subMenuHTML+"</ul></li>";
subMenuHTML = "";
}
accessTableHTML = groupNameHTML+"<ul id=\"tree\" class=\"checktree\" style=\"padding-left:25px;\" >"+accessHTML+"</ul>";
return accessTableHTML;
}
@PostMapping("/saveGroupAccessData")
public String saveGroupAccessData(@RequestBody Map<String, Object> requestBody) {
@SuppressWarnings("unchecked")
List<String> checkedData = (List<String>) requestBody.get("checkedData");
String groupId = (String) requestBody.get("groupId");
String dataType[]= {"","", "module","menu","submenu"};
if (groupId != null) {
System.out.println("groupid value: " + groupId);
// Set isActive = false based on groupId
appModuleAccessRepository.updateActiveStatus(false,groupId);
menuItemAccessRepository.updateActiveStatus(false,groupId);
subMenuItemAccessRepository.updateActiveStatus(false,groupId);
// Now update as per input data
if (checkedData != null) {
for (String data : checkedData) {
System.out.println(data);
// m_x -> Module Value (moduleId) -> 2
// mm_x_x -> Menu Value (moduleId,menuId) ->3
// sm_x_x_x -> SubMenu Value (moduleId, menuId, submenuId) ->4
String[] dataValue = data.split("_");
Integer dataLength = dataValue.length;
System.out.println(dataLength +" ==> "+dataType[dataLength]);
if(dataValue.length==2) { // Module
// Check if the ID exists in the list of entities
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, dataValue[1]);
if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) {
appModuleAccessRepository.update(true,groupId,dataValue[1]);
}
else {
appModuleAccessRepository.insert(groupId,dataValue[1]);
}
}
else if(dataValue.length==3) { // Menu
// Check if the ID exists in the list of entities
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2]);
if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) {
menuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2]);
}
else {
menuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2]);
}
}
else if(dataValue.length==4) { // SubMenu
// Check if the ID exists in the list of entities
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2], dataValue[3]);
if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) {
subMenuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2],dataValue[3]);
}
else {
subMenuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2],dataValue[3]);
}
}
}
}
}
return "";
}
@GetMapping(value="/getUserProfileBasic")
public String getUserProfileBasic(@RequestParam String userId) {
//String userHtml ="";
String userProfileHtml ="";
//String userProfileTimelineHtml ="";
getAppUserEntities = appUserRepository.showById(userId);
for (AppUserEntity appUserEntity : getAppUserEntities) {
userProfileHtml = ""
+ " "
+ " <div class='card mb-1'>"
+ " <div class='card-body'>"
+ " <div class='text-center'>"
+ " <img src='/assets/images/users/user.jpg' class='rounded' width='150'>\n"
+ " <h4 class='card-title mt-10'>"+appUserEntity.getUserid().getName()+"</h4>\n"
+ " <p class='text-muted'>Front End Developer</p>\n"
+ " </div>\n"
+ " </div>"
+ " <hr class='mb-0 mt-0'> \n"
+ " <div class='card-body'> \n"
+ " <small class='text-muted d-block'>Email address </small>\n"
+ " <h8>"+appUserEntity.getUserid().getEmail()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Phone</small>\n"
+ " <h8>"+appUserEntity.getUserid().getPhone()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Role</small>\n"
+ " <h8>"+appUserEntity.getRoles()+"</h8>\n"
+ " <small class='text-muted d-block pt-10'>Access Group</small>\n"
+ " <h8>"+appUserEntity.getUsergroup_id().getName()+"</h8>\n"
+ " </div>\n"
+ " </div>\n"
+ " ";
}
return userProfileHtml;
}
@GetMapping(value="/getUserProfile")
public String getUserProfile(@RequestParam String userId) {
String userHtml ="";
String userProfileHtml ="";
String userProfileTimelineHtml ="";
String userIp = getUserIP();
getAppUserEntities = appUserRepository.showById(userId);
for (AppUserEntity appUserEntity : getAppUserEntities) {
userProfileHtml = ""
+ " <div class='col-lg-4 col-md-5'>"
+ " <div class='card mb-1'>"
+ " <div class='card-body'>"
+ " <div class='text-center'>"
+ " <img src='/assets/images/users/user.jpg' class='rounded' width='150'>\n"
+ " <h4 class='card-title mt-10'>"+appUserEntity.getUserid().getName()+"</h4>\n"
+ " <p class='text-muted'>Front End Developer</p>\n"
+ " <p class='text-muted'>"+userIp+"</p>\n"
+ " </div>\n"
+ " </div>"
+ " <hr class='mb-0 mt-0'> \n"
+ " <div class='card-body'> \n"
+ " <small class='text-muted d-block'>Email address </small>\n"
+ " <h8>"+appUserEntity.getUserid().getEmail()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Phone</small>\n"
+ " <h8>"+appUserEntity.getUserid().getPhone()+"</h8> \n"
+ " <small class='text-muted d-block pt-10'>Role</small>\n"
+ " <h8>"+appUserEntity.getRoles()+"</h8>\n"
+ " <small class='text-muted d-block pt-10'>Access Group</small>\n"
+ " <h8>"+appUserEntity.getUsergroup_id().getName()+"</h8>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>";
userProfileTimelineHtml = ""
+ "<div class='col-lg-8 col-md-7'>"
+ " <div class='card'>"
+ " <ul class='nav nav-pills custom-pills' id='pills-tab' role='tablist'>"
+ " <li class='nav-item'>"
+ " <a class='nav-link active' id='pills-timeline-tab' data-toggle='pill' href='#current-month' role='tab' aria-controls='pills-timeline' aria-selected='true'>Timeline</a>"
+ " </li>"
+ " <li class='nav-item'>"
+ " <a class='nav-link' id='pills-profile-tab' data-toggle='pill' href='#last-month' role='tab' aria-controls='pills-profile' aria-selected='false'>Profile</a>"
+ " </li>"
+ " </ul>"
+ " <div class='tab-content' id='pills-tabContent'>"
+ " <div class='tab-pane fade active show' id='current-month' role='tabpanel' aria-labelledby='pills-timeline-tab'>"
+ userTimeLine(appUserEntity.getUserid().getUserid().toString(),appUserEntity.getUserid().getName(),"user.jpg")
+ " </div>"
+ " </div>"
+ " </div>"
+ "</div>";
userHtml ="<div class='row'>" + userProfileHtml + userProfileTimelineHtml + "</div>";
}
return userHtml;
}
public String userTimeLine(String userid, String userName, String img) {
String userTimeLineHTML = "";
getActivityLogs = userActivityLogRepository.findByUserIdOrderByTimestampDesc(userid);
for (UserActivityLog userActivityLog : getActivityLogs) {
userTimeLineHTML += ""
+ " <div class='sl-item'>"
+ " <div class='sl-left'> "
+ " <img src='/assets/images/users/"+img+"' alt='user' class='rounded-circle'> "
+ " </div>"
+ " <div class='sl-right'>"
+ " <div>"
+ " <a href='javascript:void(0)' class='link'>"+userName+"</a> "
+ " <span class='sl-date'>"+dateFormat(userActivityLog.getTimestamp().toString())+"</span>"
+ " <blockquote class='mt-10'>"
+ " "+userActivityLog.getActivityType()
+ " </blockquote>"
+ " </div>"
+ " </div>"
+ " </div><hr>";
}
userTimeLineHTML = ""
+ "<div class='card-body'>"
+ " <div class='profiletimeline mt-0'>"
+ userTimeLineHTML
+ " </div>"
+ "</div>";
return userTimeLineHTML;
}
public String dateFormat(String timestampString) {
//String timestampString = "2023-12-28T16:21:24";
LocalDateTime timestamp = LocalDateTime.parse(timestampString, DateTimeFormatter.ISO_DATE_TIME);
// Define the desired date-time format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
// Format the timestamp
String formattedTimestamp = timestamp.format(formatter);
//System.out.println(formattedTimestamp);
return formattedTimestamp.toUpperCase();
}
public String getUserIP() {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
@GetMapping(value="/passwordGenerator")
public String passwordGenerator(@RequestParam(value = "password", required = false) String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String rawPassword = password;
String encodedPassword = passwordEncoder.encode(rawPassword);
return encodedPassword;
}
@PostMapping(value="/resetPassword")
public String resetPassword(
@RequestParam(value = "", required = false) String userid,
@RequestParam(value = "", required = false) String oldpassword,
@RequestParam(value = "", required = false) String newpassword
) {
System.out.println(userid+" : "+oldpassword+" : "+newpassword);
String oldPasswordTxt=oldpassword; //passwordGenerator(oldpassword);
String newPasswordTxt=newpassword; //passwordGenerator(newpassword);
String rawPasswordTxt=newpassword;
System.out.println(oldPasswordTxt+" : "+newPasswordTxt+" : "+rawPasswordTxt);
String response = loginUserInfo.resetPassword(userid,oldPasswordTxt,newPasswordTxt,rawPasswordTxt);
return response;
}
@PostMapping(value="/userCheck")
public List<Map<String, Object>> userCheck(
@RequestParam(value = "", required = false) String usernametxt,
@RequestParam(value = "", required = false) String passwordtxt
) {
System.out.println("HRM Service : "+usernametxt+" : "+passwordtxt);
List<Map<String, Object>> response = loginUserInfo.userCheck(usernametxt,passwordtxt);
return response;
}
// @GetMapping(value="/getDailyKural")
// public List getDailyKural() {
// return loginUserInfo.getDailyContent();
// }
}

148
src/main/java/com/gcc/election/controller/AdminController.java

@ -1,148 +0,0 @@
package com.gcc.election.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.election.entity.AppUserGroupEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.AppUserGroupRepository;
import com.gcc.election.repository.AppUserRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.service.LoginUserInfo;
@RequestMapping("/election/admin")
@Controller("electionAdminController")
public class AdminController {
private final AppUserRepository appUserRepository;
private final AppUserGroupRepository appUserGroupRepository;
private final AppModuleRepository appModuleRepository;
private final MenuItemRepository menuItemRepository;
private final SubMenuItemRepository subMenuItemRepository;
@Autowired
public AdminController(
AppUserRepository appUserRepository,
AppUserGroupRepository appUserGroupRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository) {
this.appUserRepository = appUserRepository;
this.appUserGroupRepository = appUserGroupRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
}
@GetMapping({"", "/", "/index"})
public String main(Model model) {
String userId = LoginUserInfo.getLoginUserId();
if (userId != null && !userId.isEmpty()) {
System.out.println("String UserID: " + userId);
}
return "modules/admin/index";
}
@GetMapping("/user-list")
public String userList(Model model) {
model.addAttribute("userlist",getUser());
return "modules/admin/user-list";
}
@GetMapping("/user-group-list")
public String userGroupList(Model model) {
model.addAttribute("userGroupList",getUserGroup());
return "modules/admin/user-group-list";
}
@GetMapping("/user-group-access")
public String userGroupAccess(Model model) {
String accessTableHTML = getAccessTreeHTML();
model.addAttribute("userGroupList",getUserGroup());
model.addAttribute("accessHTML",accessTableHTML);
return "modules/admin/user-group-access";
}
//////////////////////////////////////// (Functions) ////////////////////////////////////////
public List<AppUserEntity> getUser() {
List<AppUserEntity> appUserEntities;
appUserEntities = appUserRepository.showAll();
return appUserEntities;
}
public List<AppUserGroupEntity> getUserGroup() {
List<AppUserGroupEntity> appUserGroupEntities;
appUserGroupEntities = appUserGroupRepository.findAll();
return appUserGroupEntities;
}
public String getAccessTreeHTML() {
//List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
getAppModuleEntities = appModuleRepository.showAll();
String accessHTML = "";
String accessTableHTML = "";
//String MenuHTML = "";
//String subMenuHTML = "";
for (AppModuleEntity moduleName : getAppModuleEntities) {
accessHTML = accessHTML+"<li><input id=\"m"+moduleName.getId()+"\" type=\"checkbox\" data-type=\"parent\" value=\"\"/>&nbsp;<label for=\"m"+moduleName.getId()+"\" style=\"background-color:#000;color:#fff;\">&nbsp;&nbsp;<i class=\""+moduleName.getIcon()+"\"></i> "+moduleName.getName()+"&nbsp;&nbsp;</label>";
List<MenuItemEntity> getMenuItems;
getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItems) {
if(menuItem.getHasSub()) {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
subSubMenuHTML = subSubMenuHTML+"<li><input id=\"sm"+subMenuItem.getId()+"\" type=\"checkbox\" data-type=\"sub-child\"/> <label for=\"sm"+subMenuItem.getId()+"\"><i class=\""+subMenuItem.getIcon()+"\"></i> "+subMenuItem.getName()+"</label></li>";
}
if(subSubMenuHTML.equals(""))
{
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\" /> <label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\"/> <label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label> <ul>"+subSubMenuHTML+"</ul></li>";
}
}
else {
subMenuHTML = subMenuHTML+"<li><input id=\"mm"+menuItem.getId()+"\" type=\"checkbox\" data-type=\"child\"/> <label for=\"mm"+menuItem.getId()+"\"><i class=\""+menuItem.getIcon()+"\"></i> "+menuItem.getName()+"</label></li>";
}
}
accessHTML = accessHTML+"<ul>"+subMenuHTML+"</ul></li>";
subMenuHTML = "";
}
accessTableHTML = "<ul id=\"tree\" class=\"checktree\">"+accessHTML+"</ul>";
return accessTableHTML;
}
}

37
src/main/java/com/gcc/election/controller/MainController.java

@ -1,37 +0,0 @@
package com.gcc.election.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 com.gcc.election.service.LoginUserInfo;
@RequestMapping("/election")
@Controller("electionMainController")
public class MainController {
private final LoginUserInfo loginUserInfo;
@Autowired
public MainController(LoginUserInfo loginUserInfo) {
this.loginUserInfo = loginUserInfo;
}
@GetMapping({"", "/", "/index"})
public String main(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
if (LoginUserId != null && !LoginUserId.isEmpty()) {
System.out.println("String UserID: " + LoginUserId);
}
model.addAttribute("LoginUserId",LoginUserId);
return "index";
}
@GetMapping("/widget-statistic")
public String widgetStatistic(Model model) {
return "widget-statistic";
}
}

167
src/main/java/com/gcc/election/controller/MenuController.java

@ -1,167 +0,0 @@
package com.gcc.election.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.service.LoginUserInfo;
@ControllerAdvice
public class MenuController {
private final AppModuleRepository appModuleRepository;
private final MenuItemRepository menuItemRepository;
private final SubMenuItemRepository subMenuItemRepository;
private final AppModuleAccessRepository appModuleAccessRepository;
private final MenuItemAccessRepository menuItemAccessRepository;
private final SubMenuItemAccessRepository subMenuItemAccessRepository;
@Autowired
public MenuController(AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository) {
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
}
@ModelAttribute("menuItemsHTML") // This will add the menuItems to the model for all requests
public String menuHTML() {
if(LoginUserInfo.getLoginUserId() == null || LoginUserInfo.getUserGroupId()==null) {
return "";
}
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
getAppModuleEntities = appModuleRepository.showAll();
}
else {
getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId());
String[] checkModuleId = new String[getAppModuleAccessEntities.size()];
int i=0;
for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) {
checkModuleId[i]=accessEntity.getModuleId().getId().toString();
i++;
}
getAppModuleEntities = appModuleRepository.showAllById(checkModuleId);
}
String menuHTML = "";
menuHTML = "<div class=\"nav-item\"><a href=\"/election\"><i class=\"ik ik-home\"></i><span>Dashboard</span></a></div>";
for (AppModuleEntity moduleName : getAppModuleEntities) {
menuHTML = menuHTML+"<div class=\"nav-item has-sub\"><a href=\"javascript:void(0)\"><i class=\""+moduleName.getIcon()+"\"></i><span>"+moduleName.getName()+"</span></a><div class=\"submenu-content\">";
List<MenuItemEntity> getMenuItems;
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
}
else {
List<MenuItemAccessEntity> getMenuItemAccess = menuItemAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId(), moduleName.getId().toString());
String[] checkMenuId = new String[getMenuItemAccess.size()];
int j=0;
for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) {
checkMenuId[j]=menuAccessEntity.getMenuItemId().getId().toString();
j++;
}
getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(moduleName.getId(),checkMenuId);
}
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItems) {
if(menuItem.getHasSub()) {
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if(subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML+"<a href=\""+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
else {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/election/"+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
}
if(subSubMenuHTML.equals(""))
{
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>";
}
else {
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>";
}
}
else {
List<SubMenuItemAccessEntity> getSubMenuItemAccess = subMenuItemAccessRepository.findByUserGroupIDAccess(LoginUserInfo.getUserGroupId(), moduleName.getId().toString(), menuItem.getId().toString());
String[] checkSubMenuId = new String[getSubMenuItemAccess.size()];
if(checkSubMenuId.length>0)
{
int k=0;
for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) {
checkSubMenuId[k]=subMenuItemAccessEntity.getSubMenuItemId().getId().toString();
k++;
}
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(menuItem.getId(),checkSubMenuId);
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if(subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML+"<a href=\""+subMenuItem.getUrl()+"\" class=\"menu-item\""+target+"><i class=\""+subMenuItem.getIcon()+"\"></i><span>"+subMenuItem.getName()+"</span></a>";
}
else {
subSubMenuHTML = subSubMenuHTML+"<a href=\"/election/"+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>";
}
else {
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>";
}
}
}
else {
if(menuItem.getOrderby()>0) {
subMenuHTML = subMenuHTML+"<a href=\"/election/"+menuItem.getUrl()+"\" class=\"menu-item\"><i class=\""+menuItem.getIcon()+"\"></i><span>"+menuItem.getName()+"</span></a>";
}
}
}
menuHTML = menuHTML+subMenuHTML+"</div></div>";
}
return menuHTML;
}
}

260
src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java

@ -1,260 +0,0 @@
package com.gcc.election.dataentry.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.election.dataentry.service.BatchAPIService;
@RestController
@RequestMapping("/election/api/dataentry/batch")
public class BatchAPIController {
@Autowired
private BatchAPIService batchAPIService;
// to get batch details for data entry screen (with count)
@GetMapping("/getBatchDetails")
public ResponseEntity<?> getBatchDetails() {
try {
List<Map<String, Object>> list = batchAPIService.getBatchDetails();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getbatchbyId")
public ResponseEntity<?> getBatchById(@RequestParam String id) {
try {
Map<String, Object> list = batchAPIService.getBatchById(id);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getAllDesignations")
public ResponseEntity<?> getAllDesignations(){
try {
List<Map<String, Object>> list = batchAPIService.getAllDesignations();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getPayDetails")
public ResponseEntity<?> getPayDetails(@RequestParam int DesgId) {
try {
Map<String, Object> list = batchAPIService.getPayDetailsByDesgId(DesgId);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getAllDistricts")
public ResponseEntity<?> getAllDistricts(){
try {
List<Map<String, Object>> list = batchAPIService.getAllDistricts();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getAllAclist")
public ResponseEntity<?> getAllAcList(){
try {
List<Map<String, Object>> list = batchAPIService.getAllAcList();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getOfficeDetailsById")
public ResponseEntity<?> getOfficeDetailsById(@RequestParam int officeId){
try {
List<Map<String, Object>> list = batchAPIService.getOfficeDetailsById(officeId);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@PostMapping("/savenewentry")
public ResponseEntity<Map<String, Object>> savenewentry(
@RequestParam String pBatchId, @RequestParam String pName,
@RequestParam (name="pAge", required = false) String pAge, @RequestParam String pGender,
@RequestParam String Designation, @RequestParam int DesignationId,
@RequestParam int DeptId, @RequestParam int officeId,
@RequestParam(name="address1", required = false) String address1,
@RequestParam(name="address2", required = false) String address2,
@RequestParam(name="address3", required = false) String address3,
@RequestParam(name="pincode", required = false) Integer pincode,
@RequestParam(name="policest", required = false) String policest,
@RequestParam(name="phoneno", required = false) String phoneno,
@RequestParam(name="mobileno", required = false) String mobileno,
@RequestParam(name="district", required = false) Integer district,
@RequestParam(name="nativeac", required = false) Integer nativeac,
@RequestParam(name="resideac", required = false) Integer resideac,
@RequestParam(name="electoracno", required = false) Integer electoracno,
@RequestParam(name="electorpartno", required = false) Integer partno,
@RequestParam(name="electorslno", required = false) Integer electorslno,
@RequestParam(name="epicno", required = false) String epicno,
@RequestParam String userid
){
//int mcount = 0;
int ecount = 0;
// if (mobileno != null && !mobileno.trim().isEmpty()) {
// mcount = batchAPIService.checkMobile(mobileno);
// }
if (epicno != null && !epicno.trim().isEmpty()) {
ecount = batchAPIService.checkEpicno(epicno);
}
// if (mcount > 0) {
// return ResponseEntity.ok(Map.of(
// "status", false,
// "message", "mobile number already entered",
// "description", "Duplicate entry (Mobile Number already entered)"
// ));
// }
if (ecount > 0) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "epic number already entered",
"description", "Duplicate entry (EPIC Number already entered)"
));
}
String saveStatus= batchAPIService.saveNewEntry(pBatchId,pName,pAge,pGender,Designation,DesignationId,DeptId,officeId,address1,address2,address3,
pincode,policest,phoneno,mobileno,district,nativeac,resideac,electoracno,partno,electorslno,epicno,
userid);
if (saveStatus == null || saveStatus.equals("error")) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Failed to save the details"
));
}
return ResponseEntity.ok(Map.of(
"status", true,
"message", "success",
"description", "Details Saved Successfully" ,
"unique_no", saveStatus
));
}
}

108
src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java

@ -1,108 +0,0 @@
package com.gcc.election.dataentry.controller;
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 com.gcc.election.dataentry.service.BatchAPIService;
import com.gcc.election.service.LoginUserInfo;
@RequestMapping("/election/dataentry")
@Controller("electionDataentryController")
public class Maincontroller {
@Autowired
private BatchAPIService batchService;
@GetMapping("/dashboard")
public String dashboard(Model model) {
return "modules/dataentry/dashboard";
}
@GetMapping("/batches")
public String batches(Model model) {
return "modules/dataentry/batches";
}
@GetMapping("/batchbyid")
public String batchById(@RequestParam String batchid, Model model) {
if (batchid == null || batchid.trim().isEmpty()) {
return "modules/dataentry/batches";
}
Map<String, Object> batchdetails = batchService.getBatchById(batchid);
Object pendingObj = batchdetails.get("pending");
int pending = 0;
if (pendingObj != null) {
try {
pending = Integer.parseInt(pendingObj.toString());
} catch (NumberFormatException e) {
pending = 0;
}
}
if (pending == 0) {
return "modules/dataentry/batches";
}
model.addAttribute("batchdetails", batchdetails);
return "modules/dataentry/batchbyid";
}
@GetMapping("/newentry")
public String newEntry(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId",LoginUserId);
return "modules/dataentry/newentry";
}
@GetMapping("/updation")
public String updation(Model model) {
return "modules/dataentry/updation";
}
@GetMapping("/updateform")
public String updateform(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId",LoginUserId);
return "modules/dataentry/updateform";
}
@GetMapping("/verification")
public String verification(Model model) {
return "modules/dataentry/verification";
}
@GetMapping("/notices")
public String notices(Model model) {
return "modules/dataentry/notices";
}
}

175
src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java

@ -1,175 +0,0 @@
package com.gcc.election.dataentry.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.gcc.election.dataentry.service.BatchAPIService;
import com.gcc.election.dataentry.service.UpdationService;
@RestController
@RequestMapping("/election/api/dataentry/update")
public class UpdationAPIController {
@Autowired
private UpdationService upservice;
@GetMapping("/getbymobanduniq")
public ResponseEntity<?> getbymobanduniq(
@RequestParam(name="mobilenum", required = false) String mobilenum,
@RequestParam(name="uniquenum", required = false) String uniquenum,
@RequestParam(name="batch_num", required = false) String batch_num
)
{
try {
List<Map<String, Object>> list=upservice.getbymobanduniq(mobilenum,uniquenum,batch_num);
Map<String, Object> response = new HashMap<>();
if(list.isEmpty()) {
response.put("status", "no_data");
response.put("data", "No Data Available");
}
else {
response.put("status", "success");
response.put("data", list);
}
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@GetMapping("/getPollingDetailsById")
public ResponseEntity<?> getPollingDetailsById(@RequestParam int id){
try {
List<Map<String, Object>> list = upservice.getPollingDetailsById(id);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", list);
return ResponseEntity.ok(response);
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
@PostMapping("/updateppdetailsbyid")
public ResponseEntity<Map<String, Object>> updateppdetailsbyid(
@RequestParam String pBatchId, @RequestParam String pName,
@RequestParam (name="pAge", required = false) String pAge, @RequestParam String pGender,
@RequestParam String Designation, @RequestParam int DesignationId,
@RequestParam int DeptId, @RequestParam int officeId,
@RequestParam(name="address1", required = false) String address1,
@RequestParam(name="address2", required = false) String address2,
@RequestParam(name="address3", required = false) String address3,
@RequestParam(name="pincode", required = false) Integer pincode,
@RequestParam(name="policest", required = false) String policest,
@RequestParam(name="phoneno", required = false) String phoneno,
@RequestParam(name="mobileno", required = false) String mobileno,
@RequestParam(name="district", required = false) Integer district,
@RequestParam(name="nativeac", required = false) Integer nativeac,
@RequestParam(name="resideac", required = false) Integer resideac,
@RequestParam(name="electoracno", required = false) Integer electoracno,
@RequestParam(name="electorpartno", required = false) Integer partno,
@RequestParam(name="electorslno", required = false) Integer electorslno,
@RequestParam(name="epicno", required = false) String epicno,
@RequestParam String userid,
@RequestParam String nppid,
@RequestParam String slno,
@RequestParam (required = false)MultipartFile pp_image
){
int ecount = 0;
if (epicno != null && !epicno.trim().isEmpty()) {
ecount = upservice.checkEpicno(epicno,nppid);
}
if (ecount > 0) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "epic number already entered",
"description", "Duplicate entry (EPIC Number already entered)"
));
}
System.out.println("pp_image==="+pp_image);
if(pp_image!=null && !pp_image.isEmpty()) {
String filesave=upservice.fileUpload(nppid,pp_image,userid,slno);
if(filesave.equalsIgnoreCase("error")) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Error in Image Processing"
));
}
}
String logEntry=upservice.logentry(nppid);
if(logEntry.equalsIgnoreCase("success")) {
String saveStatus= upservice.updateppdetailsbyid(pBatchId,pName,pAge,pGender,Designation,DesignationId,DeptId,officeId,address1,address2,address3,
pincode,policest,phoneno,mobileno,district,nativeac,resideac,electoracno,partno,electorslno,epicno,
userid,nppid);
if (saveStatus == null || saveStatus.equals("error")) {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Failed to Update the details"
));
}
return ResponseEntity.ok(Map.of(
"status", true,
"message", "success",
"description", "Details Updated Successfully"
));
}
else {
return ResponseEntity.ok(Map.of(
"status", false,
"message", "failed",
"description", "Failed to insert in log details"
));
}
}
}

214
src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java

@ -1,214 +0,0 @@
package com.gcc.election.dataentry.service;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.Query;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
@Service
public class BatchAPIService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getBatchDetails() {
String sql = "select b.id, date_format(b.rec_date, '%d-%m-%Y') as rec_date, dm.dept_name, od.office_name, "
+ " b.noof_application, count(ppn.batch_no) as completed, (b.noof_application - count(ppn.batch_no)) as pending from batch_master b"
+ " left join poll_person_new ppn on b.id = ppn.batch_no"
+ " left join dept_master dm on b.dept_id = dm.dept_id"
+ " left join office_details od on b.office_id = od.id"
+ " where b.is_active = 1"
+ " group by b.id, ppn.batch_no";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public Map<String, Object> getBatchById(String id) {
String sql = "SELECT bm.id, DATE_FORMAT(bm.rec_date, '%Y-%m-%d') AS rec_date, bm.noof_application,DATE_FORMAT(bm.rec_date, '%d-%m-%Y') AS received_date,om.id as office_id,dm.dept_id as dept_id, "
+ "dm.dept_name, "
+ "om.office_name ,count(ppn.batch_no) as completed,(bm.noof_application - count(ppn.batch_no)) as pending "
+ "FROM batch_master bm "
+ "LEFT JOIN dept_master dm ON dm.dept_id = bm.dept_id "
+ "LEFT JOIN office_details om ON om.id = bm.office_id "
+ " LEFT JOIN poll_person_new ppn on bm.id = ppn.batch_no "
+ "WHERE bm.id = ? AND bm.is_active = 1";
try {
return jdbcTemplate.queryForMap(sql, id);
} catch (Exception ex) {
ex.printStackTrace();
return new HashMap<>();
}
}
public List<Map<String, Object>> getAllDesignations() {
String sql="SELECT * FROM designation WHERE is_active=1 AND is_delete=0 ORDER BY new_designation";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public Map<String, Object> getPayDetailsByDesgId(int desgId) {
String sql = "SELECT * FROM designation WHERE desig_id = ? AND is_active = 1";
try {
return jdbcTemplate.queryForMap(sql, desgId);
}
catch (Exception e) {
e.printStackTrace();
return new HashMap<>();
}
}
public List<Map<String, Object>> getAllAcList() {
String sql="SELECT * FROM ac_list_all WHERE is_active=1 ORDER BY ac_name";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public List<Map<String, Object>> getAllDistricts() {
String sql="SELECT * FROM district_master WHERE is_active=1 ORDER BY dist_name";
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public List<Map<String, Object>> getOfficeDetailsById(int officeId) {
String sql = "SELECT od.*,dm.dept_name as office_category,al.ac_name as office_assembly"
+ " FROM office_details od "
+ " LEFT JOIN dept_master dm ON dm.dept_id=od.dept_id "
+ " LEFT JOIN ac_list_all al ON al.ac_no = od.work_ac_no "
+ " WHERE od.id = ? AND od.is_active = 1";
try {
return jdbcTemplate.queryForList(sql,officeId);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public String saveNewEntry(String pBatchId, String pName, String pAge, String pGender, String designation,
int designationId, int deptId, int officeId, String address1, String address2, String address3,
Integer pincode, String policest, String phoneno, String mobileno, Integer district, Integer nativeac,
Integer resideac, Integer electoracno, Integer partno, Integer electorslno, String epicno,String userid) {
String pAgeVal = (pAge != null && !pAge.trim().isEmpty()) ? pAge : null;
String address1Val = (address1 != null && !address1.trim().isEmpty()) ? address1.toUpperCase() : null;
String address2Val = (address2 != null && !address2.trim().isEmpty()) ? address2.toUpperCase() : null;
String address3Val = (address3 != null && !address3.trim().isEmpty()) ? address3.toUpperCase() : null;
String policestVal = (policest != null && !policest.trim().isEmpty()) ? policest.toUpperCase() : null;
String phonenoVal = (phoneno != null && !phoneno.trim().isEmpty()) ? phoneno : null;
String mobilenoVal = (mobileno != null && !mobileno.trim().isEmpty()) ? mobileno : null;
String epicnoVal = (epicno != null && !epicno.trim().isEmpty()) ? epicno.toUpperCase() : null;
String sql = "INSERT INTO poll_person_new ("
+ " dept,name,age,sex,designation_id,office_id,r_address1,r_address2,r_address3,r_pincode,r_phone_no,r_mobile_no,"
+ " r_policest,home_dist,native_ac_no,reside_ac_no,elector_ac_no,elector_part_no,elector_sl_no,elector_epic_no,"
+ " batch_no,created_by "
+ ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int result = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
ps.setInt(1, deptId);
ps.setString(2, pName);
ps.setString(3, pAgeVal);
ps.setString(4, pGender);
ps.setInt(5, designationId);
ps.setInt(6, officeId);
ps.setString(7, address1Val);
ps.setString(8, address2Val);
ps.setString(9, address3Val);
if (pincode != null) ps.setInt(10, pincode);
else ps.setNull(10, java.sql.Types.INTEGER);
ps.setString(11, phonenoVal);
ps.setString(12, mobilenoVal);
ps.setString(13, policestVal);
if (district != null) ps.setInt(14, district);
else ps.setNull(14, java.sql.Types.INTEGER);
if (nativeac != null) ps.setInt(15, nativeac);
else ps.setNull(15, java.sql.Types.INTEGER);
if (resideac != null) ps.setInt(16, resideac);
else ps.setNull(16, java.sql.Types.INTEGER);
if (electoracno != null) ps.setInt(17, electoracno);
else ps.setNull(17, java.sql.Types.INTEGER);
if (partno != null) ps.setInt(18, partno);
else ps.setNull(18, java.sql.Types.INTEGER);
if (electorslno != null) ps.setInt(19, electorslno);
else ps.setNull(19, java.sql.Types.INTEGER);
ps.setString(20,epicnoVal);
ps.setString(21,pBatchId);
ps.setString(22,userid);
return ps;
}, keyHolder);
//return keyHolder.getKey().intValue();
if (result > 0) {
int generatedId = keyHolder.getKey().intValue();
int slnoNumeric = 100000 + generatedId;
String slnoString = String.valueOf(slnoNumeric);
String updateSql = "UPDATE poll_person_new SET slno = ? WHERE id = ?";
jdbcTemplate.update(updateSql, slnoString, generatedId);
return slnoString;
}
//return "error";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
public int checkMobile(String mobileno) {
String sql="SELECT count(*) FROM poll_person_new WHERE r_mobile_no=? AND is_active=1";
return jdbcTemplate.queryForObject(sql, Integer.class, mobileno);
}
public int checkEpicno(String epicno) {
String sql="SELECT count(*) FROM poll_person_new WHERE elector_epic_no=? AND is_active=1";
return jdbcTemplate.queryForObject(sql, Integer.class, epicno);
}
}

302
src/main/java/com/gcc/election/dataentry/service/UpdationService.java

@ -1,302 +0,0 @@
package com.gcc.election.dataentry.service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import com.gcc.election.controller.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class UpdationService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccElectionDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Autowired
private Environment environment;
private String fileBaseUrl;
public UpdationService(Environment environment) {
this.fileBaseUrl = environment.getProperty("fileBaseUrl");
}
public List<Map<String, Object>> getbymobanduniq(String mobilenum, String uniquenum,String batch_num) {
StringBuilder sql = new StringBuilder("SELECT pp.*,CONCAT_WS(',',pp.r_address1,r_address2,r_address3,r_pincode) as res_address,dm.dept_name as dept_name,dg.new_designation as new_designation,od.office_name as office_name,CONCAT_WS(', ', od.address1, od.address2, od.address3, od.pincode) AS office_address,bm.id as batch_id,al.ac_name as res_assembly,al2.ac_name as native_assembly,al3.ac_name as enrolled_assembly,"
+ "dg.pay_scale as pay_scale,dg.grade_pay as grade_pay,dg.basic_pay as basic_pay,od.govt_type as govt_type,od.work_ac_no as work_ac_no,al4.ac_name as work_assembly,pm.image_path as raw_path, "
+ "CONCAT('" + fileBaseUrl + "', pm.image_path) AS img_full_path "
//+ " 'https://gccservices.in/gccofficialapp/files/asset_activity/2/2_after_725115_14112025105400_7760.jpeg' as img_full_path "
+ " FROM poll_person_new pp "
+ "LEFT JOIN dept_master dm ON dm.dept_id=pp.dept "
+ "LEFT JOIN designation dg ON dg.desig_id=pp.designation_id "
+ "LEFT JOIN ac_list_all al ON (al.ac_no = pp.reside_ac_no) "
+ "LEFT JOIN ac_list_all al2 ON (al2.ac_no = pp.native_ac_no) "
+ "LEFT JOIN ac_list_all al3 ON (al3.ac_no = pp.elector_ac_no) "
+ "LEFT JOIN office_details od ON od.id=pp.office_id "
+ "LEFT JOIN ac_list_all al4 ON (al4.ac_no = od.work_ac_no) "
+ "LEFT JOIN batch_master bm ON bm.id=pp.batch_no "
+ "LEFT JOIN poll_person_images pm ON pm.ppn_id=pp.id "
+ "WHERE pp.is_active = 1");
List<Object> params = new ArrayList<>();
// Add conditions dynamically
if (mobilenum != null && !mobilenum.trim().isEmpty()) {
sql.append(" AND pp.r_mobile_no = ?");
params.add(mobilenum);
}
if (uniquenum != null && !uniquenum.trim().isEmpty()) {
sql.append(" AND pp.slno = ?");
params.add(uniquenum);
}
if (batch_num != null && !batch_num.trim().isEmpty()) {
sql.append(" AND pp.batch_no = ?");
params.add(batch_num);
}
// Ensure at least one parameter is provided
if (params.isEmpty()) {
return new ArrayList<>(); // or throw exception
}
//System.out.println("sql==="+sql);
try {
return jdbcTemplate.queryForList(sql.toString(), params.toArray());
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>();
}
}
//
public List<Map<String, Object>> getPollingDetailsById(int id) {
String sql = "SELECT pp.*,pm.image_path as img_raw_path, "
+ "CONCAT('" + fileBaseUrl + "', pm.image_path) AS img_full_path "
//+ " 'https://gccservices.in/gccofficialapp/files/asset_activity/2/2_after_725115_14112025105400_7760.jpeg' as img_full_path "
+ " FROM poll_person_new pp "
+ " LEFT JOIN poll_person_images pm ON pm.ppn_id=pp.id "
+ " WHERE pp.id = ? AND pp.is_active = 1 AND pp.is_delete=0";
try {
return jdbcTemplate.queryForList(sql,id);
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>(); // return empty list on error
}
}
public String logentry(String nppid) {
String sql="INSERT INTO poll_person_new_log"
+ "(slno,dept,name,age,sex,designation_id,category_id,office_id,r_address1,r_address2,r_address3,r_pincode,r_std_code,"
+ "r_phone_no,r_mobile_no,r_policest,home_dist,native_ac_no,reside_ac_no,elector_ac_no,elector_part_no,elector_sl_no,elector_epic_no,"
+ "officiated,officiated_det,evm_experience,disqualified,category,status,allocation,allot_ac,team_code,allot_pc,allot_ps,c_code,record_no,"
+ "rnd_no,emp_no,designation,batch,old_c_code,hall_no,batch_no,taluk,user_sno,entry_batch,cdate,created_by,updated_by,is_active,is_delete) "
+ "SELECT slno,dept,name,age,sex,designation_id,category_id,office_id,r_address1,r_address2,r_address3,r_pincode,r_std_code,"
+ "r_phone_no,r_mobile_no,r_policest,home_dist,native_ac_no,reside_ac_no,elector_ac_no,elector_part_no,elector_sl_no,elector_epic_no,"
+ "officiated,officiated_det,evm_experience,disqualified,category,status,allocation,allot_ac,team_code,allot_pc,allot_ps,c_code,record_no,"
+ "rnd_no,emp_no,designation,batch,old_c_code,hall_no,batch_no,taluk,user_sno,entry_batch,cdate,created_by,updated_by,is_active,is_delete "
+ "FROM poll_person_new WHERE id=? ";
try {
jdbcTemplate.update(sql,nppid);
return "success";
} catch (Exception ex) {
ex.printStackTrace();
return "error";
}
}
public String updateppdetailsbyid(String pBatchId, String pName, String pAge, String pGender,
String designation, int designationId, int deptId, int officeId, String address1, String address2,
String address3, Integer pincode, String policest, String phoneno, String mobileno, Integer district,
Integer nativeac, Integer resideac, Integer electoracno, Integer partno, Integer electorslno,
String epicno, String userid, String nppid) {
String pAgeVal = (pAge != null && !pAge.trim().isEmpty()) ? pAge : null;
String address1Val = (address1 != null && !address1.trim().isEmpty()) ? address1.toUpperCase() : null;
String address2Val = (address2 != null && !address2.trim().isEmpty()) ? address2.toUpperCase() : null;
String address3Val = (address3 != null && !address3.trim().isEmpty()) ? address3.toUpperCase() : null;
String policestVal = (policest != null && !policest.trim().isEmpty()) ? policest.toUpperCase() : null;
String phonenoVal = (phoneno != null && !phoneno.trim().isEmpty()) ? phoneno : null;
String mobilenoVal = (mobileno != null && !mobileno.trim().isEmpty()) ? mobileno : null;
String epicnoVal = (epicno != null && !epicno.trim().isEmpty()) ? epicno.toUpperCase() : null;
String sql="UPDATE poll_person_new SET dept=?,name=?,age=?,sex=?,designation_id=?,office_id=?,r_address1=?,r_address2=?,r_address3=?,r_pincode=?,"
+ "r_phone_no=?,r_mobile_no=?,r_policest=?,home_dist=?,native_ac_no=?,reside_ac_no=?,elector_ac_no=?,elector_part_no=?,elector_sl_no=?,elector_epic_no=?,"
+ "batch_no=?,updated_by=?,updated_date=NOW() "
+ "WHERE id=? AND is_active=1 ";
try {
int update = jdbcTemplate.update(sql,
deptId,
pName,
pAgeVal,
pGender,
designationId,
officeId,
address1Val,
address2Val,
address3Val,
pincode != null ? pincode : null,
phonenoVal,
mobilenoVal,
policestVal,
district != null ? district : null,
nativeac != null ? nativeac : null,
resideac != null ? resideac : null,
electoracno != null ? electoracno : null,
partno != null ? partno : null,
electorslno != null ? electorslno : null,
epicnoVal,
pBatchId,
userid,
nppid
);
if (update > 0) {
return "success";
}
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
public int checkEpicno(String epicno,String nppid) {
String sql="SELECT count(*) FROM poll_person_new WHERE elector_epic_no=? AND id!=? AND is_active=1";
return jdbcTemplate.queryForObject(sql, Integer.class, epicno,nppid);
}
public String fileUpload(String nppid, MultipartFile pp_image, String userid, String slno) {
String sql = "SELECT image_path FROM poll_person_images WHERE ppn_id=? AND is_active=1 AND is_delete=0";
String existingpath = "";
try {
List<String> result = jdbcTemplate.query(
sql,
(rs, rowNum) -> rs.getString("image_path"),
nppid
);
existingpath = result.isEmpty() ? "" : result.get(0);
} catch (Exception e) {
e.printStackTrace();
return "error";
}
try {
String imgPath = saveimage(pp_image, "profile_img");
if ("error".equalsIgnoreCase(imgPath)) return "error";
if (existingpath.isEmpty()) {
String insertSql = "INSERT INTO poll_person_images (ppn_id, slno, image_path, created_by) VALUES (?, ?, ?, ?)";
jdbcTemplate.update(insertSql, nppid, slno, imgPath, userid);
return "success";
} else {
imgLog(nppid);
String updateSql = "UPDATE poll_person_images SET image_path=?, updated_by=?, updated_date=NOW() WHERE ppn_id=? AND is_active=1";
jdbcTemplate.update(updateSql, imgPath, userid, nppid);
return "success";
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
private void imgLog(String nppid) {
String sql="INSERT INTO poll_person_images_log (ppn_id,slno,image_path,is_active,is_delete,created_by,created_date,updated_by) "
+ "SELECT ppn_id,slno,image_path,is_active,is_delete,created_by,created_date,updated_by FROM poll_person_images WHERE ppn_id=? ";
try {
jdbcTemplate.update(sql, nppid);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
private String saveimage(MultipartFile file, String name) {
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("election_profile_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
uploadDirectory = uploadDirectory + serviceFolderName + "/" + year + "/" + month;
try {
// Create directory if it doesn't exist
Path directoryPath = Paths.get(uploadDirectory);
if (!Files.exists(directoryPath)) {
Files.createDirectories(directoryPath);
}
// Datetime string
String datetimetxt = DateTimeUtil.getCurrentDateTime();
// File name
String fileName = name + "_" + datetimetxt + "_" + file.getOriginalFilename();
fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename
String filePath = uploadDirectory + "/" + fileName;
String filepath_txt = "/" + serviceFolderName + "/" + year + "/" + month + "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
Files.write(path, bytes);
System.out.println(filePath);
System.out.println(" filepath_txt=="+ filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}

321
src/main/java/com/gcc/election/interceptor/AppInterceptor.java

@ -1,321 +0,0 @@
package com.gcc.election.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.election.entity.AppModuleEntity;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.election.entity.SubMenuItemEntity;
import com.gcc.election.repository.AppModuleAccessRepository;
import com.gcc.election.repository.AppModuleRepository;
import com.gcc.election.repository.MenuItemAccessRepository;
import com.gcc.election.repository.MenuItemRepository;
import com.gcc.election.repository.SubMenuItemAccessRepository;
import com.gcc.election.repository.SubMenuItemRepository;
import com.gcc.election.service.LoginUserInfo;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AppInterceptor implements HandlerInterceptor{
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<MenuItemAccessEntity> getMenuItemAccessEntities;
List<SubMenuItemAccessEntity> getSubMenuItemAccessEntities;
private AppModuleAccessRepository appModuleAccessRepository;
private MenuItemAccessRepository menuItemAccessRepository;
private SubMenuItemAccessRepository subMenuItemAccessRepository;
List<AppModuleEntity> getAppModuleEntities;
List<MenuItemEntity> getMenuItemEntities;
List<SubMenuItemEntity> getSubMenuItemEntities;
private AppModuleRepository appModuleRepository;
private MenuItemRepository menuItemRepository;
private SubMenuItemRepository subMenuItemRepository;
private final Environment environment;
@Autowired
public AppInterceptor(AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
Environment environment) {
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.environment = environment;
}
private boolean isLoginPage(HttpServletRequest request) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/election/login");
return loginPageMatcher.matches(request);
}
private boolean isErrorPage(HttpServletRequest request) {
RequestMatcher errorPageMatcher = new AntPathRequestMatcher("/election/error");
return errorPageMatcher.matches(request);
}
private boolean isfavicon(HttpServletRequest request) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/favicon.ico");
return loginPageMatcher.matches(request);
}
public static String[] Split(String request,String patten) {
String path = request;
// Split the string by "/"
String[] parts = path.split(patten);
/*
// Display the parts
for (String part : parts) {
System.out.println(part);
}
*/
return parts;
}
private boolean hasModuleAccess(String moduleName) {
getAppModuleEntities = appModuleRepository.findByModulePath(moduleName);
//System.out.println("DataTable Size for the url ("+moduleName+"): "+getAppModuleEntities.size());
String moduleid = null;
if(getAppModuleEntities.size()>0) {
for ( AppModuleEntity appModuleEntity : getAppModuleEntities) {
moduleid = appModuleEntity.getId().toString();
}
if(moduleid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasModuleAccess : Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid);
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(userGroupId,moduleid);
//System.out.println("After Check in(hasModuleAccess):"+getAppModuleAccessEntities.size());
if(getAppModuleAccessEntities.size()>0) {
return true;
}
else {
System.out.println("hasModuleAccess : getAppModuleAccessEntities.size = " + getAppModuleAccessEntities.size());
}
}
}
return false;
}
private boolean hasMenuAccess(String url,String moduleName,String menuName) {
if(!hasModuleAccess(moduleName)) {return false; }
getMenuItemEntities = menuItemRepository.findByUrl(url);
//System.out.println("DataTable Size for the url ("+url+"): "+getMenuItemEntities.size());
String moduleid = null;
String menuid = null;
if(getMenuItemEntities.size()>0) {
for (MenuItemEntity MenuEntity : getMenuItemEntities) {
moduleid = MenuEntity.getModuleId().getId().toString();
menuid = MenuEntity.getId().toString();
}
if(moduleid != null && menuid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasMenuAccess : Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid);
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId,moduleid,menuid);
if(getMenuItemAccessEntities.size()>0) {
return true;
}
}
}
return false;
}
private boolean hasSubMenuAccess(String url,String moduleName,String menuName,String subMenuName) {
if(!hasModuleAccess(moduleName)) {return false; }
getSubMenuItemEntities = subMenuItemRepository.findByUrl(url);
//System.out.println("DataTable Size for the url ("+url+"): "+getSubMenuItemEntities.size());
String moduleid = null;
String menuid = null;
String submenuid = null;
if(getSubMenuItemEntities.size()>0) {
for (SubMenuItemEntity subMenuEntity : getSubMenuItemEntities) {
moduleid = subMenuEntity.getModuleId().getId().toString();
menuid = subMenuEntity.getMenuItemId().getId().toString();
submenuid = subMenuEntity.getId().toString();
}
if(moduleid != null && menuid != null && submenuid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasSubMenuAccess 1: Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid+"\n submenuid : "+submenuid);
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(userGroupId,moduleid,menuid,submenuid);
if(getSubMenuItemAccessEntities.size()>0) {
// Check Parent Menu Access (Menu Access)
if(moduleid != null && menuid != null) {
System.out.println("hasSubMenuAccess 2: Query input`s :\n userGroupId : "+userGroupId+"\n moduleid : "+moduleid+"\n menuid : "+menuid);
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId,moduleid,menuid);
if(getMenuItemAccessEntities.size()>0) {
return true;
}
}
}
}
}
return false;
}
private boolean hasAccess(String path) {
String userRole = LoginUserInfo.getUserRole();
if (userRole != null && userRole.equals("ADMIN")) {
return true;
}
/*
if(LoginUserInfo.getUserRole().equals("ADMIN")) {
return true;
}
*/
String url = removeLeadingSlash(path);
url = removeStartingString(url); // Remove parent App url "gcc"
//System.out.println("Give URL : "+path+" After remove leading slash : "+url);
// If default home page
if(path.equals("/")) {
return true;
}
//continue for access check
String[] parts = Split(url, "/");
if(parts.length<=0) {return true;}
//System.out.println("Part Length:"+ parts.length);
if(parts.length>1) {
int j=0;
for (String part : parts) {
System.out.println(j+") URL SPLIT: "+part);
j++;
}
String moduleName = "";
String menuName = "";
String subMenuName = "";
if(parts.length==1) { // Check Only Module Access
moduleName = parts[0];
return hasModuleAccess(moduleName);
}
else if(parts.length==2) { // Check Module & Menu Access
moduleName = parts[0];
menuName = parts[1];
subMenuName = "";
return hasMenuAccess(url,moduleName,menuName);
}
else if(parts.length==3) { // Check Module , Menu & Sub-Menu Access
moduleName = parts[0];
menuName = parts[1];
subMenuName = parts[2];
return hasSubMenuAccess(url,moduleName,menuName,subMenuName);
}
}
return true;
}
public static String removeLeadingSlash(String input) {
if (input.startsWith("/")) {
return input.substring(1);
}
return input;
}
public static String removeStartingString(String input) {
if (input.startsWith("election")) {
return removeLeadingSlash(input.substring(8));
}
return input;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String assetsBaseUrl = environment.getProperty("assets.base-url");
request.setAttribute("assetsBaseUrl", assetsBaseUrl);
if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
String fullRequestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String path = fullRequestURI.substring(contextPath.length());
if(!hasAccess(path)) {
//Object principal = authentication.getPrincipal();
//UserDetails userDetails = (UserDetails) principal;
//System.out.println("1) Access Deny For --- " + userDetails.getAuthorities().toString());
// Redirect to the error page
//response.sendRedirect(request.getContextPath() + "/error");
request.getRequestDispatcher("/error").forward(request, response);
// response.sendRedirect(request.getContextPath() + "/election/error");
// return false;
}
}
}
// Continue with the request processing
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// Check if the current request matches the login or error page URLs
if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) {
if (modelAndView != null) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
request.setAttribute("assetsBaseUrl", assetsBaseUrl);
modelAndView.addObject("assetsBaseUrl", assetsBaseUrl);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
modelAndView.addObject("currentUserDetails", userDetails);
System.out.println(userDetails);
}
}
}
}
}
}

30
src/main/java/com/gcc/election/repository/AppModuleRepository.java

@ -1,30 +0,0 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppModuleEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface AppModuleRepository extends JpaRepository<AppModuleEntity,Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `modules` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`", nativeQuery = true)
List<AppModuleEntity> showAll();
@Query(value = "SELECT * FROM `modules` WHERE `id` IN (:checkModuleid) AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id`", nativeQuery = true)
List<AppModuleEntity> showAllById(String[] checkModuleid);
@Query(value = "SELECT * FROM `modules` WHERE (`module_path` = :module_path) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<AppModuleEntity> findByModulePath(String module_path);
}

34
src/main/java/com/gcc/election/repository/SubMenuItemRepository.java

@ -1,34 +0,0 @@
package com.gcc.election.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.election.entity.SubMenuItemEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface SubMenuItemRepository extends JpaRepository<SubMenuItemEntity, Integer>{
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByModuleId(@Param("module_id") int module_id);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `menuitem_id`=:menuitem_id ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByMenuItemId(@Param("menuitem_id") int menuitem_id);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`menuitem_id`=:menuitem_id AND `id` IN (:checkSubMenuid)) ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByMenuItemIdAccess(@Param("menuitem_id") int menuitem_id,String[] checkSubMenuid);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`url`=:url) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<SubMenuItemEntity> findByUrl(@Param("url") String url);
}

37
src/main/java/com/gcc/election/service/Base64Util.java

@ -1,37 +0,0 @@
package com.gcc.election.service;
import java.util.Base64;
import org.springframework.stereotype.Service;
@Service
public class Base64Util {
// Encode to Base64
public static String encodeBase64(String value) {
if (value != null && !value.isEmpty()) {
byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes());
// Print the original value and its encoded version
// System.out.println(value + " : " + new String(encodedBytes));
return new String(encodedBytes);
} else {
return "";
}
}
// Decode from Base64
public static String decodeBase64(String encodedValue) {
if (encodedValue != null && !encodedValue.isEmpty()) {
try {
byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
return new String(decodedBytes);
} catch (IllegalArgumentException e) {
// Handle the exception, e.g., log it or return an error message
System.err.println("Error decoding Base64 string: " + e.getMessage());
return "error"; // Or return an error message string
}
} else {
return "";
}
}
}

6
src/main/java/com/gcc/election/ElectionApplication.java → src/main/java/com/gcc/swm_services/SwmApplication.java

@ -1,13 +1,13 @@
package com.gcc.election;
package com.gcc.swm_services;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class ElectionApplication {
public class SwmApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ElectionApplication.class, args);
SpringApplication.run(SwmApplication.class, args);
} }
} }

7
src/main/java/com/gcc/election/configuration/AppConfig.java → src/main/java/com/gcc/swm_services/configuration/AppConfig.java

@ -1,4 +1,4 @@
package com.gcc.election.configuration;
package com.gcc.swm_services.configuration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -7,10 +7,9 @@ import org.springframework.web.client.RestTemplate;
@Configuration @Configuration
public class AppConfig { public class AppConfig {
@Bean
@Bean
public RestTemplate restTemplate() { public RestTemplate restTemplate() {
return new RestTemplate(); return new RestTemplate();
} }
} }

90
src/main/java/com/gcc/swm_services/configuration/DataSourceConfig.java

@ -0,0 +1,90 @@
package com.gcc.swm_services.configuration;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
// private static String host = "localhost:3306";
// private static String dbpassword = "root";
// 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";
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "appEntityManagerFactory", transactionManagerRef = "appTransactionManager", basePackages = {
"com.gcc.swm_services.repository" })
public static class MysqlAppDataSourceConfig {
@Primary
@Bean(name = "mysqlAppDataSource")
public DataSource mysqlAppDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_swm_services_apps");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
/*
* @Bean(name = "mysqlAppJdbcTemplate")
* public JdbcTemplate mysqlAppJdbcTemplate(@Qualifier("mysqlAppDataSource")
* DataSource dataSource) {
* return new JdbcTemplate(dataSource);
* }
*/
@Primary
@Bean(name = "appEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier("mysqlAppDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("com.gcc.swm_services.entity");
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
@Primary
@Bean(name = "appTransactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("appEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
//////////////////////////// (For GCC Election) ////////////////////////
@Bean(name = "mysqlSwmDataSource")
public DataSource mysqlSwmDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_swm_facilities");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
}

9
src/main/java/com/gcc/election/configuration/JacksonConfiguration.java → src/main/java/com/gcc/swm_services/configuration/JacksonConfiguration.java

@ -1,5 +1,4 @@
package com.gcc.election.configuration;
package com.gcc.swm_services.configuration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -7,14 +6,14 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@Configuration @Configuration
public class JacksonConfiguration { public class JacksonConfiguration {
@Bean
@Bean
public ObjectMapper objectMapper() { public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during serialization
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during
// serialization
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Serialize dates as Strings objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Serialize dates as Strings
objectMapper.registerModule(new JavaTimeModule()); // Register JavaTimeModule for Java 8 Date/Time support objectMapper.registerModule(new JavaTimeModule()); // Register JavaTimeModule for Java 8 Date/Time support
return objectMapper; return objectMapper;

93
src/main/java/com/gcc/swm_services/configuration/SecurityConfig.java

@ -0,0 +1,93 @@
package com.gcc.swm_services.configuration;
import javax.persistence.Basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.gcc.swm_services.service.CustomUserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomUserDetailsService customUserDetailsService;
@Autowired
public SecurityConfig(CustomUserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/static/**", "/assets/**", "/api/**", "/images/**", "/swm/static/**",
"/swm/assets/**", "/swm/api/**", "/swm/images/**", "/swm/files/**", "/.well-known/**",
"/favicon.ico",
"/static/**",
"/css/**",
"/js/**");
// .antMatchers("/election/static/**", "/election/assets/**",
// "/election/api/**","/election/images/**");
// .antMatchers("/assets/**", "/css/**", "/js/**", "/images/**", "/fonts/**");
// // Add the paths to your static resources here
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
// Configure authorization (URL-based access control)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and() // Enable CORS
.csrf().disable() // Disable CSRF protection for simplicity (Enable if needed)
.authorizeRequests()
.antMatchers("/swm/error").permitAll()
.antMatchers("/swm/login").permitAll() // Add the login URL
.antMatchers("/swm/admin/**").hasRole("ADMIN") // Add the admin URLs
.antMatchers("/swm/**").hasAnyRole("ADMIN", "USER") // Add other URLs
// .anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/swm/login") // Customize the login page URL
.defaultSuccessUrl("/swm") // Include the success URL
.permitAll()
.and()
.logout()
.logoutUrl("/swm/logout") // Include the logout URL
.logoutSuccessUrl("/swm/login") // Include the success logout URL
.permitAll()
.and()
.sessionManagement()
.sessionFixation()
.migrateSession(); // or .none(), .newSession()
/*
* // Print role values
* http.authorizeRequests().anyRequest().authenticated().and().formLogin().
* successHandler((request, response, authentication) -> {
* System.out.println("User Roles: ");
* authentication.getAuthorities().forEach(authority ->
* System.out.println(authority.getAuthority()));
* System.out.println();
* response.sendRedirect("/election");
* });
*/
}
@Basic
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

33
src/main/java/com/gcc/swm_services/configuration/ThymeleafConfig.java

@ -0,0 +1,33 @@
package com.gcc.swm_services.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
// @Configuration
// public class ThymeleafConfig {
//
// @Bean
// public ITemplateResolver templateResolver() {
// SpringResourceTemplateResolver templateResolver = new
// SpringResourceTemplateResolver();
// templateResolver.setPrefix("classpath:/templates/"); // Set your Thymeleaf
// templates prefix here
// templateResolver.setSuffix(".html");
// templateResolver.setTemplateMode(TemplateMode.HTML);
// templateResolver.setCacheable(false); // Disable template caching for
// development environment
// return templateResolver;
// }
//
// @Bean
// public SpringTemplateEngine templateEngine() {
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setTemplateResolver(templateResolver());
// return templateEngine;
// }
//
// }

71
src/main/java/com/gcc/swm_services/configuration/WebMvcConfig.java

@ -0,0 +1,71 @@
package com.gcc.swm_services.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.gcc.swm_services.repository.AppModuleAccessRepository;
import com.gcc.swm_services.repository.AppModuleRepository;
import com.gcc.swm_services.repository.MenuItemAccessRepository;
import com.gcc.swm_services.repository.MenuItemRepository;
import com.gcc.swm_services.repository.SubMenuItemAccessRepository;
import com.gcc.swm_services.repository.SubMenuItemRepository;
import com.gcc.swm_services.interceptor.AppInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final String uploadDirectory;
private AppModuleAccessRepository appModuleAccessRepository;
private MenuItemAccessRepository menuItemAccessRepository;
private SubMenuItemAccessRepository subMenuItemAccessRepository;
private AppModuleRepository appModuleRepository;
private MenuItemRepository menuItemRepository;
private SubMenuItemRepository subMenuItemRepository;
private final Environment environment;
@Autowired
public WebMvcConfig(
@Value("${file.upload.directory}") String uploadDirectory,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
Environment environment) {
this.uploadDirectory = uploadDirectory;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.environment = environment;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppInterceptor(
appModuleAccessRepository,
menuItemAccessRepository,
subMenuItemAccessRepository,
appModuleRepository,
menuItemRepository,
subMenuItemRepository,
environment));
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadDirectory + "/");
}
}

491
src/main/java/com/gcc/swm_services/controller/APIController.java

@ -0,0 +1,491 @@
package com.gcc.swm_services.controller;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.swm_services.entity.AppModuleAccessEntity;
import com.gcc.swm_services.entity.AppModuleEntity;
import com.gcc.swm_services.entity.AppUserEntity;
import com.gcc.swm_services.entity.MenuItemAccessEntity;
import com.gcc.swm_services.entity.MenuItemEntity;
import com.gcc.swm_services.entity.SubMenuItemAccessEntity;
import com.gcc.swm_services.entity.SubMenuItemEntity;
import com.gcc.swm_services.entity.UserActivityLog;
import com.gcc.swm_services.repository.AppModuleAccessRepository;
import com.gcc.swm_services.repository.AppModuleRepository;
import com.gcc.swm_services.repository.AppUserRepository;
import com.gcc.swm_services.repository.MenuItemAccessRepository;
import com.gcc.swm_services.repository.MenuItemRepository;
import com.gcc.swm_services.repository.SubMenuItemAccessRepository;
import com.gcc.swm_services.repository.SubMenuItemRepository;
import com.gcc.swm_services.repository.UserActivityLogRepository;
import com.gcc.swm_services.service.LoginUserInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@RequestMapping("/swm/api")
@RestController
public class APIController {
List<AppUserEntity> getAppUserEntities;
@Autowired
private HttpServletRequest request;
@Autowired
private AppUserRepository appUserRepository;
@Autowired
private LoginUserInfo loginUserInfo;
List<UserActivityLog> getActivityLogs;
@Autowired
private UserActivityLogRepository userActivityLogRepository;
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<MenuItemAccessEntity> getMenuItemAccessEntities;
List<SubMenuItemAccessEntity> getSubMenuItemAccessEntities;
@Autowired
private AppModuleAccessRepository appModuleAccessRepository;
@Autowired
private MenuItemAccessRepository menuItemAccessRepository;
@Autowired
private SubMenuItemAccessRepository subMenuItemAccessRepository;
List<AppModuleEntity> getAppModuleEntities;
List<MenuItemEntity> getMenuItemEntities;
List<SubMenuItemEntity> getSubMenuItemEntities;
@Autowired
private AppModuleRepository appModuleRepository;
@Autowired
private MenuItemRepository menuItemRepository;
@Autowired
private SubMenuItemRepository subMenuItemRepository;
@Autowired
public APIController(
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
UserActivityLogRepository userActivityLogRepository) {
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.userActivityLogRepository = userActivityLogRepository;
}
// Encode to Base64
@GetMapping(value = "/encodeBase64")
public static String encodeBase64(@RequestParam String string) {
String value = string;
byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes());
return new String(encodedBytes);
}
// Decode from Base64
@GetMapping(value = "/decodeBase64")
public static String decodeBase64(@RequestParam String string) {
String encodedValue = string;
byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
return new String(decodedBytes);
}
@GetMapping(value = "/getAccessTree")
public String getAccessTreeHTML(@RequestParam String groupId, @RequestParam String groupName) {
getAppModuleEntities = appModuleRepository.showAll();
String accessHTML = "";
String accessTableHTML = "";
// String MenuHTML = "";
String isSelected = "";
// String subMenuHTML = "";
String groupNameHTML = "<span class=\"badge badge-pill badge-primary mb-1\">" + groupName + "</span>";
for (AppModuleEntity moduleName : getAppModuleEntities) {
// ID to check
Integer desiredId = moduleName.getId();
// Check if the ID exists in the list of entities
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, desiredId.toString());
// Check Module Id Access
if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) {
isSelected = "checked";
} else {
isSelected = "";
}
accessHTML = accessHTML + "<li><input id=\"m" + moduleName.getId()
+ "\" type=\"checkbox\" data-type=\"parent\" value=\"m_" + desiredId + "\" " + isSelected
+ "/>&nbsp;<label for=\"m" + moduleName.getId()
+ "\" style=\"background-color:#000;color:#fff;\">&nbsp;&nbsp;<i class=\"" + moduleName.getIcon()
+ "\"></i> " + moduleName.getName() + "&nbsp;&nbsp;</label>";
getMenuItemEntities = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItemEntities) {
String mmid = desiredId + "_" + menuItem.getId();
// Check if the ID exists in the list of entities
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, desiredId.toString(),
menuItem.getId().toString());
// Check Module Id Access
if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) {
isSelected = "checked";
} else {
isSelected = "";
}
if (menuItem.getHasSub()) {
getSubMenuItemEntities = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getSubMenuItemEntities) {
String isSelected2 = "";
String smid = desiredId + "_" + menuItem.getId() + "_" + subMenuItem.getId();
// Check if the ID exists in the list of entities
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId,
desiredId.toString(), menuItem.getId().toString(), subMenuItem.getId().toString());
// Check Module Id Access
if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) {
isSelected2 = "checked";
} else {
isSelected2 = "";
}
subSubMenuHTML = subSubMenuHTML + "<li><input id=\"sm" + subMenuItem.getId()
+ "\" type=\"checkbox\" data-type=\"sub-child\" value=\"sm_" + smid + "\" "
+ isSelected2 + "/>&nbsp;<label for=\"sm" + subMenuItem.getId() + "\"><i class=\""
+ subMenuItem.getIcon() + "\"></i> " + subMenuItem.getName() + "</label></li>";
}
if (subSubMenuHTML.equals("")) {
subMenuHTML = subMenuHTML + "<li><input id=\"mm" + menuItem.getId()
+ "\" type=\"checkbox\" data-type=\"child\" value=\"mm_" + mmid + "\" " + isSelected
+ "/>&nbsp;<label for=\"mm" + menuItem.getId() + "\"><i class=\"" + menuItem.getIcon()
+ "\"></i> " + menuItem.getName() + "</label></li>";
} else {
subMenuHTML = subMenuHTML + "<li><input id=\"mm" + menuItem.getId()
+ "\" type=\"checkbox\" data-type=\"child\" value=\"mm_" + mmid + "\" " + isSelected
+ "/>&nbsp;<label for=\"mm" + menuItem.getId() + "\">&nbsp;<i class=\""
+ menuItem.getIcon() + "\"></i> " + menuItem.getName() + "</label> <ul>"
+ subSubMenuHTML + "</ul></li>";
}
} else {
subMenuHTML = subMenuHTML + "<li><input id=\"mm" + menuItem.getId()
+ "\" type=\"checkbox\" data-type=\"child\" value=\"mm_" + mmid + "\" " + isSelected
+ "/>&nbsp;<label for=\"mm" + menuItem.getId() + "\"><i class=\"" + menuItem.getIcon()
+ "\"></i> " + menuItem.getName() + "</label></li>";
}
}
accessHTML = accessHTML + "<ul>" + subMenuHTML + "</ul></li>";
subMenuHTML = "";
}
accessTableHTML = groupNameHTML + "<ul id=\"tree\" class=\"checktree\" style=\"padding-left:25px;\" >"
+ accessHTML + "</ul>";
return accessTableHTML;
}
@PostMapping("/saveGroupAccessData")
public String saveGroupAccessData(@RequestBody Map<String, Object> requestBody) {
@SuppressWarnings("unchecked")
List<String> checkedData = (List<String>) requestBody.get("checkedData");
String groupId = (String) requestBody.get("groupId");
String dataType[] = { "", "", "module", "menu", "submenu" };
if (groupId != null) {
System.out.println("groupid value: " + groupId);
// Set isActive = false based on groupId
appModuleAccessRepository.updateActiveStatus(false, groupId);
menuItemAccessRepository.updateActiveStatus(false, groupId);
subMenuItemAccessRepository.updateActiveStatus(false, groupId);
// Now update as per input data
if (checkedData != null) {
for (String data : checkedData) {
System.out.println(data);
// m_x -> Module Value (moduleId) -> 2
// mm_x_x -> Menu Value (moduleId,menuId) ->3
// sm_x_x_x -> SubMenu Value (moduleId, menuId, submenuId) ->4
String[] dataValue = data.split("_");
Integer dataLength = dataValue.length;
System.out.println(dataLength + " ==> " + dataType[dataLength]);
if (dataValue.length == 2) { // Module
// Check if the ID exists in the list of entities
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, dataValue[1]);
if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) {
appModuleAccessRepository.update(true, groupId, dataValue[1]);
} else {
appModuleAccessRepository.insert(groupId, dataValue[1]);
}
} else if (dataValue.length == 3) { // Menu
// Check if the ID exists in the list of entities
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, dataValue[1],
dataValue[2]);
if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) {
menuItemAccessRepository.update(true, groupId, dataValue[1], dataValue[2]);
} else {
menuItemAccessRepository.insert(groupId, dataValue[1], dataValue[2]);
}
} else if (dataValue.length == 4) { // SubMenu
// Check if the ID exists in the list of entities
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, dataValue[1],
dataValue[2], dataValue[3]);
if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) {
subMenuItemAccessRepository.update(true, groupId, dataValue[1], dataValue[2], dataValue[3]);
} else {
subMenuItemAccessRepository.insert(groupId, dataValue[1], dataValue[2], dataValue[3]);
}
}
}
}
}
return "";
}
@GetMapping(value = "/getUserProfileBasic")
public String getUserProfileBasic(@RequestParam String userId) {
// String userHtml ="";
String userProfileHtml = "";
// String userProfileTimelineHtml ="";
getAppUserEntities = appUserRepository.showById(userId);
for (AppUserEntity appUserEntity : getAppUserEntities) {
userProfileHtml = ""
+ " "
+ " <div class='card mb-1'>"
+ " <div class='card-body'>"
+ " <div class='text-center'>"
+ " <img src='/assets/images/users/user.jpg' class='rounded' width='150'>\n"
+ " <h4 class='card-title mt-10'>" + appUserEntity.getUserid().getName()
+ "</h4>\n"
+ " <p class='text-muted'>Front End Developer</p>\n"
+ " </div>\n"
+ " </div>"
+ " <hr class='mb-0 mt-0'> \n"
+ " <div class='card-body'> \n"
+ " <small class='text-muted d-block'>Email address </small>\n"
+ " <h8>" + appUserEntity.getUserid().getEmail() + "</h8> \n"
+ " <small class='text-muted d-block pt-10'>Phone</small>\n"
+ " <h8>" + appUserEntity.getUserid().getPhone() + "</h8> \n"
+ " <small class='text-muted d-block pt-10'>Role</small>\n"
+ " <h8>" + appUserEntity.getRoles() + "</h8>\n"
+ " <small class='text-muted d-block pt-10'>Access Group</small>\n"
+ " <h8>" + appUserEntity.getUsergroup_id().getName() + "</h8>\n"
+ " </div>\n"
+ " </div>\n"
+ " ";
}
return userProfileHtml;
}
@GetMapping(value = "/getUserProfile")
public String getUserProfile(@RequestParam String userId) {
String userHtml = "";
String userProfileHtml = "";
String userProfileTimelineHtml = "";
String userIp = getUserIP();
getAppUserEntities = appUserRepository.showById(userId);
for (AppUserEntity appUserEntity : getAppUserEntities) {
userProfileHtml = ""
+ " <div class='col-lg-4 col-md-5'>"
+ " <div class='card mb-1'>"
+ " <div class='card-body'>"
+ " <div class='text-center'>"
+ " <img src='/assets/images/users/user.jpg' class='rounded' width='150'>\n"
+ " <h4 class='card-title mt-10'>" + appUserEntity.getUserid().getName()
+ "</h4>\n"
+ " <p class='text-muted'>Front End Developer</p>\n"
+ " <p class='text-muted'>" + userIp + "</p>\n"
+ " </div>\n"
+ " </div>"
+ " <hr class='mb-0 mt-0'> \n"
+ " <div class='card-body'> \n"
+ " <small class='text-muted d-block'>Email address </small>\n"
+ " <h8>" + appUserEntity.getUserid().getEmail() + "</h8> \n"
+ " <small class='text-muted d-block pt-10'>Phone</small>\n"
+ " <h8>" + appUserEntity.getUserid().getPhone() + "</h8> \n"
+ " <small class='text-muted d-block pt-10'>Role</small>\n"
+ " <h8>" + appUserEntity.getRoles() + "</h8>\n"
+ " <small class='text-muted d-block pt-10'>Access Group</small>\n"
+ " <h8>" + appUserEntity.getUsergroup_id().getName() + "</h8>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>";
userProfileTimelineHtml = ""
+ "<div class='col-lg-8 col-md-7'>"
+ " <div class='card'>"
+ " <ul class='nav nav-pills custom-pills' id='pills-tab' role='tablist'>"
+ " <li class='nav-item'>"
+ " <a class='nav-link active' id='pills-timeline-tab' data-toggle='pill' href='#current-month' role='tab' aria-controls='pills-timeline' aria-selected='true'>Timeline</a>"
+ " </li>"
+ " <li class='nav-item'>"
+ " <a class='nav-link' id='pills-profile-tab' data-toggle='pill' href='#last-month' role='tab' aria-controls='pills-profile' aria-selected='false'>Profile</a>"
+ " </li>"
+ " </ul>"
+ " <div class='tab-content' id='pills-tabContent'>"
+ " <div class='tab-pane fade active show' id='current-month' role='tabpanel' aria-labelledby='pills-timeline-tab'>"
+ userTimeLine(appUserEntity.getUserid().getUserid().toString(),
appUserEntity.getUserid().getName(), "user.jpg")
+ " </div>"
+ " </div>"
+ " </div>"
+ "</div>";
userHtml = "<div class='row'>" + userProfileHtml + userProfileTimelineHtml + "</div>";
}
return userHtml;
}
public String userTimeLine(String userid, String userName, String img) {
String userTimeLineHTML = "";
getActivityLogs = userActivityLogRepository.findByUserIdOrderByTimestampDesc(userid);
for (UserActivityLog userActivityLog : getActivityLogs) {
userTimeLineHTML += ""
+ " <div class='sl-item'>"
+ " <div class='sl-left'> "
+ " <img src='/assets/images/users/" + img + "' alt='user' class='rounded-circle'> "
+ " </div>"
+ " <div class='sl-right'>"
+ " <div>"
+ " <a href='javascript:void(0)' class='link'>" + userName + "</a> "
+ " <span class='sl-date'>" + dateFormat(userActivityLog.getTimestamp().toString())
+ "</span>"
+ " <blockquote class='mt-10'>"
+ " " + userActivityLog.getActivityType()
+ " </blockquote>"
+ " </div>"
+ " </div>"
+ " </div><hr>";
}
userTimeLineHTML = ""
+ "<div class='card-body'>"
+ " <div class='profiletimeline mt-0'>"
+ userTimeLineHTML
+ " </div>"
+ "</div>";
return userTimeLineHTML;
}
public String dateFormat(String timestampString) {
// String timestampString = "2023-12-28T16:21:24";
LocalDateTime timestamp = LocalDateTime.parse(timestampString, DateTimeFormatter.ISO_DATE_TIME);
// Define the desired date-time format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
// Format the timestamp
String formattedTimestamp = timestamp.format(formatter);
// System.out.println(formattedTimestamp);
return formattedTimestamp.toUpperCase();
}
public String getUserIP() {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
@GetMapping(value = "/passwordGenerator")
public String passwordGenerator(@RequestParam(value = "password", required = false) String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String rawPassword = password;
String encodedPassword = passwordEncoder.encode(rawPassword);
return encodedPassword;
}
@PostMapping(value = "/resetPassword")
public String resetPassword(
@RequestParam(value = "", required = false) String userid,
@RequestParam(value = "", required = false) String oldpassword,
@RequestParam(value = "", required = false) String newpassword) {
System.out.println(userid + " : " + oldpassword + " : " + newpassword);
String oldPasswordTxt = oldpassword; // passwordGenerator(oldpassword);
String newPasswordTxt = newpassword; // passwordGenerator(newpassword);
String rawPasswordTxt = newpassword;
System.out.println(oldPasswordTxt + " : " + newPasswordTxt + " : " + rawPasswordTxt);
String response = loginUserInfo.resetPassword(userid, oldPasswordTxt, newPasswordTxt, rawPasswordTxt);
return response;
}
@PostMapping(value = "/userCheck")
public List<Map<String, Object>> userCheck(
@RequestParam(value = "", required = false) String usernametxt,
@RequestParam(value = "", required = false) String passwordtxt) {
System.out.println("HRM Service : " + usernametxt + " : " + passwordtxt);
List<Map<String, Object>> response = loginUserInfo.userCheck(usernametxt, passwordtxt);
return response;
}
// @GetMapping(value="/getDailyKural")
// public List getDailyKural() {
// return loginUserInfo.getDailyContent();
// }
}

157
src/main/java/com/gcc/swm_services/controller/AdminController.java

@ -0,0 +1,157 @@
package com.gcc.swm_services.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gcc.swm_services.entity.AppModuleEntity;
import com.gcc.swm_services.entity.AppUserEntity;
import com.gcc.swm_services.entity.AppUserGroupEntity;
import com.gcc.swm_services.entity.MenuItemEntity;
import com.gcc.swm_services.entity.SubMenuItemEntity;
import com.gcc.swm_services.repository.AppModuleRepository;
import com.gcc.swm_services.repository.AppUserGroupRepository;
import com.gcc.swm_services.repository.AppUserRepository;
import com.gcc.swm_services.repository.MenuItemRepository;
import com.gcc.swm_services.repository.SubMenuItemRepository;
import com.gcc.swm_services.service.LoginUserInfo;
@RequestMapping("/swm/admin")
@Controller("swmAdminController")
public class AdminController {
private final AppUserRepository appUserRepository;
private final AppUserGroupRepository appUserGroupRepository;
private final AppModuleRepository appModuleRepository;
private final MenuItemRepository menuItemRepository;
private final SubMenuItemRepository subMenuItemRepository;
@Autowired
public AdminController(
AppUserRepository appUserRepository,
AppUserGroupRepository appUserGroupRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository) {
this.appUserRepository = appUserRepository;
this.appUserGroupRepository = appUserGroupRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
}
@GetMapping({ "", "/", "/index" })
public String main(Model model) {
String userId = LoginUserInfo.getLoginUserId();
if (userId != null && !userId.isEmpty()) {
System.out.println("String UserID: " + userId);
}
return "modules/admin/index";
}
@GetMapping("/user-list")
public String userList(Model model) {
model.addAttribute("userlist", getUser());
return "modules/admin/user-list";
}
@GetMapping("/user-group-list")
public String userGroupList(Model model) {
model.addAttribute("userGroupList", getUserGroup());
return "modules/admin/user-group-list";
}
@GetMapping("/user-group-access")
public String userGroupAccess(Model model) {
String accessTableHTML = getAccessTreeHTML();
model.addAttribute("userGroupList", getUserGroup());
model.addAttribute("accessHTML", accessTableHTML);
return "modules/admin/user-group-access";
}
//////////////////////////////////////// (Functions)
//////////////////////////////////////// ////////////////////////////////////////
public List<AppUserEntity> getUser() {
List<AppUserEntity> appUserEntities;
appUserEntities = appUserRepository.showAll();
return appUserEntities;
}
public List<AppUserGroupEntity> getUserGroup() {
List<AppUserGroupEntity> appUserGroupEntities;
appUserGroupEntities = appUserGroupRepository.findAll();
return appUserGroupEntities;
}
public String getAccessTreeHTML() {
// List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
getAppModuleEntities = appModuleRepository.showAll();
String accessHTML = "";
String accessTableHTML = "";
// String MenuHTML = "";
// String subMenuHTML = "";
for (AppModuleEntity moduleName : getAppModuleEntities) {
accessHTML = accessHTML + "<li><input id=\"m" + moduleName.getId()
+ "\" type=\"checkbox\" data-type=\"parent\" value=\"\"/>&nbsp;<label for=\"m" + moduleName.getId()
+ "\" style=\"background-color:#000;color:#fff;\">&nbsp;&nbsp;<i class=\"" + moduleName.getIcon()
+ "\"></i> " + moduleName.getName() + "&nbsp;&nbsp;</label>";
List<MenuItemEntity> getMenuItems;
getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItems) {
if (menuItem.getHasSub()) {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository
.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
subSubMenuHTML = subSubMenuHTML + "<li><input id=\"sm" + subMenuItem.getId()
+ "\" type=\"checkbox\" data-type=\"sub-child\"/> <label for=\"sm" + subMenuItem.getId()
+ "\"><i class=\"" + subMenuItem.getIcon() + "\"></i> " + subMenuItem.getName()
+ "</label></li>";
}
if (subSubMenuHTML.equals("")) {
subMenuHTML = subMenuHTML + "<li><input id=\"mm" + menuItem.getId()
+ "\" type=\"checkbox\" data-type=\"child\" /> <label for=\"mm" + menuItem.getId()
+ "\"><i class=\"" + menuItem.getIcon() + "\"></i> " + menuItem.getName()
+ "</label></li>";
} else {
subMenuHTML = subMenuHTML + "<li><input id=\"mm" + menuItem.getId()
+ "\" type=\"checkbox\" data-type=\"child\"/> <label for=\"mm" + menuItem.getId()
+ "\"><i class=\"" + menuItem.getIcon() + "\"></i> " + menuItem.getName()
+ "</label> <ul>" + subSubMenuHTML + "</ul></li>";
}
} else {
subMenuHTML = subMenuHTML + "<li><input id=\"mm" + menuItem.getId()
+ "\" type=\"checkbox\" data-type=\"child\"/> <label for=\"mm" + menuItem.getId()
+ "\"><i class=\"" + menuItem.getIcon() + "\"></i> " + menuItem.getName() + "</label></li>";
}
}
accessHTML = accessHTML + "<ul>" + subMenuHTML + "</ul></li>";
subMenuHTML = "";
}
accessTableHTML = "<ul id=\"tree\" class=\"checktree\">" + accessHTML + "</ul>";
return accessTableHTML;
}
}

60
src/main/java/com/gcc/election/controller/CustomErrorController.java → src/main/java/com/gcc/swm_services/controller/CustomErrorController.java

@ -1,4 +1,4 @@
package com.gcc.election.controller;
package com.gcc.swm_services.controller;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -14,16 +14,14 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.gcc.election.modeldata.ErrorResponse;
import com.gcc.swm_services.modeldata.ErrorResponse;
@Controller @Controller
public class CustomErrorController implements ErrorController{
private static final String ERROR_PATH = "/error";
public class CustomErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
private static final Map<Integer, String> PAGE_NAME_MAP = new HashMap<>(); private static final Map<Integer, String> PAGE_NAME_MAP = new HashMap<>();
public String getPageName(Integer statusCode) { public String getPageName(Integer statusCode) {
if (statusCode != null) { if (statusCode != null) {
return PAGE_NAME_MAP.getOrDefault(statusCode, "errorPage"); return PAGE_NAME_MAP.getOrDefault(statusCode, "errorPage");
@ -31,18 +29,20 @@ public class CustomErrorController implements ErrorController{
return "errorPage"; return "errorPage";
} }
} }
// Handle errors for web applications, return HTML error pages // Handle errors for web applications, return HTML error pages
@RequestMapping(value = ERROR_PATH, produces = "text/html") @RequestMapping(value = ERROR_PATH, produces = "text/html")
public String handleWebError(HttpServletRequest request, Model model) { public String handleWebError(HttpServletRequest request, Model model) {
// Retrieve error information from the request // Retrieve error information from the request
// HttpStatus status = HttpStatus.valueOf((Integer) request.getAttribute("javax.servlet.error.status_code"));
//Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
// HttpStatus status = HttpStatus.valueOf((Integer)
// request.getAttribute("javax.servlet.error.status_code"));
// Throwable throwable = (Throwable)
// request.getAttribute("javax.servlet.error.exception");
// Retrieve error information from the request
// Retrieve error information from the request
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) { if (statusCode == null) {
// Add the error message to the model
// Add the error message to the model
model.addAttribute("errorStatus", "Error 403"); model.addAttribute("errorStatus", "Error 403");
model.addAttribute("errorError", "403 - Access Denied"); model.addAttribute("errorError", "403 - Access Denied");
model.addAttribute("errorMessage", "Oops, You don`t have permission to access this page."); model.addAttribute("errorMessage", "Oops, You don`t have permission to access this page.");
@ -50,7 +50,7 @@ public class CustomErrorController implements ErrorController{
// You may choose to set default values or redirect to a generic error page // You may choose to set default values or redirect to a generic error page
return "error-403"; return "error-403";
} }
HttpStatus status = (statusCode != null) ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR; HttpStatus status = (statusCode != null) ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR;
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
@ -59,41 +59,38 @@ public class CustomErrorController implements ErrorController{
Integer errorStatus = 404; Integer errorStatus = 404;
String errorError = "Internal Server Error"; String errorError = "Internal Server Error";
String errorMessage = "An error occurred"; // Default error message String errorMessage = "An error occurred"; // Default error message
String pageName = new CustomErrorController().getPageName(status.value()); String pageName = new CustomErrorController().getPageName(status.value());
// Print error information to the console // Print error information to the console
if (status != null) { if (status != null) {
errorStatus = status.value();
errorStatus = status.value();
errorError = status.getReasonPhrase(); errorError = status.getReasonPhrase();
System.err.println("HTTP Status: " + status +"\n"
+"Status Code: "+status.value()+"\n"+ "Status Error: "
+status.getReasonPhrase()
+"Page Name: "+pageName);
System.err.println("HTTP Status: " + status + "\n"
+ "Status Code: " + status.value() + "\n" + "Status Error: "
+ status.getReasonPhrase()
+ "Page Name: " + pageName);
// Check if the status code // Check if the status code
if (status == HttpStatus.NOT_FOUND) { if (status == HttpStatus.NOT_FOUND) {
errorPage = "error-404"; // 400 Error Page errorPage = "error-404"; // 400 Error Page
}
else if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
} else if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
errorPage = "error-500"; // 500 Error page errorPage = "error-500"; // 500 Error page
}
else {
errorPage = "error"; //// Other Error page
} else {
errorPage = "error"; //// Other Error page
} }
} }
if (throwable != null) { if (throwable != null) {
// Retrieve the exception message
// Retrieve the exception message
errorMessage = throwable.getMessage(); errorMessage = throwable.getMessage();
throwable.printStackTrace(); throwable.printStackTrace();
} }
// Add the error message to the model // Add the error message to the model
model.addAttribute("errorStatus", errorStatus); model.addAttribute("errorStatus", errorStatus);
model.addAttribute("errorError", errorError); model.addAttribute("errorError", errorError);
model.addAttribute("errorMessage", errorMessage); model.addAttribute("errorMessage", errorMessage);
return errorPage; // Return the name of your custom HTML error page (without the .html extension) return errorPage; // Return the name of your custom HTML error page (without the .html extension)
} }
@ -120,7 +117,6 @@ public class CustomErrorController implements ErrorController{
return ResponseEntity.status(status).body(errorResponse); return ResponseEntity.status(status).body(errorResponse);
} }
@GetMapping(ERROR_PATH) @GetMapping(ERROR_PATH)
public String handleError() { public String handleError() {
return "error-404"; // Return the name of your custom error page (without the .html extension) return "error-404"; // Return the name of your custom error page (without the .html extension)

23
src/main/java/com/gcc/election/controller/DateTimeUtil.java → src/main/java/com/gcc/swm_services/controller/DateTimeUtil.java

@ -1,36 +1,39 @@
package com.gcc.election.controller;
package com.gcc.swm_services.controller;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@Service @Service
public class DateTimeUtil { public class DateTimeUtil {
public static String getCurrentDateTime() {
public static String getCurrentDateTime() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss");
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
return now.format(formatter); return now.format(formatter);
} }
public static String getCurrentYear() {
public static String getCurrentYear() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
return now.format(formatter); return now.format(formatter);
} }
public static String getCurrentMonth() {
public static String getCurrentMonth() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
return now.format(formatter); return now.format(formatter);
} }
public static String getCurrentDay() {
public static String getCurrentDay() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
return now.format(formatter); return now.format(formatter);
} }
public static String getCurrentDateTimeMysql() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
public static String getCurrentDateTimeMysql() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
} }
} }

30
src/main/java/com/gcc/election/controller/FileController.java → src/main/java/com/gcc/swm_services/controller/FileController.java

@ -1,4 +1,4 @@
package com.gcc.election.controller;
package com.gcc.swm_services.controller;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
@ -11,8 +11,6 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.HandlerMapping;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@ -20,24 +18,25 @@ import javax.servlet.http.HttpServletRequest;
@Controller @Controller
public class FileController { public class FileController {
@Value("${file.upload.directory}")
@Value("${file.upload.directory}")
private String uploadDirectory; private String uploadDirectory;
@GetMapping("/election/files/{directoryPath}/**")
@GetMapping("/swm/files/{directoryPath}/**")
public ResponseEntity<Resource> serveFile(@PathVariable String directoryPath, HttpServletRequest request) { public ResponseEntity<Resource> serveFile(@PathVariable String directoryPath, HttpServletRequest request) {
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
System.out.println(fullPath.toString()+"\n"+directoryPath.length()+"\n directoryPath:"+directoryPath);
//String relativePath = fullPath.substring(directoryPath.length() + 1); // Adding 1 for the trailing '/'
String relativePath = fullPath.replace("/election/files", "");
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
System.out.println(fullPath.toString() + "\n" + directoryPath.length() + "\n directoryPath:" + directoryPath);
// String relativePath = fullPath.substring(directoryPath.length() + 1); //
// Adding 1 for the trailing '/'
String relativePath = fullPath.replace("/swm/files", "");
String filePath = uploadDirectory + "/" + relativePath; String filePath = uploadDirectory + "/" + relativePath;
Path path = Paths.get(filePath).normalize(); Path path = Paths.get(filePath).normalize();
System.out.println(path.toString()); System.out.println(path.toString());
Resource resource; Resource resource;
try {
try {
resource = new UrlResource(path.toUri()); resource = new UrlResource(path.toUri());
if (resource.exists() || resource.isReadable()) { if (resource.exists() || resource.isReadable()) {
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
// Determine content type based on file extension // Determine content type based on file extension
String fileName = resource.getFilename(); String fileName = resource.getFilename();
if (fileName != null) { if (fileName != null) {
@ -60,9 +59,10 @@ public class FileController {
} }
} }
return ResponseEntity.ok() return ResponseEntity.ok()
.contentType(mediaType)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
//.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.contentType(mediaType)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
// .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" +
// resource.getFilename() + "\"")
.body(resource); .body(resource);
} else { } else {
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();

36
src/main/java/com/gcc/swm_services/controller/MainController.java

@ -0,0 +1,36 @@
package com.gcc.swm_services.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 com.gcc.swm_services.service.LoginUserInfo;
@RequestMapping("/swm")
@Controller("MainController")
public class MainController {
private final LoginUserInfo loginUserInfo;
@Autowired
public MainController(LoginUserInfo loginUserInfo) {
this.loginUserInfo = loginUserInfo;
}
@GetMapping({ "", "/", "/index" })
public String main(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
if (LoginUserId != null && !LoginUserId.isEmpty()) {
System.out.println("String UserID: " + LoginUserId);
}
model.addAttribute("LoginUserId", LoginUserId);
return "index";
}
@GetMapping("/widget-statistic")
public String widgetStatistic(Model model) {
return "widget-statistic";
}
}

184
src/main/java/com/gcc/swm_services/controller/MenuController.java

@ -0,0 +1,184 @@
package com.gcc.swm_services.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.gcc.swm_services.entity.AppModuleAccessEntity;
import com.gcc.swm_services.entity.AppModuleEntity;
import com.gcc.swm_services.entity.MenuItemAccessEntity;
import com.gcc.swm_services.entity.MenuItemEntity;
import com.gcc.swm_services.entity.SubMenuItemAccessEntity;
import com.gcc.swm_services.entity.SubMenuItemEntity;
import com.gcc.swm_services.repository.AppModuleAccessRepository;
import com.gcc.swm_services.repository.AppModuleRepository;
import com.gcc.swm_services.repository.MenuItemAccessRepository;
import com.gcc.swm_services.repository.MenuItemRepository;
import com.gcc.swm_services.repository.SubMenuItemAccessRepository;
import com.gcc.swm_services.repository.SubMenuItemRepository;
import com.gcc.swm_services.service.LoginUserInfo;
@ControllerAdvice
public class MenuController {
private final AppModuleRepository appModuleRepository;
private final MenuItemRepository menuItemRepository;
private final SubMenuItemRepository subMenuItemRepository;
private final AppModuleAccessRepository appModuleAccessRepository;
private final MenuItemAccessRepository menuItemAccessRepository;
private final SubMenuItemAccessRepository subMenuItemAccessRepository;
@Autowired
public MenuController(AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository) {
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
}
@ModelAttribute("menuItemsHTML") // This will add the menuItems to the model for all requests
public String menuHTML() {
if (LoginUserInfo.getLoginUserId() == null || LoginUserInfo.getUserGroupId() == null) {
return "";
}
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<AppModuleEntity> getAppModuleEntities;
if (LoginUserInfo.getUserRole().equals("ADMIN")) {
getAppModuleEntities = appModuleRepository.showAll();
} else {
getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId());
String[] checkModuleId = new String[getAppModuleAccessEntities.size()];
int i = 0;
for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) {
checkModuleId[i] = accessEntity.getModuleId().getId().toString();
i++;
}
getAppModuleEntities = appModuleRepository.showAllById(checkModuleId);
}
String menuHTML = "";
menuHTML = "<div class=\"nav-item\"><a href=\"/swm\"><i class=\"ik ik-home\"></i><span>Dashboard</span></a></div>";
for (AppModuleEntity moduleName : getAppModuleEntities) {
menuHTML = menuHTML + "<div class=\"nav-item has-sub\"><a href=\"javascript:void(0)\"><i class=\""
+ moduleName.getIcon() + "\"></i><span>" + moduleName.getName()
+ "</span></a><div class=\"submenu-content\">";
List<MenuItemEntity> getMenuItems;
if (LoginUserInfo.getUserRole().equals("ADMIN")) {
getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId());
} else {
List<MenuItemAccessEntity> getMenuItemAccess = menuItemAccessRepository
.findByUserGroupID(LoginUserInfo.getUserGroupId(), moduleName.getId().toString());
String[] checkMenuId = new String[getMenuItemAccess.size()];
int j = 0;
for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) {
checkMenuId[j] = menuAccessEntity.getMenuItemId().getId().toString();
j++;
}
getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(moduleName.getId(), checkMenuId);
}
String subMenuHTML = "";
for (MenuItemEntity menuItem : getMenuItems) {
if (menuItem.getHasSub()) {
if (LoginUserInfo.getUserRole().equals("ADMIN")) {
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository
.getSubMenuItemByMenuItemId(menuItem.getId());
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if (subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML + "<a href=\"" + subMenuItem.getUrl()
+ "\" class=\"menu-item\"" + target + "><i class=\"" + subMenuItem.getIcon()
+ "\"></i><span>" + subMenuItem.getName() + "</span></a>";
} else {
subSubMenuHTML = subSubMenuHTML + "<a href=\"/swm/" + subMenuItem.getUrl()
+ "\" class=\"menu-item\"" + target + "><i class=\"" + subMenuItem.getIcon()
+ "\"></i><span>" + subMenuItem.getName() + "</span></a>";
}
}
if (subSubMenuHTML.equals("")) {
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>";
} else {
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>";
}
} else {
List<SubMenuItemAccessEntity> getSubMenuItemAccess = subMenuItemAccessRepository
.findByUserGroupIDAccess(LoginUserInfo.getUserGroupId(), moduleName.getId().toString(),
menuItem.getId().toString());
String[] checkSubMenuId = new String[getSubMenuItemAccess.size()];
if (checkSubMenuId.length > 0) {
int k = 0;
for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) {
checkSubMenuId[k] = subMenuItemAccessEntity.getSubMenuItemId().getId().toString();
k++;
}
List<SubMenuItemEntity> getMenuSubItems = subMenuItemRepository
.getSubMenuItemByMenuItemIdAccess(menuItem.getId(), checkSubMenuId);
String subSubMenuHTML = "";
for (SubMenuItemEntity subMenuItem : getMenuSubItems) {
String target = "";
System.err.println(subMenuItem.getExtenalLink());
if (subMenuItem.getExtenalLink()) {
target = " target=\"_blank\"";
subSubMenuHTML = subSubMenuHTML + "<a href=\"" + subMenuItem.getUrl()
+ "\" class=\"menu-item\"" + target + "><i class=\"" + subMenuItem.getIcon()
+ "\"></i><span>" + subMenuItem.getName() + "</span></a>";
} else {
subSubMenuHTML = subSubMenuHTML + "<a href=\"/swm/" + 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>";
} else {
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>";
}
}
} else {
if (menuItem.getOrderby() > 0) {
subMenuHTML = subMenuHTML + "<a href=\"/swm/" + menuItem.getUrl()
+ "\" class=\"menu-item\"><i class=\"" + menuItem.getIcon() + "\"></i><span>"
+ menuItem.getName() + "</span></a>";
}
}
}
menuHTML = menuHTML + subMenuHTML + "</div></div>";
}
return menuHTML;
}
}

6
src/main/java/com/gcc/election/controller/login.java → src/main/java/com/gcc/swm_services/controller/login.java

@ -1,12 +1,12 @@
package com.gcc.election.controller;
package com.gcc.swm_services.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/election")
@Controller("electionLoginController")
@RequestMapping("/swm")
@Controller("swmLoginController")
public class login { public class login {
@GetMapping("/login") @GetMapping("/login")

62
src/main/java/com/gcc/election/entity/AppModuleAccessEntity.java → src/main/java/com/gcc/swm_services/entity/AppModuleAccessEntity.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -17,100 +16,85 @@ public class AppModuleAccessEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppModuleAccessEntity() { public AppModuleAccessEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public AppUserGroupEntity getUserGroupId() { public AppUserGroupEntity getUserGroupId() {
return userGroupId; return userGroupId;
} }
public void setUserGroupId(AppUserGroupEntity userGroupId) { public void setUserGroupId(AppUserGroupEntity userGroupId) {
this.userGroupId = userGroupId; this.userGroupId = userGroupId;
} }
public AppModuleEntity getModuleId() { public AppModuleEntity getModuleId() {
return moduleId; return moduleId;
} }
public void setModuleId(AppModuleEntity moduleId) { public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId; this.moduleId = moduleId;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

80
src/main/java/com/gcc/election/entity/AppModuleEntity.java → src/main/java/com/gcc/swm_services/entity/AppModuleEntity.java

@ -1,4 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -7,130 +7,110 @@ import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name = "modules") @Table(name = "modules")
public class AppModuleEntity { public class AppModuleEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "module_path",nullable = false)
private String modulePath;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "module_path", nullable = false)
private String modulePath;
@Column(name = "icon", nullable = true)
private String icon;
@Column(name = "orderby", nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppModuleEntity() { public AppModuleEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getModulePath() { public String getModulePath() {
return modulePath; return modulePath;
} }
public String getIcon() { public String getIcon() {
return icon; return icon;
} }
public void setIcon(String icon) { public void setIcon(String icon) {
this.icon = icon; this.icon = icon;
} }
public void setModulePath(String modulePath) { public void setModulePath(String modulePath) {
this.modulePath = modulePath; this.modulePath = modulePath;
} }
public Integer getOrderby() { public Integer getOrderby() {
return orderby; return orderby;
} }
public void setOrderby(Integer orderby) { public void setOrderby(Integer orderby) {
this.orderby = orderby; this.orderby = orderby;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

87
src/main/java/com/gcc/election/entity/AppUserEntity.java → src/main/java/com/gcc/swm_services/entity/AppUserEntity.java

@ -1,4 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -10,146 +10,123 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name = "appusers") @Table(name = "appusers")
public class AppUserEntity { public class AppUserEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userid", referencedColumnName = "userid")
private UserInfoEntity userid;
@JoinColumn(name = "userid", referencedColumnName = "userid")
private UserInfoEntity userid;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity usergroup_id;
@Column(name = "username",nullable = false)
private String username;
@Column(name = "password",nullable = false)
private String password;
@Column(name = "roles",nullable = false)
private String roles;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity usergroup_id;
@Column(name = "username", nullable = false)
private String username;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "roles", nullable = false)
private String roles;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppUserEntity() { public AppUserEntity() {
} }
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public UserInfoEntity getUserid() { public UserInfoEntity getUserid() {
return userid; return userid;
} }
public void setUserid(UserInfoEntity userid) { public void setUserid(UserInfoEntity userid) {
this.userid = userid; this.userid = userid;
} }
public AppUserGroupEntity getUsergroup_id() { public AppUserGroupEntity getUsergroup_id() {
return usergroup_id; return usergroup_id;
} }
public void setUsergroup_id(AppUserGroupEntity usergroup_id) { public void setUsergroup_id(AppUserGroupEntity usergroup_id) {
this.usergroup_id = usergroup_id; this.usergroup_id = usergroup_id;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public String getRoles() { public String getRoles() {
return roles; return roles;
} }
public void setRoles(String roles) { public void setRoles(String roles) {
this.roles = roles; this.roles = roles;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

62
src/main/java/com/gcc/election/entity/AppUserGroupEntity.java → src/main/java/com/gcc/swm_services/entity/AppUserGroupEntity.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -14,98 +13,83 @@ public class AppUserGroupEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "icon", nullable = true)
private String icon;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public AppUserGroupEntity() { public AppUserGroupEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getIcon() { public String getIcon() {
return icon; return icon;
} }
public void setIcon(String icon) { public void setIcon(String icon) {
this.icon = icon; this.icon = icon;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

70
src/main/java/com/gcc/election/entity/MenuItemAccessEntity.java → src/main/java/com/gcc/swm_services/entity/MenuItemAccessEntity.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -17,114 +16,97 @@ public class MenuItemAccessEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@ManyToOne @ManyToOne
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public MenuItemAccessEntity() { public MenuItemAccessEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public AppUserGroupEntity getUserGroupId() { public AppUserGroupEntity getUserGroupId() {
return userGroupId; return userGroupId;
} }
public void setUserGroupId(AppUserGroupEntity userGroupId) { public void setUserGroupId(AppUserGroupEntity userGroupId) {
this.userGroupId = userGroupId; this.userGroupId = userGroupId;
} }
public MenuItemEntity getMenuItemId() { public MenuItemEntity getMenuItemId() {
return menuItemId; return menuItemId;
} }
public void setMenuItemId(MenuItemEntity menuItemId) { public void setMenuItemId(MenuItemEntity menuItemId) {
this.menuItemId = menuItemId; this.menuItemId = menuItemId;
} }
public AppModuleEntity getModuleId() { public AppModuleEntity getModuleId() {
return moduleId; return moduleId;
} }
public void setModuleId(AppModuleEntity moduleId) { public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId; this.moduleId = moduleId;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

96
src/main/java/com/gcc/election/entity/MenuItemEntity.java → src/main/java/com/gcc/swm_services/entity/MenuItemEntity.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -17,151 +16,128 @@ public class MenuItemEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "url",nullable = false)
private String url;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "ishassub",nullable = false, columnDefinition = "Boolean default false")
private Boolean hasSub;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "url", nullable = false)
private String url;
@Column(name = "icon", nullable = true)
private String icon;
@Column(name = "orderby", nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "ishassub", nullable = false, columnDefinition = "Boolean default false")
private Boolean hasSub;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public MenuItemEntity() { public MenuItemEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public AppModuleEntity getModuleId() { public AppModuleEntity getModuleId() {
return moduleId; return moduleId;
} }
public void setModuleId(AppModuleEntity moduleId) { public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId; this.moduleId = moduleId;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getUrl() { public String getUrl() {
return url; return url;
} }
public void setUrl(String url) { public void setUrl(String url) {
this.url = url; this.url = url;
} }
public String getIcon() { public String getIcon() {
return icon; return icon;
} }
public Integer getOrderby() { public Integer getOrderby() {
return orderby; return orderby;
} }
public void setOrderby(Integer orderby) { public void setOrderby(Integer orderby) {
this.orderby = orderby; this.orderby = orderby;
} }
public void setIcon(String icon) { public void setIcon(String icon) {
this.icon = icon; this.icon = icon;
} }
public Boolean getHasSub() { public Boolean getHasSub() {
return hasSub; return hasSub;
} }
public void setHasSub(Boolean hasSub) { public void setHasSub(Boolean hasSub) {
this.hasSub = hasSub; this.hasSub = hasSub;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

79
src/main/java/com/gcc/election/entity/SubMenuItemAccessEntity.java → src/main/java/com/gcc/swm_services/entity/SubMenuItemAccessEntity.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -17,129 +16,109 @@ public class SubMenuItemAccessEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@JoinColumn(name = "usergroup_id", referencedColumnName = "id")
private AppUserGroupEntity userGroupId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "submenuitem_id", referencedColumnName = "id")
private SubMenuItemEntity subMenuItemId;
@JoinColumn(name = "submenuitem_id", referencedColumnName = "id")
private SubMenuItemEntity subMenuItemId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public SubMenuItemAccessEntity() { public SubMenuItemAccessEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public AppUserGroupEntity getUserGroupId() { public AppUserGroupEntity getUserGroupId() {
return userGroupId; return userGroupId;
} }
public void setUserGroupId(AppUserGroupEntity userGroupId) { public void setUserGroupId(AppUserGroupEntity userGroupId) {
this.userGroupId = userGroupId; this.userGroupId = userGroupId;
} }
public SubMenuItemEntity getSubMenuItemId() { public SubMenuItemEntity getSubMenuItemId() {
return subMenuItemId; return subMenuItemId;
} }
public void setSubMenuItemId(SubMenuItemEntity subMenuItemId) { public void setSubMenuItemId(SubMenuItemEntity subMenuItemId) {
this.subMenuItemId = subMenuItemId; this.subMenuItemId = subMenuItemId;
} }
public AppModuleEntity getModuleId() { public AppModuleEntity getModuleId() {
return moduleId; return moduleId;
} }
public void setModuleId(AppModuleEntity moduleId) { public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId; this.moduleId = moduleId;
} }
public MenuItemEntity getMenuItemId() { public MenuItemEntity getMenuItemId() {
return menuItemId; return menuItemId;
} }
public void setMenuItemId(MenuItemEntity menuItemId) { public void setMenuItemId(MenuItemEntity menuItemId) {
this.menuItemId = menuItemId; this.menuItemId = menuItemId;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }

104
src/main/java/com/gcc/election/entity/SubMenuItemEntity.java → src/main/java/com/gcc/swm_services/entity/SubMenuItemEntity.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -18,163 +17,140 @@ public class SubMenuItemEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id",nullable = false)
private Integer id;
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@JoinColumn(name = "module_id", referencedColumnName = "id")
private AppModuleEntity moduleId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "url",nullable = false)
private String url;
@Column(name = "icon",nullable = true)
private String icon;
@Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@Column(name = "extenallink",nullable = false, columnDefinition = "Boolean default true")
private Boolean extenalLink;
@JoinColumn(name = "menuitem_id", referencedColumnName = "id")
private MenuItemEntity menuItemId;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "url", nullable = false)
private String url;
@Column(name = "icon", nullable = true)
private String icon;
@Column(name = "orderby", nullable = false, columnDefinition = "INTEGER default 0")
private Integer orderby;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
@Column(name = "extenallink", nullable = false, columnDefinition = "Boolean default true")
private Boolean extenalLink;
public SubMenuItemEntity() { public SubMenuItemEntity() {
}
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public AppModuleEntity getModuleId() { public AppModuleEntity getModuleId() {
return moduleId; return moduleId;
} }
public void setModuleId(AppModuleEntity moduleId) { public void setModuleId(AppModuleEntity moduleId) {
this.moduleId = moduleId; this.moduleId = moduleId;
} }
public MenuItemEntity getMenuItemId() { public MenuItemEntity getMenuItemId() {
return menuItemId; return menuItemId;
} }
public void setMenuItemId(MenuItemEntity menuItemId) { public void setMenuItemId(MenuItemEntity menuItemId) {
this.menuItemId = menuItemId; this.menuItemId = menuItemId;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getUrl() { public String getUrl() {
return url; return url;
} }
public void setUrl(String url) { public void setUrl(String url) {
this.url = url; this.url = url;
} }
public String getIcon() { public String getIcon() {
return icon; return icon;
} }
public void setIcon(String icon) { public void setIcon(String icon) {
this.icon = icon; this.icon = icon;
} }
public Integer getOrderby() { public Integer getOrderby() {
return orderby; return orderby;
} }
public void setOrderby(Integer orderby) { public void setOrderby(Integer orderby) {
this.orderby = orderby; this.orderby = orderby;
} }
public Boolean getIsDelete() { public Boolean getIsDelete() {
return isDelete; return isDelete;
} }
public void setIsDelete(Boolean isDelete) { public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete; this.isDelete = isDelete;
} }
public Boolean getIsActive() { public Boolean getIsActive() {
return isActive; return isActive;
} }
public void setIsActive(Boolean isActive) { public void setIsActive(Boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
} }
public Integer getCreatedBy() { public Integer getCreatedBy() {
return createdBy; return createdBy;
} }
public void setCreatedBy(Integer createdBy) { public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy; this.createdBy = createdBy;
} }
public String getcDate() { public String getcDate() {
return cDate; return cDate;
} }
public void setcDate(String cDate) { public void setcDate(String cDate) {
this.cDate = cDate; this.cDate = cDate;
} }
public Boolean getExtenalLink() { public Boolean getExtenalLink() {
return extenalLink; return extenalLink;
} }
public void setExtenalLink(Boolean extenalLink) { public void setExtenalLink(Boolean extenalLink) {
this.extenalLink = extenalLink; this.extenalLink = extenalLink;
} }

16
src/main/java/com/gcc/election/entity/UserActivityLog.java → src/main/java/com/gcc/swm_services/entity/UserActivityLog.java

@ -1,5 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -9,23 +8,22 @@ import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name = "user_activity_log") @Table(name = "user_activity_log")
public class UserActivityLog { public class UserActivityLog {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String userId;
private String activityType;
private String activityType;
private LocalDateTime timestamp;
private LocalDateTime timestamp;
public UserActivityLog() { public UserActivityLog() {
} }
public Long getId() { public Long getId() {

41
src/main/java/com/gcc/election/entity/UserInfoEntity.java → src/main/java/com/gcc/swm_services/entity/UserInfoEntity.java

@ -1,4 +1,4 @@
package com.gcc.election.entity;
package com.gcc.swm_services.entity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -8,39 +8,38 @@ import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name = "userinfo") @Table(name = "userinfo")
public class UserInfoEntity { public class UserInfoEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "userid",nullable = false)
private Integer userid;
@Column(name = "userid", nullable = false)
private Integer userid;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "email") @Column(name = "email")
private String email;
private String email;
@Column(name = "phone") @Column(name = "phone")
private String phone;
@Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
private String phone;
@Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false")
private Boolean isDelete;
@Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true")
private Boolean isActive;
@Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0")
private Integer createdBy;
@Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private String cDate;
public UserInfoEntity() { public UserInfoEntity() {
} }
public Integer getUserid() { public Integer getUserid() {

331
src/main/java/com/gcc/swm_services/interceptor/AppInterceptor.java

@ -0,0 +1,331 @@
package com.gcc.swm_services.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.gcc.swm_services.entity.AppModuleAccessEntity;
import com.gcc.swm_services.entity.AppModuleEntity;
import com.gcc.swm_services.entity.MenuItemAccessEntity;
import com.gcc.swm_services.entity.MenuItemEntity;
import com.gcc.swm_services.entity.SubMenuItemAccessEntity;
import com.gcc.swm_services.entity.SubMenuItemEntity;
import com.gcc.swm_services.repository.AppModuleAccessRepository;
import com.gcc.swm_services.repository.AppModuleRepository;
import com.gcc.swm_services.repository.MenuItemAccessRepository;
import com.gcc.swm_services.repository.MenuItemRepository;
import com.gcc.swm_services.repository.SubMenuItemAccessRepository;
import com.gcc.swm_services.repository.SubMenuItemRepository;
import com.gcc.swm_services.service.LoginUserInfo;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AppInterceptor implements HandlerInterceptor {
List<AppModuleAccessEntity> getAppModuleAccessEntities;
List<MenuItemAccessEntity> getMenuItemAccessEntities;
List<SubMenuItemAccessEntity> getSubMenuItemAccessEntities;
private AppModuleAccessRepository appModuleAccessRepository;
private MenuItemAccessRepository menuItemAccessRepository;
private SubMenuItemAccessRepository subMenuItemAccessRepository;
List<AppModuleEntity> getAppModuleEntities;
List<MenuItemEntity> getMenuItemEntities;
List<SubMenuItemEntity> getSubMenuItemEntities;
private AppModuleRepository appModuleRepository;
private MenuItemRepository menuItemRepository;
private SubMenuItemRepository subMenuItemRepository;
private final Environment environment;
@Autowired
public AppInterceptor(AppModuleAccessRepository appModuleAccessRepository,
MenuItemAccessRepository menuItemAccessRepository,
SubMenuItemAccessRepository subMenuItemAccessRepository,
AppModuleRepository appModuleRepository,
MenuItemRepository menuItemRepository,
SubMenuItemRepository subMenuItemRepository,
Environment environment) {
this.appModuleAccessRepository = appModuleAccessRepository;
this.menuItemAccessRepository = menuItemAccessRepository;
this.subMenuItemAccessRepository = subMenuItemAccessRepository;
this.appModuleRepository = appModuleRepository;
this.menuItemRepository = menuItemRepository;
this.subMenuItemRepository = subMenuItemRepository;
this.environment = environment;
}
private boolean isLoginPage(HttpServletRequest request) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/swm/login");
return loginPageMatcher.matches(request);
}
private boolean isErrorPage(HttpServletRequest request) {
RequestMatcher errorPageMatcher = new AntPathRequestMatcher("/swm/error");
return errorPageMatcher.matches(request);
}
private boolean isfavicon(HttpServletRequest request) {
RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/favicon.ico");
return loginPageMatcher.matches(request);
}
public static String[] Split(String request, String patten) {
String path = request;
// Split the string by "/"
String[] parts = path.split(patten);
// Display the parts
for (String part : parts) {
System.out.println(part);
}
return parts;
}
private boolean hasModuleAccess(String moduleName) {
getAppModuleEntities = appModuleRepository.findByModulePath(moduleName);
// System.out.println("DataTable Size for the url ("+moduleName+"):
// "+getAppModuleEntities.size());
String moduleid = null;
if (getAppModuleEntities.size() > 0) {
for (AppModuleEntity appModuleEntity : getAppModuleEntities) {
moduleid = appModuleEntity.getId().toString();
}
if (moduleid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasModuleAccess : Query input`s :\n userGroupId : " + userGroupId + "\n moduleid : "
+ moduleid);
getAppModuleAccessEntities = appModuleAccessRepository.findByAll(userGroupId, moduleid);
// System.out.println("After Check
// in(hasModuleAccess):"+getAppModuleAccessEntities.size());
if (getAppModuleAccessEntities.size() > 0) {
return true;
} else {
System.out.println(
"hasModuleAccess : getAppModuleAccessEntities.size = " + getAppModuleAccessEntities.size());
}
}
}
return false;
}
private boolean hasMenuAccess(String url, String moduleName, String menuName) {
if (!hasModuleAccess(moduleName)) {
return false;
}
getMenuItemEntities = menuItemRepository.findByUrl(url);
// System.out.println("DataTable Size for the url ("+url+"):
// "+getMenuItemEntities.size());
String moduleid = null;
String menuid = null;
if (getMenuItemEntities.size() > 0) {
for (MenuItemEntity MenuEntity : getMenuItemEntities) {
moduleid = MenuEntity.getModuleId().getId().toString();
menuid = MenuEntity.getId().toString();
}
if (moduleid != null && menuid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasMenuAccess : Query input`s :\n userGroupId : " + userGroupId + "\n moduleid : "
+ moduleid + "\n menuid : " + menuid);
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId, moduleid, menuid);
if (getMenuItemAccessEntities.size() > 0) {
return true;
}
}
}
return false;
}
private boolean hasSubMenuAccess(String url, String moduleName, String menuName, String subMenuName) {
if (!hasModuleAccess(moduleName)) {
return false;
}
getSubMenuItemEntities = subMenuItemRepository.findByUrl(url);
// System.out.println("DataTable Size for the url ("+url+"):
// "+getSubMenuItemEntities.size());
String moduleid = null;
String menuid = null;
String submenuid = null;
if (getSubMenuItemEntities.size() > 0) {
for (SubMenuItemEntity subMenuEntity : getSubMenuItemEntities) {
moduleid = subMenuEntity.getModuleId().getId().toString();
menuid = subMenuEntity.getMenuItemId().getId().toString();
submenuid = subMenuEntity.getId().toString();
}
if (moduleid != null && menuid != null && submenuid != null) {
String userGroupId = LoginUserInfo.getUserGroupId();
System.out.println("hasSubMenuAccess 1: Query input`s :\n userGroupId : " + userGroupId
+ "\n moduleid : " + moduleid + "\n menuid : " + menuid + "\n submenuid : " + submenuid);
getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(userGroupId, moduleid, menuid,
submenuid);
if (getSubMenuItemAccessEntities.size() > 0) {
// Check Parent Menu Access (Menu Access)
if (moduleid != null && menuid != null) {
System.out.println("hasSubMenuAccess 2: Query input`s :\n userGroupId : " + userGroupId
+ "\n moduleid : " + moduleid + "\n menuid : " + menuid);
getMenuItemAccessEntities = menuItemAccessRepository.findByAll(userGroupId, moduleid, menuid);
if (getMenuItemAccessEntities.size() > 0) {
return true;
}
}
}
}
}
return false;
}
private boolean hasAccess(String path) {
String userRole = LoginUserInfo.getUserRole();
if (userRole != null && userRole.equals("ADMIN")) {
return true;
}
/*
* if(LoginUserInfo.getUserRole().equals("ADMIN")) {
* return true;
* }
*/
String url = removeLeadingSlash(path);
url = removeStartingString(url); // Remove parent App url "gcc"
// System.out.println("Give URL : "+path+" After remove leading slash : "+url);
// If default home page
if (path.equals("/")) {
return true;
}
// continue for access check
String[] parts = Split(url, "/");
if (parts.length <= 0) {
return true;
}
// System.out.println("Part Length:"+ parts.length);
if (parts.length > 1) {
int j = 0;
for (String part : parts) {
System.out.println(j + ") URL SPLIT: " + part);
j++;
}
String moduleName = "";
String menuName = "";
String subMenuName = "";
if (parts.length == 1) { // Check Only Module Access
moduleName = parts[0];
return hasModuleAccess(moduleName);
} else if (parts.length == 2) { // Check Module & Menu Access
moduleName = parts[0];
menuName = parts[1];
subMenuName = "";
return hasMenuAccess(url, moduleName, menuName);
} else if (parts.length == 3) { // Check Module , Menu & Sub-Menu Access
moduleName = parts[0];
menuName = parts[1];
subMenuName = parts[2];
return hasSubMenuAccess(url, moduleName, menuName, subMenuName);
}
}
return true;
}
public static String removeLeadingSlash(String input) {
if (input.startsWith("/")) {
return input.substring(1);
}
return input;
}
public static String removeStartingString(String input) {
if (input.startsWith("swm")) {
return removeLeadingSlash(input.substring(3));
}
return input;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String assetsBaseUrl = environment.getProperty("assets.base-url");
request.setAttribute("assetsBaseUrl", assetsBaseUrl);
if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
String fullRequestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String path = fullRequestURI.substring(contextPath.length());
if (!hasAccess(path)) {
// Object principal = authentication.getPrincipal();
// UserDetails userDetails = (UserDetails) principal;
// System.out.println("1) Access Deny For --- " +
// userDetails.getAuthorities().toString());
// Redirect to the error page
// response.sendRedirect(request.getContextPath() + "/error");
request.getRequestDispatcher("/error").forward(request, response);
// response.sendRedirect(request.getContextPath() + "/election/error");
// return false;
}
}
}
// Continue with the request processing
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// Check if the current request matches the login or error page URLs
if (!isLoginPage(request) && !isErrorPage(request) && !isfavicon(request)) {
if (modelAndView != null) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
request.setAttribute("assetsBaseUrl", assetsBaseUrl);
modelAndView.addObject("assetsBaseUrl", assetsBaseUrl);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
modelAndView.addObject("currentUserDetails", userDetails);
System.out.println(userDetails);
}
}
}
}
}
}

28
src/main/java/com/gcc/election/modeldata/ErrorResponse.java → src/main/java/com/gcc/swm_services/modeldata/ErrorResponse.java

@ -1,20 +1,20 @@
package com.gcc.election.modeldata;
package com.gcc.swm_services.modeldata;
public class ErrorResponse { public class ErrorResponse {
private int status; private int status;
private String error;
private String message;
private String exception;
// Constructors, getters, and setters for the above fields
public ErrorResponse(int status, String error, String message, String exception) {
this.status = status;
this.error = error;
this.message = message;
this.exception = exception;
}
private String error;
private String message;
private String exception;
// Constructors, getters, and setters for the above fields
public ErrorResponse(int status, String error, String message, String exception) {
this.status = status;
this.error = error;
this.message = message;
this.exception = exception;
}
public ErrorResponse() { public ErrorResponse() {
super(); super();

28
src/main/java/com/gcc/election/repository/AppModuleAccessRepository.java → src/main/java/com/gcc/swm_services/repository/AppModuleAccessRepository.java

@ -1,4 +1,4 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import java.util.List; import java.util.List;
@ -10,31 +10,31 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppModuleAccessEntity;
import com.gcc.swm_services.entity.AppModuleAccessEntity;
@Repository @Repository
@Transactional @Transactional
public interface AppModuleAccessRepository extends JpaRepository<AppModuleAccessEntity,Integer>{
public interface AppModuleAccessRepository extends JpaRepository<AppModuleAccessEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `modules_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true) @Query(value = "SELECT * FROM `modules_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true)
List<AppModuleAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id);
List<AppModuleAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id);
@Query(value = "SELECT * FROM `modules_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) @Query(value = "SELECT * FROM `modules_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true)
List<AppModuleAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id);
List<AppModuleAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id);
@Modifying @Modifying
@Query(value = "INSERT INTO `modules_access`(`module_id`, `usergroup_id`) VALUES (:module_id,:usergroup_id)", nativeQuery = true) @Query(value = "INSERT INTO `modules_access`(`module_id`, `usergroup_id`) VALUES (:module_id,:usergroup_id)", nativeQuery = true)
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id);
@Modifying @Modifying
@Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id", nativeQuery = true) @Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id", nativeQuery = true)
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id);
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id);
@Modifying @Modifying
@Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) @Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true)
void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id);

28
src/main/java/com/gcc/swm_services/repository/AppModuleRepository.java

@ -0,0 +1,28 @@
package com.gcc.swm_services.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.swm_services.entity.AppModuleEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface AppModuleRepository extends JpaRepository<AppModuleEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `modules` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`", nativeQuery = true)
List<AppModuleEntity> showAll();
@Query(value = "SELECT * FROM `modules` WHERE `id` IN (:checkModuleid) AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id`", nativeQuery = true)
List<AppModuleEntity> showAllById(String[] checkModuleid);
@Query(value = "SELECT * FROM `modules` WHERE (`module_path` = :module_path) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<AppModuleEntity> findByModulePath(String module_path);
}

10
src/main/java/com/gcc/election/repository/AppUserGroupRepository.java → src/main/java/com/gcc/swm_services/repository/AppUserGroupRepository.java

@ -1,19 +1,17 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppUserGroupEntity;
import com.gcc.swm_services.entity.AppUserGroupEntity;
import javax.transaction.Transactional; import javax.transaction.Transactional;
@Repository @Repository
@Transactional @Transactional
public interface AppUserGroupRepository extends JpaRepository<AppUserGroupEntity,Integer>{
public interface AppUserGroupRepository extends JpaRepository<AppUserGroupEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId(); Integer getLastInsertedId();
} }

18
src/main/java/com/gcc/election/repository/AppUserRepository.java → src/main/java/com/gcc/swm_services/repository/AppUserRepository.java

@ -1,6 +1,4 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import java.util.List; import java.util.List;
@ -8,7 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.swm_services.entity.AppUserEntity;
import javax.transaction.Transactional; import javax.transaction.Transactional;
@ -16,13 +14,13 @@ import javax.transaction.Transactional;
@Transactional @Transactional
public interface AppUserRepository extends JpaRepository<AppUserEntity, Integer> { public interface AppUserRepository extends JpaRepository<AppUserEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `appusers`", nativeQuery = true) @Query(value = "SELECT * FROM `appusers`", nativeQuery = true)
List<AppUserEntity> showAll();
List<AppUserEntity> showAll();
@Query(value = "SELECT * FROM `appusers` WHERE (userid=:userId AND `isdelete`=0)", nativeQuery = true) @Query(value = "SELECT * FROM `appusers` WHERE (userid=:userId AND `isdelete`=0)", nativeQuery = true)
List<AppUserEntity> showById(String userId);
List<AppUserEntity> showById(String userId);
AppUserEntity findByUsername(String username); AppUserEntity findByUsername(String username);
} }

30
src/main/java/com/gcc/election/repository/MenuItemAccessRepository.java → src/main/java/com/gcc/swm_services/repository/MenuItemAccessRepository.java

@ -1,6 +1,4 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import java.util.List; import java.util.List;
@ -10,7 +8,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.MenuItemAccessEntity;
import com.gcc.swm_services.entity.MenuItemAccessEntity;
import javax.transaction.Transactional; import javax.transaction.Transactional;
@ -19,22 +17,26 @@ import javax.transaction.Transactional;
public interface MenuItemAccessRepository extends JpaRepository<MenuItemAccessEntity, Integer> { public interface MenuItemAccessRepository extends JpaRepository<MenuItemAccessEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) @Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true)
List<MenuItemAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id);
List<MenuItemAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id);
@Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) @Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<MenuItemAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id);
List<MenuItemAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id);
@Modifying @Modifying
@Query(value = "INSERT INTO `menuitem_access`(`menuitem_id`, `module_id`, `usergroup_id`) VALUES (:menuitem_id,:module_id,:usergroup_id)", nativeQuery = true) @Query(value = "INSERT INTO `menuitem_access`(`menuitem_id`, `module_id`, `usergroup_id`) VALUES (:menuitem_id,:module_id,:usergroup_id)", nativeQuery = true)
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id);
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id,
@Param("menuitem_id") String menuitem_id);
@Modifying @Modifying
@Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id", nativeQuery = true) @Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id", nativeQuery = true)
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id);
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id);
@Modifying @Modifying
@Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) @Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true)
void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id);

20
src/main/java/com/gcc/election/repository/MenuItemRepository.java → src/main/java/com/gcc/swm_services/repository/MenuItemRepository.java

@ -1,6 +1,4 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import java.util.List; import java.util.List;
@ -9,7 +7,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.MenuItemEntity;
import com.gcc.swm_services.entity.MenuItemEntity;
import javax.transaction.Transactional; import javax.transaction.Transactional;
@ -17,15 +15,15 @@ import javax.transaction.Transactional;
@Transactional @Transactional
public interface MenuItemRepository extends JpaRepository<MenuItemEntity, Integer> { public interface MenuItemRepository extends JpaRepository<MenuItemEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId(); Integer getLastInsertedId();
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true)
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true)
List<MenuItemEntity> getMenuItemByModuleId(@Param("module_id") int module_id); List<MenuItemEntity> getMenuItemByModuleId(@Param("module_id") int module_id);
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`module_id`=:module_id AND `id` IN (:checkMenuid)) ORDER BY `orderby`", nativeQuery = true)
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`module_id`=:module_id AND `id` IN (:checkMenuid)) ORDER BY `orderby`", nativeQuery = true)
List<MenuItemEntity> getMenuItemByModuleIdAccess(@Param("module_id") int module_id, String[] checkMenuid); List<MenuItemEntity> getMenuItemByModuleIdAccess(@Param("module_id") int module_id, String[] checkMenuid);
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`url`=:url) LIMIT 0,1", nativeQuery = true)
@Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`url`=:url) LIMIT 0,1", nativeQuery = true)
List<MenuItemEntity> findByUrl(@Param("url") String url); List<MenuItemEntity> findByUrl(@Param("url") String url);
} }

34
src/main/java/com/gcc/election/repository/SubMenuItemAccessRepository.java → src/main/java/com/gcc/swm_services/repository/SubMenuItemAccessRepository.java

@ -1,4 +1,4 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import java.util.List; import java.util.List;
@ -8,34 +8,40 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.SubMenuItemAccessEntity;
import com.gcc.swm_services.entity.SubMenuItemAccessEntity;
import javax.transaction.Transactional; import javax.transaction.Transactional;
@Repository @Repository
@Transactional @Transactional
public interface SubMenuItemAccessRepository extends JpaRepository<SubMenuItemAccessEntity, Integer>{
public interface SubMenuItemAccessRepository extends JpaRepository<SubMenuItemAccessEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `submenuitem_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true) @Query(value = "SELECT * FROM `submenuitem_access` WHERE `usergroup_id`=:usergroup_id AND `isactive`=1 AND `isdelete`=0", nativeQuery = true)
List<SubMenuItemAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id);
List<SubMenuItemAccessEntity> findByUserGroupID(@Param("usergroup_id") String usergroup_id);
@Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) @Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true)
List<SubMenuItemAccessEntity> findByUserGroupIDAccess(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id);
List<SubMenuItemAccessEntity> findByUserGroupIDAccess(@Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id);
@Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) @Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<SubMenuItemAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id,@Param("submenuitem_id") String submenuitem_id);
List<SubMenuItemAccessEntity> findByAll(@Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id,
@Param("submenuitem_id") String submenuitem_id);
@Modifying @Modifying
@Query(value = "INSERT INTO `submenuitem_access`(`submenuitem_id`, `menuitem_id`, `module_id`, `usergroup_id`) VALUES (:submenuitem_id, :menuitem_id, :module_id, :usergroup_id)", nativeQuery = true) @Query(value = "INSERT INTO `submenuitem_access`(`submenuitem_id`, `menuitem_id`, `module_id`, `usergroup_id`) VALUES (:submenuitem_id, :menuitem_id, :module_id, :usergroup_id)", nativeQuery = true)
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id);
void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id,
@Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id);
@Modifying @Modifying
@Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id", nativeQuery = true) @Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id", nativeQuery = true)
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id);
void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id,
@Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id,
@Param("submenuitem_id") String submenuitem_id);
@Modifying @Modifying
@Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) @Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true)
void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id);

33
src/main/java/com/gcc/swm_services/repository/SubMenuItemRepository.java

@ -0,0 +1,33 @@
package com.gcc.swm_services.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.swm_services.entity.SubMenuItemEntity;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface SubMenuItemRepository extends JpaRepository<SubMenuItemEntity, Integer> {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId();
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByModuleId(@Param("module_id") int module_id);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `menuitem_id`=:menuitem_id ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByMenuItemId(@Param("menuitem_id") int menuitem_id);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`menuitem_id`=:menuitem_id AND `id` IN (:checkSubMenuid)) ORDER BY `orderby`", nativeQuery = true)
List<SubMenuItemEntity> getSubMenuItemByMenuItemIdAccess(@Param("menuitem_id") int menuitem_id,
String[] checkSubMenuid);
@Query(value = "SELECT * FROM `submenuitem` WHERE (`url`=:url) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true)
List<SubMenuItemEntity> findByUrl(@Param("url") String url);
}

6
src/main/java/com/gcc/election/repository/UserActivityLogRepository.java → src/main/java/com/gcc/swm_services/repository/UserActivityLogRepository.java

@ -1,13 +1,11 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.swm_services.entity.UserActivityLog;
import javax.transaction.Transactional; import javax.transaction.Transactional;

8
src/main/java/com/gcc/election/repository/UserInfoRepository.java → src/main/java/com/gcc/swm_services/repository/UserInfoRepository.java

@ -1,6 +1,4 @@
package com.gcc.election.repository;
package com.gcc.swm_services.repository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -10,7 +8,7 @@ import javax.transaction.Transactional;
@Repository @Repository
@Transactional @Transactional
public interface UserInfoRepository { public interface UserInfoRepository {
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
@Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
Integer getLastInsertedId(); Integer getLastInsertedId();
} }

37
src/main/java/com/gcc/swm_services/service/Base64Util.java

@ -0,0 +1,37 @@
package com.gcc.swm_services.service;
import java.util.Base64;
import org.springframework.stereotype.Service;
@Service
public class Base64Util {
// Encode to Base64
public static String encodeBase64(String value) {
if (value != null && !value.isEmpty()) {
byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes());
// Print the original value and its encoded version
// System.out.println(value + " : " + new String(encodedBytes));
return new String(encodedBytes);
} else {
return "";
}
}
// Decode from Base64
public static String decodeBase64(String encodedValue) {
if (encodedValue != null && !encodedValue.isEmpty()) {
try {
byte[] decodedBytes = Base64.getDecoder().decode(encodedValue);
return new String(decodedBytes);
} catch (IllegalArgumentException e) {
// Handle the exception, e.g., log it or return an error message
System.err.println("Error decoding Base64 string: " + e.getMessage());
return "error"; // Or return an error message string
}
} else {
return "";
}
}
}

19
src/main/java/com/gcc/election/service/CustomUserDetails.java → src/main/java/com/gcc/swm_services/service/CustomUserDetails.java

@ -1,5 +1,4 @@
package com.gcc.election.service;
package com.gcc.swm_services.service;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
@ -8,9 +7,9 @@ import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
public class CustomUserDetails implements UserDetails, Serializable{
public class CustomUserDetails implements UserDetails, Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String username; private String username;
private String password; private String password;
@ -22,12 +21,12 @@ public class CustomUserDetails implements UserDetails, Serializable{
private Map<String, Object> additionalAttributes; private Map<String, Object> additionalAttributes;
public CustomUserDetails(String username, String password, public CustomUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities,
boolean accountNonExpired,
boolean accountNonLocked,
boolean credentialsNonExpired,
boolean enabled,
Map<String, Object> additionalAttributes) {
Collection<? extends GrantedAuthority> authorities,
boolean accountNonExpired,
boolean accountNonLocked,
boolean credentialsNonExpired,
boolean enabled,
Map<String, Object> additionalAttributes) {
this.username = username; this.username = username;
this.password = password; this.password = password;
this.authorities = authorities; this.authorities = authorities;

81
src/main/java/com/gcc/election/service/CustomUserDetailsService.java → src/main/java/com/gcc/swm_services/service/CustomUserDetailsService.java

@ -1,4 +1,4 @@
package com.gcc.election.service;
package com.gcc.swm_services.service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -12,17 +12,17 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.gcc.election.entity.AppUserEntity;
import com.gcc.election.repository.AppUserRepository;
import com.gcc.swm_services.entity.AppUserEntity;
import com.gcc.swm_services.repository.AppUserRepository;
@Service @Service
public class CustomUserDetailsService implements UserDetailsService{
public class CustomUserDetailsService implements UserDetailsService {
private final AppUserRepository appUserRepository;
private final AppUserRepository appUserRepository;
private final UserActivityService userActivityService; private final UserActivityService userActivityService;
@Autowired @Autowired
public CustomUserDetailsService(AppUserRepository appUserRepository,UserActivityService userActivityService ) {
public CustomUserDetailsService(AppUserRepository appUserRepository, UserActivityService userActivityService) {
this.appUserRepository = appUserRepository; this.appUserRepository = appUserRepository;
this.userActivityService = userActivityService; this.userActivityService = userActivityService;
} }
@ -30,58 +30,57 @@ public class CustomUserDetailsService implements UserDetailsService{
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUserEntity appUserEntity = appUserRepository.findByUsername(username); AppUserEntity appUserEntity = appUserRepository.findByUsername(username);
userActivityService.logUserActivity("0", "Trying to Login with Username: " + username); userActivityService.logUserActivity("0", "Trying to Login with Username: " + username);
//System.out.println(username);
// System.out.println(username);
if (appUserEntity == null) { if (appUserEntity == null) {
//System.out.println("User not found");
userActivityService.logUserActivity("0","User (" + username +") not found");
// System.out.println("User not found");
userActivityService.logUserActivity("0", "User (" + username + ") not found");
throw new UsernameNotFoundException("User not found"); throw new UsernameNotFoundException("User not found");
} }
/* /*
return org.springframework.security.core.userdetails.User.builder()
.username(appUserEntity.getUsername())
.password(appUserEntity.getPassword())
.roles(appUserEntity.getRoles())
.additionalAttributes(Map.of("userid", appUserEntity.getUserid()))
.build();
*/
* return org.springframework.security.core.userdetails.User.builder()
* .username(appUserEntity.getUsername())
* .password(appUserEntity.getPassword())
* .roles(appUserEntity.getRoles())
* .additionalAttributes(Map.of("userid", appUserEntity.getUserid()))
* .build();
*/
String userRole = appUserEntity.getRoles(); String userRole = appUserEntity.getRoles();
// Ensure that the role starts with "ROLE_" // Ensure that the role starts with "ROLE_"
if (!userRole.startsWith("ROLE_")) { if (!userRole.startsWith("ROLE_")) {
userRole = "ROLE_" + userRole; userRole = "ROLE_" + userRole;
//System.out.println("User Role: "+userRole);
// System.out.println("User Role: "+userRole);
} }
// Create a SimpleGrantedAuthority for the user role // Create a SimpleGrantedAuthority for the user role
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole); SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole);
// Create a list to hold the authority/role // Create a list to hold the authority/role
List<GrantedAuthority> authorityList = new ArrayList<>(); List<GrantedAuthority> authorityList = new ArrayList<>();
authorityList.add(authority); authorityList.add(authority);
// Construct CustomUserDetails instance with custom attributes // Construct CustomUserDetails instance with custom attributes
CustomUserDetails userDetails = new CustomUserDetails( CustomUserDetails userDetails = new CustomUserDetails(
appUserEntity.getUsername(),
appUserEntity.getPassword(),
authorityList,
true,
true,
true,
true,
Map.of("userid",appUserEntity.getUserid().getUserid(),
"usergroupid",appUserEntity.getUsergroup_id().getId(),
"userrole",appUserEntity.getRoles().toString()
)
);
userActivityService.logUserActivity(appUserEntity.getUserid().getUserid().toString(), "Login Success: <br>Username: "+appUserEntity.getUsername()
+"<br>Role: "+appUserEntity.getRoles().toString()
+"<br>Access Group: "+appUserEntity.getUsergroup_id().getName()
+"<br>Access Group ID: "+appUserEntity.getUsergroup_id().getId());
appUserEntity.getUsername(),
appUserEntity.getPassword(),
authorityList,
true,
true,
true,
true,
Map.of("userid", appUserEntity.getUserid().getUserid(),
"usergroupid", appUserEntity.getUsergroup_id().getId(),
"userrole", appUserEntity.getRoles().toString()));
userActivityService.logUserActivity(appUserEntity.getUserid().getUserid().toString(),
"Login Success: <br>Username: " + appUserEntity.getUsername()
+ "<br>Role: " + appUserEntity.getRoles().toString()
+ "<br>Access Group: " + appUserEntity.getUsergroup_id().getName()
+ "<br>Access Group ID: " + appUserEntity.getUsergroup_id().getId());
return userDetails; return userDetails;
} }
} }

188
src/main/java/com/gcc/election/service/LoginUserInfo.java → src/main/java/com/gcc/swm_services/service/LoginUserInfo.java

@ -1,4 +1,4 @@
package com.gcc.election.service;
package com.gcc.swm_services.service;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
@ -22,15 +22,14 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Service @Service
public class LoginUserInfo { public class LoginUserInfo {
private JdbcTemplate jdbcAppTemplate;
private JdbcTemplate jdbcKuralTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource sosDataSource
) {
this.jdbcAppTemplate = new JdbcTemplate(sosDataSource);
}
private JdbcTemplate jdbcAppTemplate;
private JdbcTemplate jdbcKuralTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource sosDataSource) {
this.jdbcAppTemplate = new JdbcTemplate(sosDataSource);
}
public static UserDetails getCurrentUserDetails() { public static UserDetails getCurrentUserDetails() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) { if (authentication != null && authentication.isAuthenticated()) {
@ -41,12 +40,12 @@ public class LoginUserInfo {
} }
return null; return null;
} }
public static String getLoginUserId() { public static String getLoginUserId() {
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
if (userDetails instanceof CustomUserDetails) { if (userDetails instanceof CustomUserDetails) {
//System.out.println("User Details : "+userDetails.toString());
// System.out.println("User Details : "+userDetails.toString());
CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes(); Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes();
if (additionalAttributes != null) { if (additionalAttributes != null) {
@ -57,17 +56,18 @@ public class LoginUserInfo {
} }
} }
/* /*
for (Map.Entry<String, Object> entry : additionalAttributes.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}*/
* for (Map.Entry<String, Object> entry : additionalAttributes.entrySet()) {
* String key = entry.getKey();
* Object value = entry.getValue();
* System.out.println("Key: " + key + ", Value: " + value);
* }
*/
} }
return null;
return null;
} }
public static String getUserGroupId() { public static String getUserGroupId() {
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
if (userDetails instanceof CustomUserDetails) { if (userDetails instanceof CustomUserDetails) {
CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes(); Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes();
@ -78,11 +78,11 @@ public class LoginUserInfo {
} }
} }
} }
return null;
return null;
} }
public static String getUserRole() { public static String getUserRole() {
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
UserDetails userDetails = LoginUserInfo.getCurrentUserDetails();
if (userDetails instanceof CustomUserDetails) { if (userDetails instanceof CustomUserDetails) {
CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes(); Map<String, Object> additionalAttributes = customUserDetails.getAdditionalAttributes();
@ -93,15 +93,15 @@ public class LoginUserInfo {
} }
} }
} }
return null;
return null;
} }
public String resetPassword(String userid, String oldPassword, String newPassword, String rawPassword) { public String resetPassword(String userid, String oldPassword, String newPassword, String rawPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// Query to get the stored encoded password for the given user ID // Query to get the stored encoded password for the given user ID
String fetchPasswordQuery = "SELECT `password` FROM `appusers` WHERE `id` = ?"; String fetchPasswordQuery = "SELECT `password` FROM `appusers` WHERE `id` = ?";
List<Map<String, Object>> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{userid});
List<Map<String, Object>> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[] { userid });
if (result.isEmpty()) { if (result.isEmpty()) {
// If no matching user is found, return an error message // If no matching user is found, return an error message
@ -121,7 +121,8 @@ public class LoginUserInfo {
// Update the password in the database // Update the password in the database
String updateQuery = "UPDATE `appusers` SET `password` = ?, `pwd_txt` = ? WHERE `id` = ?"; String updateQuery = "UPDATE `appusers` SET `password` = ?, `pwd_txt` = ? WHERE `id` = ?";
int rowsAffected = jdbcAppTemplate.update(updateQuery, new Object[]{encodedNewPassword, newPassword, userid});
int rowsAffected = jdbcAppTemplate.update(updateQuery,
new Object[] { encodedNewPassword, newPassword, userid });
if (rowsAffected > 0) { if (rowsAffected > 0) {
// If the update is successful, return a success message // If the update is successful, return a success message
@ -131,78 +132,79 @@ public class LoginUserInfo {
return "Failed to reset the password. Please try again."; return "Failed to reset the password. Please try again.";
} }
} }
public List<Map<String, Object>> userCheck(String username, String password) { public List<Map<String, Object>> userCheck(String username, String password) {
Integer statusCode=404;
String statusTxt="error";
String msgTxt="User not found.";
Map<String, Object> response = new HashMap<>();
Integer statusCode = 404;
String statusTxt = "error";
String msgTxt = "User not found.";
Map<String, Object> response = new HashMap<>();
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// Query to get the stored encoded password for the given user ID // Query to get the stored encoded password for the given user ID
String fetchPasswordQuery = "SELECT `id`, `roles`, `usergroup_id`, `isactive`, `dname`, `password` as saltref FROM `appusers` WHERE `username` = ? AND (`isactive`=1 AND `isdelete`=0)";
List<Map<String, Object>> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{username});
String fetchPasswordQuery = "SELECT `id`, `roles`, `usergroup_id`, `isactive`, `username`, `password` as saltref FROM `appusers` WHERE `username` = ? AND (`isactive`=1 AND `isdelete`=0)";
List<Map<String, Object>> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[] { username });
if (result.isEmpty()) { if (result.isEmpty()) {
System.out.println(fetchPasswordQuery);
System.out.println(fetchPasswordQuery);
// If no matching user is found, return an error message // If no matching user is found, return an error message
msgTxt = "User not found.";
response.put("Data", Collections.emptyList());
}
else {
String storedEncodedPassword = (String) result.get(0).get("saltref");
// Verify the password against the stored encoded password
if (!passwordEncoder.matches(password, storedEncodedPassword)) {
msgTxt = "User not found.";
response.put("Data", Collections.emptyList());
}
else {
statusCode=200;
statusTxt="success";
msgTxt = "Login Successfully";
if (result.isEmpty()) {
} else {
response.put("Data", result);
}
}
msgTxt = "User not found.";
response.put("Data", Collections.emptyList());
} else {
String storedEncodedPassword = (String) result.get(0).get("saltref");
// Verify the password against the stored encoded password
if (!passwordEncoder.matches(password, storedEncodedPassword)) {
msgTxt = "User not found.";
response.put("Data", Collections.emptyList());
} else {
statusCode = 200;
statusTxt = "success";
msgTxt = "Login Successfully";
if (result.isEmpty()) {
} else {
response.put("Data", result);
}
}
} }
response.put("statusCode", statusCode); response.put("statusCode", statusCode);
response.put("statusText", statusTxt);
response.put("message", msgTxt);
return Collections.singletonList(response);
response.put("statusText", statusTxt);
response.put("message", msgTxt);
return Collections.singletonList(response);
} }
// Dashboard : தினம் ஒரு திருக்குறள் // thirukkural // Dashboard : தினம் ஒரு திருக்குறள் // thirukkural
// public List<Map<String, Object>> getDailyContent() {
// // Query to get all content from the table
// String contentQuery = "SELECT * FROM kural"; // Replace content_table with your actual table name
// List<Map<String, Object>> contentList = jdbcKuralTemplate.queryForList(contentQuery);
//
// // Total number of records
// int totalRecords = contentList.size();
//
// if (totalRecords == 0) {
// // If there are no records, return an empty list
// return Collections.emptyList();
// }
//
// // Calculate the number of days since a specific start date (e.g., October 21, 2024)
// LocalDate startDate = LocalDate.of(2024, 10, 21);
// LocalDate currentDate = LocalDate.now();
// long daysSinceStart = ChronoUnit.DAYS.between(startDate, currentDate);
//
// // Get the content index for today (using modulo to cycle through the records)
// int contentIndex = (int) (daysSinceStart % totalRecords);
//
// // Return the content for today as a list
// return Collections.singletonList(contentList.get(contentIndex));
// }
// public List<Map<String, Object>> getDailyContent() {
// // Query to get all content from the table
// String contentQuery = "SELECT * FROM kural"; // Replace content_table with
// your actual table name
// List<Map<String, Object>> contentList =
// jdbcKuralTemplate.queryForList(contentQuery);
//
// // Total number of records
// int totalRecords = contentList.size();
//
// if (totalRecords == 0) {
// // If there are no records, return an empty list
// return Collections.emptyList();
// }
//
// // Calculate the number of days since a specific start date (e.g., October
// 21, 2024)
// LocalDate startDate = LocalDate.of(2024, 10, 21);
// LocalDate currentDate = LocalDate.now();
// long daysSinceStart = ChronoUnit.DAYS.between(startDate, currentDate);
//
// // Get the content index for today (using modulo to cycle through the
// records)
// int contentIndex = (int) (daysSinceStart % totalRecords);
//
// // Return the content for today as a list
// return Collections.singletonList(contentList.get(contentIndex));
// }
} }

8
src/main/java/com/gcc/election/service/UserActivityService.java → src/main/java/com/gcc/swm_services/service/UserActivityService.java

@ -1,17 +1,17 @@
package com.gcc.election.service;
package com.gcc.swm_services.service;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.election.repository.UserActivityLogRepository;
import com.gcc.swm_services.entity.UserActivityLog;
import com.gcc.swm_services.repository.UserActivityLogRepository;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@Service @Service
public class UserActivityService { public class UserActivityService {
private final UserActivityLogRepository userActivityLogRepository;
private final UserActivityLogRepository userActivityLogRepository;
@Autowired @Autowired
public UserActivityService(UserActivityLogRepository userActivityLogRepository) { public UserActivityService(UserActivityLogRepository userActivityLogRepository) {

11
src/main/java/com/gcc/election/service/UserActivityTimelineService.java → src/main/java/com/gcc/swm_services/service/UserActivityTimelineService.java

@ -1,17 +1,18 @@
package com.gcc.election.service;
package com.gcc.swm_services.service;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.gcc.election.entity.UserActivityLog;
import com.gcc.election.repository.UserActivityLogRepository;
import com.gcc.swm_services.entity.UserActivityLog;
import com.gcc.swm_services.repository.UserActivityLogRepository;
import java.util.List; import java.util.List;
@Service @Service
public class UserActivityTimelineService { public class UserActivityTimelineService {
private final UserActivityLogRepository userActivityLogRepository;
private final UserActivityLogRepository userActivityLogRepository;
@Autowired @Autowired
public UserActivityTimelineService(UserActivityLogRepository userActivityLogRepository) { public UserActivityTimelineService(UserActivityLogRepository userActivityLogRepository) {
this.userActivityLogRepository = userActivityLogRepository; this.userActivityLogRepository = userActivityLogRepository;

163
src/main/java/com/gcc/swm_services/swm/controller/AdminController.java

@ -0,0 +1,163 @@
package com.gcc.swm_services.swm.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 com.gcc.swm_services.service.LoginUserInfo;
@Controller("AdminswmController")
@RequestMapping("/swm/adminfacilities")
public class AdminController {
@GetMapping("/mcc")
public String mcc(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 1; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/mcc";
}
@GetMapping("/windrow")
public String windrow(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 2; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/windrow";
}
@GetMapping("/biocng")
public String biocng(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 3; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/biocng";
}
@GetMapping("/biogas")
public String biogas(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 4; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/biogas";
}
@GetMapping("/gwtcwaste")
public String gwtcwaste(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 5; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/gwtcwaste";
}
@GetMapping("/mrf")
public String mrf(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 6; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/mrf";
}
@GetMapping("/incinerator")
public String incinerator(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 7; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/incinerator";
}
@GetMapping("/plastingbaling")
public String plastingbaling(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
int facilityTypeId = 8; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
return "modules/swm/plastingbaling";
}
@GetMapping("/cdwaste")
public String cdwaste(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 9; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/cdwaste";
}
@GetMapping("/reports")
public String reports(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
int facilityTypeId = 9; // Plastic Baling Centre
model.addAttribute("facilityTypeId", facilityTypeId);
return "modules/swm/reports";
}
}

35
src/main/java/com/gcc/swm_services/swm/controller/DropDownApiController.java

@ -0,0 +1,35 @@
package com.gcc.swm_services.swm.controller;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.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 com.gcc.swm_services.swm.service.DropDownService;
@RestController
@RequestMapping("/swm/api/dropdown")
public class DropDownApiController {
@Autowired
private DropDownService dropDownService;
@GetMapping("/getfacilitiestypelist")
public List<Map<String, Object>> getFacilitiesTypeList() {
return dropDownService.getFacilitiesTypeList();
}
@GetMapping("/getzoneslist")
public List<Map<String, Object>> getZonesList() {
return dropDownService.getZonesList();
}
}

70
src/main/java/com/gcc/swm_services/swm/controller/MainController.java

@ -0,0 +1,70 @@
package com.gcc.swm_services.swm.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gcc.swm_services.service.LoginUserInfo;
import com.gcc.swm_services.swm.service.AddDetailsService;
@Controller("swmController")
@RequestMapping("/swm/facilities")
public class MainController {
@Autowired
private AddDetailsService addDetailsService;
@GetMapping("/adddetails")
public String home(Model model, HttpSession session) {
String loginUserId = LoginUserInfo.getLoginUserId(); // String
String officerName = LoginUserInfo.getCurrentUserDetails().getUsername();
String userRole = LoginUserInfo.getUserRole();
// store in session
session.setAttribute("gcc_user_id", loginUserId);
session.setAttribute("username", officerName);
// 🔑 derive facility type
int gccUserId = Integer.parseInt(loginUserId);
int dpid = addDetailsService.getDpidByGccUserId(gccUserId);
// DIRECT MAPPING (as fixed earlier)
int facilityTypeId = dpid;
// 🔑 THIS WAS MISSING
boolean isTwoWeightFacility = (facilityTypeId == 5);
boolean isWeightTypeFacility = (facilityTypeId == 5 || facilityTypeId == 9);
// add to model
model.addAttribute("LoginUserId", loginUserId);
model.addAttribute("officer_name", officerName);
model.addAttribute("UserRole", userRole);
model.addAttribute("isTwoWeightFacility", isTwoWeightFacility);
model.addAttribute("isWeightTypeFacility", isWeightTypeFacility);
return "modules/swm/requestlist";
}
@GetMapping("/approvelist")
public String batches() {
return "modules/swm/approvelist";
}
@GetMapping("/reports")
public String dataentry(Model model) {
String LoginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("LoginUserId", LoginUserId);
String officer_name = LoginUserInfo.getCurrentUserDetails().getUsername();
model.addAttribute("officer_name", officer_name);
String UserRole = LoginUserInfo.getUserRole(); // rdo_north / rdo_central
model.addAttribute("UserRole", UserRole);
return "modules/swm/eachreport";
}
}

118
src/main/java/com/gcc/swm_services/swm/controller/SwmAdminApiController.java

@ -0,0 +1,118 @@
package com.gcc.swm_services.swm.controller;
import java.time.LocalDate;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.swm_services.service.LoginUserInfo;
import com.gcc.swm_services.swm.service.AddDetailsService;
@RestController
@RequestMapping("/swm/api/admin")
public class SwmAdminApiController {
@Autowired
private AddDetailsService addDetailsService;
@PostMapping("/addfacility")
public ResponseEntity<?> addFacilityForAdmin(
@RequestParam int facilityTypeId,
@RequestParam int zoneId,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate reqDate,
@RequestParam Double weight,
@RequestParam(required = false) Double weight1,
@RequestParam(required = false) String weightType,
@RequestParam String createdBy) {
try {
// 🔴 Validation
if (facilityTypeId < 1 || facilityTypeId > 9) {
throw new IllegalArgumentException("Invalid facility type");
}
if (zoneId <= 0) {
throw new IllegalArgumentException("Invalid zone");
}
if (reqDate == null) {
throw new IllegalArgumentException("Request date is required");
}
if (weight == null || weight <= 0) {
throw new IllegalArgumentException("Weight must be greater than zero");
}
// 🔴 Facility type 5 → TWO weights + weightType
if (facilityTypeId == 5) {
if (weight1 == null || weight1 <= 0) {
throw new IllegalArgumentException(
"Second weight is required for GW & TC Waste facility");
}
if (weightType == null || weightType.isBlank()) {
throw new IllegalArgumentException(
"Weight type (KDG / PDG) is required");
}
}
if (facilityTypeId == 9) {
if (weightType == null || weightType.isBlank()) {
throw new IllegalArgumentException(
"Weight type (KDG / PDG) is required");
}
}
// 🔐 Admin username for audit
// String createdBy = LoginUserInfo.getCurrentUserDetails().getUsername();
// 🔵 SAVE
addDetailsService.addFacility(
facilityTypeId,
zoneId,
reqDate,
createdBy,
weight,
weight1,
weightType);
return ResponseEntity.ok(
Map.of("status", "SUCCESS", "message", "Added successfully"));
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(
Map.of("status", "ERROR", "message", ex.getMessage()));
} catch (Exception ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
Map.of("status", "ERROR", "message", "Internal server error"));
}
}
@GetMapping("/reports")
public ResponseEntity<?> getZoneTargetPercentage(
@RequestParam String fromDate,
@RequestParam String toDate) {
if (fromDate == null || toDate == null ||
fromDate.isBlank() || toDate.isBlank()) {
return ResponseEntity.badRequest().body(
Map.of("status", "ERROR", "message", "Date range is required"));
}
return ResponseEntity.ok(
Map.of(
"status", "SUCCESS",
"data", addDetailsService.getZoneTargetPercentage(fromDate, toDate)));
}
}

193
src/main/java/com/gcc/swm_services/swm/controller/SwmApiController.java

@ -0,0 +1,193 @@
package com.gcc.swm_services.swm.controller;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
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.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gcc.swm_services.service.LoginUserInfo;
import com.gcc.swm_services.swm.service.AddDetailsService;
@RestController
@RequestMapping("/swm/api/facilities")
public class SwmApiController {
@Autowired
private AddDetailsService addDetailsService;
// @PostMapping("/addfacility")
// public ResponseEntity<?> addFacility(
// @RequestParam int zoneId,
// @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate
// reqDate,
// @RequestParam Double weight,
// @RequestParam(required = false) Double weight1,
// HttpSession session) {
// try {
// // 🔴 Validation
// if (zoneId <= 0) {
// throw new IllegalArgumentException("Invalid zone");
// }
// if (reqDate == null) {
// throw new IllegalArgumentException("Request date is required");
// }
// if (weight == null || weight <= 0) {
// throw new IllegalArgumentException("Weight must be greater than zero");
// }
// // 🔐 GET LOGIN DATA FROM SESSION (CORRECT WAY)
// Object gccUserIdObj = session.getAttribute("gcc_user_id");
// Object usernameObj = session.getAttribute("username");
// if (gccUserIdObj == null || usernameObj == null) {
// throw new IllegalStateException("User session expired. Please login again.");
// }
// int gccUserId = Integer.parseInt(gccUserIdObj.toString());
// String username = usernameObj.toString();
// // 🔐 DB MAPPING
// int dpid = addDetailsService.getDpidByGccUserId(gccUserId);
// int facilityTypeId = addDetailsService.getFacilityTypeIdByDpid(dpid);
// if (facilityTypeId == 5 && (weight1 == null || weight1 <= 0)) {
// throw new IllegalArgumentException(
// "Second weight is required for GW & TC Waste facility");
// }
// addDetailsService.addFacility(
// facilityTypeId,
// zoneId,
// reqDate,
// username,
// weight,
// weight1);
// return ResponseEntity.ok(
// Map.of("status", "SUCCESS", "message", "Facility added successfully"));
// } catch (IllegalArgumentException | IllegalStateException ex) {
// return ResponseEntity.badRequest().body(
// Map.of("status", "ERROR", "message", ex.getMessage()));
// } catch (Exception ex) {
// ex.printStackTrace();
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
// Map.of("status", "ERROR", "message", "Internal server error"));
// }
// }
@PostMapping("/addfacility")
public ResponseEntity<?> addFacility(
@RequestParam int zoneId,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate reqDate,
@RequestParam Double weight,
@RequestParam(required = false) Double weight1,
@RequestParam(required = false) String weightType, // ✅ ADDED
HttpSession session) {
try {
// 🔴 Validation
if (zoneId <= 0) {
throw new IllegalArgumentException("Invalid zone");
}
if (reqDate == null) {
throw new IllegalArgumentException("Request date is required");
}
if (weight == null || weight <= 0) {
throw new IllegalArgumentException("Weight must be greater than zero");
}
// 🔐 Session values
Object gccUserIdObj = session.getAttribute("gcc_user_id");
Object usernameObj = session.getAttribute("username");
if (gccUserIdObj == null || usernameObj == null) {
throw new IllegalStateException("User session expired. Please login again.");
}
int gccUserId = Integer.parseInt(gccUserIdObj.toString());
String username = usernameObj.toString();
// 🔐 gcc_user_id → dpid → facilityTypeId
int dpid = addDetailsService.getDpidByGccUserId(gccUserId);
int facilityTypeId = dpid;
// 🔴 Facility type 5 → TWO weights + weightType
if (facilityTypeId == 5) {
if (weight1 == null || weight1 <= 0) {
throw new IllegalArgumentException(
"Second weight is required for GW & TC Waste facility");
}
if (weightType == null || weightType.isBlank()) {
throw new IllegalArgumentException(
"Weight type (KDG / PDG) is required");
}
}
if (facilityTypeId == 9) {
if (weightType == null || weightType.isBlank()) {
throw new IllegalArgumentException(
"Weight type (KDG / PDG) is required");
}
}
// 🔵 SAVE
addDetailsService.addFacility(
facilityTypeId,
zoneId,
reqDate,
username,
weight,
weight1,
weightType // ✅ PASSED
);
return ResponseEntity.ok(
Map.of("status", "SUCCESS", "message", "Added successfully"));
} catch (IllegalArgumentException | IllegalStateException ex) {
return ResponseEntity.badRequest().body(
Map.of("status", "ERROR", "message", ex.getMessage()));
} catch (Exception ex) {
ex.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
Map.of("status", "ERROR", "message", "Internal server error"));
}
}
@GetMapping("/reports")
public ResponseEntity<?> getZoneWiseByLogin(
@RequestParam String username,
@RequestParam String fromDate,
@RequestParam String toDate) {
List<Map<String, Object>> data = addDetailsService.getZoneWiseFacilityByLogin(
username, fromDate, toDate);
return ResponseEntity.ok(Map.of(
"status", "SUCCESS",
"data", data));
}
}

362
src/main/java/com/gcc/swm_services/swm/service/AddDetailsService.java

@ -0,0 +1,362 @@
package com.gcc.swm_services.swm.service;
import java.sql.Timestamp;
import java.time.LocalDate;
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 AddDetailsService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSourcemysql(@Qualifier("mysqlSwmDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
// // ---------------- SAVE ----------------
// public void addFacility(
// int facilityTypeId,
// int zoneId,
// LocalDate reqDate,
// String createdBy,
// Double weight,
// Double weight1) {
// String sql = """
// INSERT INTO facilities_weight_details
// (ft_id, zone_id, req_date, cby, weight, weight_1)
// VALUES (?, ?, ?, ?, ?, ?)
// """;
// Timestamp reqTimestamp = Timestamp.valueOf(reqDate.atStartOfDay());
// Double dbWeight1 = (facilityTypeId == 5) ? weight1 : null;
// jdbcTemplate.update(
// sql,
// facilityTypeId,
// zoneId,
// reqTimestamp,
// createdBy,
// weight,
// dbWeight1);
// }
// public void addFacility(
// int facilityTypeId,
// int zoneId,
// LocalDate reqDate,
// String createdBy,
// Double weight,
// Double weight1,
// String weightType) {
// String sql = """
// INSERT INTO facilities_weight_details
// (ft_id, zone_id, req_date, cby, weight, weight_1, weight_type)
// VALUES (?, ?, ?, ?, ?, ?, ?)
// """;
// Timestamp reqTimestamp = Timestamp.valueOf(reqDate.atStartOfDay());
// Double dbWeight1 = (facilityTypeId == 5) ? weight1 : null;
// // ✅ weight_type allowed for GW & TC (5) AND PBC / C&D (9)
// String dbWeightType = (facilityTypeId == 5 || facilityTypeId == 9)
// ? weightType
// : null;
// jdbcTemplate.update(
// sql,
// facilityTypeId,
// zoneId,
// reqTimestamp,
// createdBy,
// weight,
// dbWeight1,
// dbWeightType);
// }
private Integer getExistingRecordId(
int facilityTypeId,
int zoneId,
LocalDate reqDate) {
String sql = """
SELECT fid
FROM facilities_weight_details
WHERE ft_id = ?
AND zone_id = ?
AND DATE(req_date) = ?
AND is_delete = 0
LIMIT 1
""";
List<Integer> ids = jdbcTemplate.query(
sql,
ps -> {
ps.setInt(1, facilityTypeId);
ps.setInt(2, zoneId);
ps.setDate(3, java.sql.Date.valueOf(reqDate));
},
(rs, rowNum) -> rs.getInt("fid"));
return ids.isEmpty() ? null : ids.get(0);
}
public void addFacility(
int facilityTypeId,
int zoneId,
LocalDate reqDate,
String officerName,
Double weight,
Double weight1,
String weightType) {
Timestamp reqTimestamp = Timestamp.valueOf(reqDate.atStartOfDay());
Double dbWeight1 = (facilityTypeId == 5) ? weight1 : null;
String dbWeightType = (facilityTypeId == 5 || facilityTypeId == 9)
? weightType
: null;
Integer existingId = getExistingRecordId(
facilityTypeId, zoneId, reqDate);
if (existingId == null) {
// 🟢 INSERT
String insertSql = """
INSERT INTO facilities_weight_details
(ft_id, zone_id, req_date, weight, weight_1, weight_type,
cby, cdate, is_active, is_delete)
VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)
""";
jdbcTemplate.update(
insertSql,
facilityTypeId,
zoneId,
reqTimestamp,
weight,
dbWeight1,
dbWeightType,
officerName);
} else {
// 🔵 UPDATE
String updateSql = """
UPDATE facilities_weight_details
SET weight = ?,
weight_1 = ?,
weight_type = ?,
updated_by = ?,
updated_date = NOW()
WHERE fid = ?
""";
jdbcTemplate.update(
updateSql,
weight,
dbWeight1,
dbWeightType,
officerName,
existingId);
}
}
// ---------------- DPID ----------------
public int getDpidByGccUserId(int gccUserId) {
String sql = """
SELECT dpid
FROM department_login
WHERE gcc_user_id = ?
AND is_active = 1
AND is_delete = 0
""";
List<Integer> list = jdbcTemplate.queryForList(sql, Integer.class, gccUserId);
if (list.isEmpty()) {
throw new IllegalArgumentException(
"Department not mapped for user id: " + gccUserId);
}
return list.get(0);
}
// ---------------- FACILITY TYPE ----------------
public int getFacilityTypeIdByDpid(int dpid) {
String sql = """
SELECT ft.ft_id
FROM department_login dl
JOIN facilities_type ft
ON LOWER(REPLACE(REPLACE(dl.department_name,'swm_',''),'_',' '))
LIKE CONCAT('%', LOWER(ft.facilities_name), '%')
WHERE dl.dpid = ?
AND dl.is_active = 1
AND dl.is_delete = 0
AND ft.is_active = 1
AND ft.is_delete = 0
""";
List<Integer> list = jdbcTemplate.queryForList(sql, Integer.class, dpid);
if (list.isEmpty()) {
throw new IllegalArgumentException(
"Facility type not mapped for department id: " + dpid);
}
return list.get(0);
}
public List<Map<String, Object>> getZoneTargetPercentage(
String fromDate, String toDate) {
String sql = """
SELECT
t.zone,
t.facility,
t.target,
COALESCE(a.achieved, 0) AS achieved,
ROUND(
CASE
WHEN t.target = 0 AND COALESCE(a.achieved, 0) > 0 THEN 100
WHEN t.target = 0 THEN 0
ELSE LEAST((COALESCE(a.achieved, 0) / t.target) * 100, 100)
END,
2
) AS percentage
FROM (
SELECT zone, 1 AS ft_id, 'MCC' AS facility, mcc AS target
FROM zonewise_target WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 2, 'Windrow', windrow FROM zonewise_target
WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 3, 'Bio-CNG', bio_cng FROM zonewise_target
WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 4, 'Bio-GAS', bio_gas FROM zonewise_target
WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 5, 'GW & TC Waste', gw_tc_waste FROM zonewise_target
WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 6, 'MRF OR RRC', mrf_mrr FROM zonewise_target
WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 7, 'Incinerator', incinerator FROM zonewise_target
WHERE is_active = 1 AND is_delete = 0
UNION ALL
SELECT zone, 9, 'Plastic Baling Centre', plasting_baling_centre
FROM zonewise_target WHERE is_active = 1 AND is_delete = 0
) t
LEFT JOIN (
SELECT
fwd.zone_id AS zone,
fwd.ft_id,
SUM(
CASE
WHEN fwd.ft_id = 5
THEN COALESCE(fwd.weight, 0)
+ COALESCE(fwd.weight_1, 0)
ELSE
COALESCE(fwd.weight, 0)
END
) AS achieved
FROM facilities_weight_details fwd
WHERE fwd.is_active = 1
AND fwd.is_delete = 0
AND DATE(fwd.req_date) BETWEEN ? AND ?
GROUP BY fwd.zone_id, fwd.ft_id
) a
ON a.zone = t.zone
AND a.ft_id = t.ft_id
ORDER BY t.zone, t.facility
""";
return jdbcTemplate.queryForList(sql, fromDate, toDate);
}
public List<Map<String, Object>> getZoneWiseFacilityByLogin(
String username,
String fromDate,
String toDate) {
String sql = """
SELECT
t.zone,
t.facility,
t.target,
COALESCE(a.achieved, 0) AS achieved,
ROUND(
CASE
WHEN t.target = 0 AND COALESCE(a.achieved, 0) > 0 THEN 100
WHEN t.target = 0 AND COALESCE(a.achieved, 0) = 0 THEN 0
ELSE LEAST((COALESCE(a.achieved, 0) / t.target) * 100, 100)
END, 2
) AS percentage
FROM (
/* 🔹 TARGET – ONLY FACILITY FROM LOGIN */
SELECT
zt.zone,
ft.facilities_name AS facility,
CASE
WHEN ft.facilities_name = 'MCC' THEN zt.mcc
WHEN ft.facilities_name = 'Windrow' THEN zt.windrow
WHEN ft.facilities_name = 'Bio-CNG' THEN zt.bio_cng
WHEN ft.facilities_name = 'Bio-GAS' THEN zt.bio_gas
WHEN ft.facilities_name = 'Incinerator' THEN zt.incinerator
WHEN ft.facilities_name = 'Plastic Baling Centre'
THEN zt.plasting_baling_centre
END AS target
FROM department_login dl
JOIN facilities_type ft ON ft.ft_id = dl.dpid
JOIN zonewise_target zt ON zt.is_active = 1 AND zt.is_delete = 0
WHERE dl.user_name = ?
) t
LEFT JOIN (
/* 🔹 ACHIEVED – SAME FT_ID + LOGIN */
SELECT
fwd.zone_id AS zone,
ft.facilities_name AS facility,
SUM(COALESCE(fwd.weight, 0) + COALESCE(fwd.weight_1, 0)) AS achieved
FROM facilities_weight_details fwd
JOIN facilities_type ft ON ft.ft_id = fwd.ft_id
WHERE fwd.is_active = 1
AND fwd.is_delete = 0
AND fwd.cby = ?
AND DATE(fwd.req_date) BETWEEN ? AND ?
GROUP BY fwd.zone_id, ft.facilities_name
) a
ON a.zone = t.zone AND a.facility = t.facility
ORDER BY t.zone
""";
return jdbcTemplate.queryForList(
sql,
username,
username,
fromDate,
toDate);
}
}

37
src/main/java/com/gcc/swm_services/swm/service/DropDownService.java

@ -0,0 +1,37 @@
package com.gcc.swm_services.swm.service;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class DropDownService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSourcemysql(@Qualifier("mysqlSwmDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getFacilitiesTypeList() {
String sql = " SELECT * FROM facilities_type where is_active = '1' and is_delete ='0' ";
return jdbcTemplate.queryForList(sql);
}
public List<Map<String, Object>> getZonesList() {
String sql = " SELECT * FROM zones where is_active = '1' and is_delete ='0' ";
return jdbcTemplate.queryForList(sql);
}
}

2
src/main/resources/application-dev.properties

@ -1,5 +1,5 @@
assets.base-url=/assets/ assets.base-url=/assets/
fileBaseUrl=http://localhost:8080
fileBaseUrl=http://localhost:8060
#fileBaseUrl = D:/Projects/Election_Project/election_v1/gcc_election_uploads #fileBaseUrl = D:/Projects/Election_Project/election_v1/gcc_election_uploads

2
src/main/resources/application-prod.properties

@ -1,3 +1,3 @@
assets.base-url=/election/assets/
assets.base-url=/swm/assets/
fileBaseUrl=https://gccservices.in/files fileBaseUrl=https://gccservices.in/files

4
src/main/resources/application.properties

@ -2,7 +2,7 @@ spring.profiles.active=dev
#spring.profiles.active=prod #spring.profiles.active=prod
# Spring properties # Spring properties
spring.application.name=election
spring.application.name=swm_login
spring.datasource.hikari.connection-timeout=30000 spring.datasource.hikari.connection-timeout=30000
@ -15,7 +15,7 @@ spring.servlet.multipart.max-file-size=20MB
spring.servlet.multipart.max-request-size=20MB spring.servlet.multipart.max-request-size=20MB
# HTTP Server # HTTP Server
server.port = 8080
server.port = 8060
#server.servlet.context-path=/gccoffice #server.servlet.context-path=/gccoffice
server.error.include-stacktrace= on_param server.error.include-stacktrace= on_param
# Hibernate logging # Hibernate logging

14
src/main/resources/templates/fragments/modules/base/footer.html

@ -1,7 +1,7 @@
<footer class="footer">
<form id="logout-form" th:action="@{/election/logout}" method="post" style="display: none;"></form>
<div class="w-100 clearfix text-center">
<span class="text-center">Copyright &copy; Greater Chennai Corporation | All rights reserved</span>
<!-- <span class="float-none float-sm-right mt-1 mt-sm-0 text-center">Coded By BonTon Softwares Pvt Ltd</span> -->
</div>
</footer>
<footer class="footer">
<form id="logout-form" th:action="@{/swm/logout}" method="post" style="display: none;"></form>
<div class="w-100 clearfix text-center">
<span class="text-center">Copyright &copy; Greater Chennai Corporation | All rights reserved</span>
<!-- <span class="float-none float-sm-right mt-1 mt-sm-0 text-center">Coded By BonTon Softwares Pvt Ltd</span> -->
</div>
</footer>

1541
src/main/resources/templates/fragments/modules/base/head.html
File diff suppressed because it is too large
View File

68
src/main/resources/templates/fragments/modules/base/header.html

@ -1,26 +1,26 @@
<header class="header-top">
<div class="container-fluid">
<div class="d-flex justify-content-between">
<header class="header-top">
<div class="container-fluid">
<div class="d-flex justify-content-between">
<div class="top-menu d-flex align-items-center">
<button type="button" class="btn-icon mobile-nav-toggle d-lg-none"><span></span></button>
<!-- <div class="header-search">
<div class="top-menu d-flex align-items-center">
<button type="button" class="btn-icon mobile-nav-toggle d-lg-none"><span></span></button>
<!-- <div class="header-search">
<div class="input-group"> <div class="input-group">
<span class="input-group-addon search-close"><i class="ik ik-x"></i></span> <span class="input-group-addon search-close"><i class="ik ik-x"></i></span>
<input type="text" class="form-control"> <input type="text" class="form-control">
<span class="input-group-addon search-btn"><i class="ik ik-search"></i></span> <span class="input-group-addon search-btn"><i class="ik ik-search"></i></span>
</div> </div>
</div> </div>
-->
<button type="button" id="navbar-fullscreen" class="nav-link"><i class="ik ik-maximize"></i></button>
</div>
<div id="headings_center">
Polling Personnel Data Management System
</div>
<div class="top-menu d-flex align-items-center">
<!-- <div class="dropdown">
-->
<button type="button" id="navbar-fullscreen" class="nav-link"><i class="ik ik-maximize"></i></button>
</div>
<div id="headings_center">
Solid Waste Management System
</div>
<div class="top-menu d-flex align-items-center">
<!-- <div class="dropdown">
<a class="nav-link dropdown-toggle" href="#" id="notiDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <a class="nav-link dropdown-toggle" href="#" id="notiDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="ik ik-bell bell"></i><span class="badge bg-danger">3</span> <i class="ik ik-bell bell"></i><span class="badge bg-danger">3</span>
</a> </a>
@ -58,24 +58,28 @@
<div class="footer"><a href="javascript:void(0);">See all activity</a></div> <div class="footer"><a href="javascript:void(0);">See all activity</a></div>
</div> </div>
</div> --> </div> -->
<div class="dropdown">
<a class="dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<img class="avatar" src="images/users/user.jpg" alt="">
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
<!-- <a class="dropdown-item" href="profile.html"><i class="ik ik-user dropdown-icon"></i> Profile</a>
<div class="dropdown">
<a class="dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<img class="avatar" src="images/users/user.jpg" alt="">
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
<!-- <a class="dropdown-item" href="profile.html"><i class="ik ik-user dropdown-icon"></i> Profile</a>
<a class="dropdown-item" href="#"><i class="ik ik-settings dropdown-icon"></i> Settings</a> <a class="dropdown-item" href="#"><i class="ik ik-settings dropdown-icon"></i> Settings</a>
<a class="dropdown-item" href="#"><span class="float-right"><span class="badge badge-primary">6</span></span><i class="ik ik-mail dropdown-icon"></i> Inbox</a> <a class="dropdown-item" href="#"><span class="float-right"><span class="badge badge-primary">6</span></span><i class="ik ik-mail dropdown-icon"></i> Inbox</a>
<a class="dropdown-item" href="#"><i class="ik ik-navigation dropdown-icon"></i> Message</a> --> <a class="dropdown-item" href="#"><i class="ik ik-navigation dropdown-icon"></i> Message</a> -->
<a class="dropdown-item" th:href="@{/election/logout}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"><i class="ik ik-power dropdown-icon"></i> Logout</a>
<a class="dropdown-item" th:href="@{#}" onclick="event.preventDefault();passwordReset();"><i class="ik ik-settings dropdown-icon"></i> Password Reset</a>
</div>
</div>
</div>
<a class="dropdown-item" th:href="@{/swm/logout}"
onclick="event.preventDefault(); document.getElementById('logout-form').submit();"><i
class="ik ik-power dropdown-icon"></i> Logout</a>
<a class="dropdown-item" th:href="@{#}" onclick="event.preventDefault();passwordReset();"><i
class="ik ik-settings dropdown-icon"></i> Password Reset</a>
</div> </div>
</div> </div>
</header>
</div>
</div>
</div>
</header>

1543
src/main/resources/templates/fragments/modules/base/login-head.html
File diff suppressed because it is too large
View File

644
src/main/resources/templates/fragments/modules/base/script.html

@ -37,339 +37,339 @@
<script src="dist/js/theme.js"></script> <script src="dist/js/theme.js"></script>
<script th:inline="javascript"> <script th:inline="javascript">
// Get the current page URL path
var currentPagePath = window.location.pathname;
// Remove the leading slash from the current page URL path
currentPagePath = currentPagePath.substr(1);
//alert(currentPagePath);
// Get the parent menu item and the sub-menu item based on the current page URL path
var parentMenuItem = document.querySelector('.nav-item.has-sub');
var subMenuItem = document.querySelector('.submenu-content .menu-item[href="' + currentPagePath + '"]');
// Add the "active" class to the parent menu item and its associated sub-menu item
if (parentMenuItem && subMenuItem) {
parentMenuItem.classList.add('active', 'open');
subMenuItem.classList.add('active');
}
// Get the current page URL path
var currentPagePath = window.location.pathname;
// Remove the leading slash from the current page URL path
currentPagePath = currentPagePath.substr(1);
//alert(currentPagePath);
// Get the parent menu item and the sub-menu item based on the current page URL path
var parentMenuItem = document.querySelector('.nav-item.has-sub');
var subMenuItem = document.querySelector('.submenu-content .menu-item[href="' + currentPagePath + '"]');
// Add the "active" class to the parent menu item and its associated sub-menu item
if (parentMenuItem && subMenuItem) {
parentMenuItem.classList.add('active', 'open');
subMenuItem.classList.add('active');
}
</script> </script>
<script th:inline="javascript"> <script th:inline="javascript">
$(document).ready(function() {
/*
// Get the current URL
var currentUrl = window.location.href;
// Remove the query parameter from the URL
var newUrl = currentUrl.split("?")[0];
// Replace the current URL with the modified URL without the query parameter
window.history.replaceState({}, document.title, newUrl);
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
var currentPagePath = window.location.pathname;
//console.error(currentPagePath);
currentPagePath = "/"+currentPagePath.substr(1);
//console.error(currentPagePath);
// Set active class for parent menu items
$('.nav-item').each(function() {
var link = $(this).find('a').attr('href');
//console.log("Main: "+link +" == "+ currentPagePath);
if (link === currentPagePath || link === currentPagePath) {
$(this).addClass('active');
$(this).parents('.has-sub').addClass('active open');
}
});
// Set active class for submenu items
$('.submenu-content .menu-item').each(function() {
var link = $(this).attr('href');
//console.log("Sub: "+link +" == "+ currentPagePath);
if (link === currentPagePath || link === currentPagePath) {
//console.error("Sub: "+link +" == "+ currentPagePath);
$(this).addClass('active');
$(this).parents('.has-sub').addClass('active open');
}
});
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
$(document).ready(function () {
/*
// Get the current URL
var currentUrl = window.location.href;
// Remove the query parameter from the URL
var newUrl = currentUrl.split("?")[0];
// Replace the current URL with the modified URL without the query parameter
window.history.replaceState({}, document.title, newUrl);
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
var currentPagePath = window.location.pathname;
//console.error(currentPagePath);
currentPagePath = "/" + currentPagePath.substr(1);
//console.error(currentPagePath);
// Set active class for parent menu items
$('.nav-item').each(function () {
var link = $(this).find('a').attr('href');
//console.log("Main: "+link +" == "+ currentPagePath);
if (link === currentPagePath || link === currentPagePath) {
$(this).addClass('active');
$(this).parents('.has-sub').addClass('active open');
}
});
// Set active class for submenu items
$('.submenu-content .menu-item').each(function () {
var link = $(this).attr('href');
//console.log("Sub: "+link +" == "+ currentPagePath);
if (link === currentPagePath || link === currentPagePath) {
//console.error("Sub: "+link +" == "+ currentPagePath);
$(this).addClass('active');
$(this).parents('.has-sub').addClass('active open');
}
});
$(document).ready(function () {
$('[data-toggle="popover"]').popover();
});
$(".select2").select2();
}); });
$(".select2").select2();
});
function call_loading(div,action){
var divID="#"+div;
var loadingimage= `<center><img src="images/loading.svg" style="opacity: 1; visibility: visible; height:40px;"></center>`;
if(action=='start'){
$(divID).html(loadingimage)
}
}
// Date format
function convertdate(date_txt){
var datetxt = date_txt;
var date = new Date(datetxt);
// Extract the date components
var day = date.getDate();
var month = date.getMonth() + 1; // Month starts from 0, so add 1
var year = date.getFullYear();
// Extract the time components
var hours = date.getHours();
var minutes = date.getMinutes();
// Determine if it's AM or PM
var period = hours >= 12 ? 'PM' : 'AM';
// Adjust the hours to 12-hour format
hours = hours % 12;
hours = hours ? hours : 12; // Handle the case when hours is 0
// Format the date and time string
//var formattedDate = `${day}/${month}/${year}`;
//var formattedTime = `${hours}:${minutes.toString().padStart(2, '0')} ${period}`;
// Format the date and time strings
var formattedDate = `${day.toString().padStart(2, '0')}-${month.toString().padStart(2, '0')}-${year}`;
var formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')} ${period}`;
// Concatenate the formatted date and time
var formattedDateTime = `${formattedDate} ${formattedTime}`;
return formattedDateTime;
}
//Date format
function convertdate_2(date_txt){
var datetxt = date_txt;
var date = new Date(datetxt);
// Extract the date components
var day = date.getDate();
var month = date.getMonth() + 1; // Month starts from 0, so add 1
var year = date.getFullYear();
// Format the date and time strings
var formattedDate = `${day.toString().padStart(2, '0')}-${month.toString().padStart(2, '0')}-${year}`;
// Concatenate the formatted date and time
var formattedDateTime = `${formattedDate}`;
return formattedDateTime;
}
function date_difference(fromdate,todate,type='datetime'){
// Parse the date strings into moment objects with the specified format
var startDate = moment(fromdate, 'DD-MM-YYYY hh:mm A');
var endDate = moment(todate, 'DD-MM-YYYY hh:mm A');
// Calculate the difference in days
var daysDifference = endDate.diff(startDate, 'days');
// Calculate the remaining time components (hours, minutes)
var duration = moment.duration(endDate - startDate);
var hoursDifference = duration.hours();
var minutesDifference = duration.minutes();
var date_diff_txt ="";
var day_txt = "day";
var hour_txt = "hour";
var days_txt ="";
if(daysDifference>1){
day_txt = "days";
function call_loading(div, action) {
var divID = "#" + div;
var loadingimage = `<center><img src="images/loading.svg" style="opacity: 1; visibility: visible; height:40px;"></center>`;
if (action == 'start') {
$(divID).html(loadingimage)
}
} }
if(hoursDifference>1){
hour_txt = "hours";
// Date format
function convertdate(date_txt) {
var datetxt = date_txt;
var date = new Date(datetxt);
// Extract the date components
var day = date.getDate();
var month = date.getMonth() + 1; // Month starts from 0, so add 1
var year = date.getFullYear();
// Extract the time components
var hours = date.getHours();
var minutes = date.getMinutes();
// Determine if it's AM or PM
var period = hours >= 12 ? 'PM' : 'AM';
// Adjust the hours to 12-hour format
hours = hours % 12;
hours = hours ? hours : 12; // Handle the case when hours is 0
// Format the date and time string
//var formattedDate = `${day}/${month}/${year}`;
//var formattedTime = `${hours}:${minutes.toString().padStart(2, '0')} ${period}`;
// Format the date and time strings
var formattedDate = `${day.toString().padStart(2, '0')}-${month.toString().padStart(2, '0')}-${year}`;
var formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')} ${period}`;
// Concatenate the formatted date and time
var formattedDateTime = `${formattedDate} ${formattedTime}`;
return formattedDateTime;
} }
// Display the result
//1 day, 1 hour and 34 minutes.
if(type=='days'){
date_diff_txt = daysDifference + ' '+day_txt;
}else if(type=='time'){
date_diff_txt = hoursDifference + ' '+ hour_txt +' and ' + minutesDifference + ' minutes';
//Date format
function convertdate_2(date_txt) {
var datetxt = date_txt;
var date = new Date(datetxt);
// Extract the date components
var day = date.getDate();
var month = date.getMonth() + 1; // Month starts from 0, so add 1
var year = date.getFullYear();
// Format the date and time strings
var formattedDate = `${day.toString().padStart(2, '0')}-${month.toString().padStart(2, '0')}-${year}`;
// Concatenate the formatted date and time
var formattedDateTime = `${formattedDate}`;
return formattedDateTime;
} }
else{
if(daysDifference>0){
days_txt = daysDifference + ' '+day_txt+', ';
function date_difference(fromdate, todate, type = 'datetime') {
// Parse the date strings into moment objects with the specified format
var startDate = moment(fromdate, 'DD-MM-YYYY hh:mm A');
var endDate = moment(todate, 'DD-MM-YYYY hh:mm A');
// Calculate the difference in days
var daysDifference = endDate.diff(startDate, 'days');
// Calculate the remaining time components (hours, minutes)
var duration = moment.duration(endDate - startDate);
var hoursDifference = duration.hours();
var minutesDifference = duration.minutes();
var date_diff_txt = "";
var day_txt = "day";
var hour_txt = "hour";
var days_txt = "";
if (daysDifference > 1) {
day_txt = "days";
}
if (hoursDifference > 1) {
hour_txt = "hours";
} }
date_diff_txt = days_txt + hoursDifference + ' '+ hour_txt +' and ' + minutesDifference + ' minutes';
// Display the result
//1 day, 1 hour and 34 minutes.
if (type == 'days') {
date_diff_txt = daysDifference + ' ' + day_txt;
} else if (type == 'time') {
date_diff_txt = hoursDifference + ' ' + hour_txt + ' and ' + minutesDifference + ' minutes';
}
else {
if (daysDifference > 0) {
days_txt = daysDifference + ' ' + day_txt + ', ';
}
date_diff_txt = days_txt + hoursDifference + ' ' + hour_txt + ' and ' + minutesDifference + ' minutes';
}
return date_diff_txt;
} }
return date_diff_txt;
}
function nodata(message="Data are not availble at this moment please check later"){
var nodata = `<center><img src="images/nodata_ani.gif" width="40%"><br><p class="text-warning">`+message+`</p></center>`;
return nodata;
}
function searchinfo(message="Data are not availble at this moment please check later"){
var nodata = `<center><img src="images/hi_robo.gif" width="20%"><br><p class="text-warning">`+message+`</p></center>`;
return nodata;
}
//Function to display random messages while waiting
function getLoadingMessage() {
var messages = [
"Please wait as we fetch the data. It will take less than 30 seconds.",
"Loading data... This won't take long.",
"Fetching information. Thank you for your patience.",
"Just a moment while we gather the data.",
"Loading... Sit tight!",
"Hold on tight! We're almost there.",
"Data is on its way. Thanks for waiting.",
"Patience is a virtue! We're working on it.",
"Just a few more seconds...",
"Almost done! Thanks for your patience.",
"We appreciate your patience. Data is coming shortly.",
"Stay tuned! Data is loading."
];
// Select a random message from the array
var randomMessage = messages[Math.floor(Math.random() * messages.length)];
// Display the random message
return randomMessage;
}
//To convert the file size from bytes
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
/* Check file Exits */
function checkFileExists(url) {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('File not found');
}
return true;
})
.catch(error => {
console.error('Error checking file existence:', error);
return false;
});
}
/* File Doanload script
* Send fileUrl - Full Path
* var fileUrl = "/gcc/files/m_petition/m_action_file/filename.jpg";
*/
function callDownload(fileUrl,fileName){
checkFileExists(fileUrl).then(exists => {
if (exists) {
//download file - fileUrl
// Create a temporary anchor element
var link = document.createElement("a");
link.href = fileUrl;
link.download = fileName; // Set the download attribute to the file name
link.click(); // Simulate a click on the anchor element to trigger the download
} else {
console.log('File does not exist');
}
});
}
/* encode a string to Base64 */
function encodeBase64(value) {
if (value && value.trim() !== '') {
// Encode the string to Base64
var encodedString = btoa(value);
return encodedString;
} else {
return '';
}
function nodata(message = "Data are not availble at this moment please check later") {
var nodata = `<center><img src="images/nodata_ani.gif" width="40%"><br><p class="text-warning">` + message + `</p></center>`;
return nodata;
} }
function passwordReset(){
var loginid = /*[[${LoginUserId}]]*/'';
if(loginid!="" && loginid>0){
$("#passwordreset").modal({
backdrop: 'static',
keyboard: false
}); // Show Modal Box
$("#resetuserid").val(loginid);
$("#oldpassword").val('');
$("#password").val('');
$("#newpassword").val('');
function searchinfo(message = "Data are not availble at this moment please check later") {
var nodata = `<center><img src="images/hi_robo.gif" width="20%"><br><p class="text-warning">` + message + `</p></center>`;
return nodata;
}
//Function to display random messages while waiting
function getLoadingMessage() {
var messages = [
"Please wait as we fetch the data. It will take less than 30 seconds.",
"Loading data... This won't take long.",
"Fetching information. Thank you for your patience.",
"Just a moment while we gather the data.",
"Loading... Sit tight!",
"Hold on tight! We're almost there.",
"Data is on its way. Thanks for waiting.",
"Patience is a virtue! We're working on it.",
"Just a few more seconds...",
"Almost done! Thanks for your patience.",
"We appreciate your patience. Data is coming shortly.",
"Stay tuned! Data is loading."
];
// Select a random message from the array
var randomMessage = messages[Math.floor(Math.random() * messages.length)];
// Display the random message
return randomMessage;
}
//To convert the file size from bytes
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
/* Check file Exits */
function checkFileExists(url) {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('File not found');
}
return true;
})
.catch(error => {
console.error('Error checking file existence:', error);
return false;
});
}
/* File Doanload script
* Send fileUrl - Full Path
* var fileUrl = "/gcc/files/m_petition/m_action_file/filename.jpg";
*/
function callDownload(fileUrl, fileName) {
checkFileExists(fileUrl).then(exists => {
if (exists) {
//download file - fileUrl
// Create a temporary anchor element
var link = document.createElement("a");
link.href = fileUrl;
link.download = fileName; // Set the download attribute to the file name
link.click(); // Simulate a click on the anchor element to trigger the download
} else {
console.log('File does not exist');
}
});
}
/* encode a string to Base64 */
function encodeBase64(value) {
if (value && value.trim() !== '') {
// Encode the string to Base64
var encodedString = btoa(value);
return encodedString;
} else {
return '';
}
}
function passwordReset() {
var loginid = /*[[${LoginUserId}]]*/'';
if (loginid != "" && loginid > 0) {
$("#passwordreset").modal({
backdrop: 'static',
keyboard: false
}); // Show Modal Box
$("#resetuserid").val(loginid);
$("#oldpassword").val('');
$("#password").val('');
$("#newpassword").val('');
}
} }
}
function savePassword() {
var userid = $("#resetuserid").val();
var oldpassword = $("#oldpassword").val();
var password = $("#password").val();
var confirmpassword = $("#newpassword").val();
// Input validation
if (!userid || !oldpassword || !password || !confirmpassword) {
alert("All fields are required.");
return;
}
if (password !== confirmpassword) {
alert("New password and confirmation password do not match.");
return;
}
var formData = new FormData();
formData.append('userid', userid);
formData.append('oldpassword', oldpassword);
formData.append('newpassword', password);
// Send AJAX request to reset password
$.ajax({
url: '/election/api/resetPassword', // Update with the actual endpoint URL
type: 'POST',
data: formData,
contentType: false, // Required for FormData
processData: false, // Required for FormData
success: function(response) {
// Handle success response
if (response === 'success') {
//alert("Password reset successfully.");
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
title: "Success",
text: "Password reset successfully!",
icon: "success",
confirmButtonText: "OK"
}).then(function () {
// Optionally, redirect the user or reset the form
document.getElementById('logout-form').submit();
});
} else {
alert(response.message || "Failed to reset password.");
}
},
error: function(xhr, status, error) {
// Handle error response
var errorMessage = "An error occurred. Please try again later.";
if (xhr.responseJSON && xhr.responseJSON.message) {
errorMessage = xhr.responseJSON.message;
}
alert(errorMessage);
}
});
function savePassword() {
var userid = $("#resetuserid").val();
var oldpassword = $("#oldpassword").val();
var password = $("#password").val();
var confirmpassword = $("#newpassword").val();
// Input validation
if (!userid || !oldpassword || !password || !confirmpassword) {
alert("All fields are required.");
return;
}
if (password !== confirmpassword) {
alert("New password and confirmation password do not match.");
return;
}
var formData = new FormData();
formData.append('userid', userid);
formData.append('oldpassword', oldpassword);
formData.append('newpassword', password);
// Send AJAX request to reset password
$.ajax({
url: '/swm/api/resetPassword', // Update with the actual endpoint URL
type: 'POST',
data: formData,
contentType: false, // Required for FormData
processData: false, // Required for FormData
success: function (response) {
// Handle success response
if (response === 'success') {
//alert("Password reset successfully.");
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
title: "Success",
text: "Password reset successfully!",
icon: "success",
confirmButtonText: "OK"
}).then(function () {
// Optionally, redirect the user or reset the form
document.getElementById('logout-form').submit();
});
} else {
alert(response.message || "Failed to reset password.");
}
},
error: function (xhr, status, error) {
// Handle error response
var errorMessage = "An error occurred. Please try again later.";
if (xhr.responseJSON && xhr.responseJSON.message) {
errorMessage = xhr.responseJSON.message;
}
alert(errorMessage);
}
});
} }
</script> </script>
<!-- <!--

301
src/main/resources/templates/index.html

@ -1,47 +1,49 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" dir=""> <html lang="en" dir="">
<html xmlns:th="http://www.thymeleaf.org"> <html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head> <head th:replace="~{fragments/modules/base/head :: head}"></head>
<body>
<!--[if lt IE 8]>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]--> <![endif]-->
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<i class="ik ik-user bg-blue"></i>
<div class="d-inline">
<h5>User</h5>
<span>Details</span>
</div>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<i class="ik ik-user bg-blue"></i>
<div class="d-inline">
<h5>User</h5>
<span>Details</span>
</div> </div>
</div> </div>
<div class="col-lg-4">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="/election"><i class="ik ik-home"></i></a>
</li>
<li class="breadcrumb-item active" aria-current="page">Dashboard</li>
</ol>
</nav>
</div>
</div>
<div class="col-lg-4">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="/swm"><i class="ik ik-home"></i></a>
</li>
<li class="breadcrumb-item active" aria-current="page">Dashboard</li>
</ol>
</nav>
</div> </div>
</div> </div>
<!-- <div class="row">
</div>
<!-- <div class="row">
<div class="col-lg-3 col-md-6 col-sm-12"> <div class="col-lg-3 col-md-6 col-sm-12">
<div class="widget"> <div class="widget">
<div class="widget-header"> <div class="widget-header">
@ -91,127 +93,128 @@
</div> </div>
</div> </div>
</div> --> </div> -->
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3>User Profile</h3>
</div>
<div class="card-body">
<div class="col-sm-12" id="userProfile"></div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3>User Profile</h3>
</div>
<div class="card-body">
<div class="col-sm-12" id="userProfile"></div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div> </div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div> </div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script th:inline="javascript">
var loading_text_msg = getLoadingMessage(); // get Random loading message from base/script
var createdBy = /*[[${LoginUserId}]]*/'';
//alert(createdBy);
// Loading Div id
const loading = $("#userProfile");
function call_loading() {
loading.html(searchinfo("<b>" + loading_text_msg + "</b>"));
}
function remove_loading() {
loading.html("");
}
/* Get Complaints Data */
function get_user_basic_data() {
var apiUrl = '/swm/api/getUserProfileBasic?userId=' + createdBy;
//alert(apiUrl);
// Return a Promise
return new Promise(function (resolve, reject) {
$.ajax({
url: apiUrl,
type: 'GET',
/*dataType: 'json',*/
success: function (jsonResponse) {
// Resolve the Promise with the department list
resolve(jsonResponse);
},
error: function (xhr, status, error) {
// Reject the Promise with the error message
reject(error);
}
});
});
}
/* Get Complaints List */
function get_user_basic_info() {
get_user_basic_data().then(function (userProfile) {
// Handle the userProfile
$("#basicUserProfile").html(userProfile);
}).catch(function (error) {
// Handle errors
if (error && error.message) {
console.error('Error fetching User Profile:', error.message);
} else {
console.error('An error occurred while fetching user profile:', error);
}
});
}
/* Get Complaints Data */
function get_user_data() {
var apiUrl = '/swm/api/getUserProfile?userId=' + createdBy;
//alert(apiUrl);
// Return a Promise
return new Promise(function (resolve, reject) {
$.ajax({
url: apiUrl,
type: 'GET',
/*dataType: 'json',*/
success: function (jsonResponse) {
// Resolve the Promise with the department list
resolve(jsonResponse);
},
error: function (xhr, status, error) {
// Reject the Promise with the error message
reject(error);
}
});
});
}
/* Get Complaints List */
function get_user_info() {
get_user_data().then(function (userProfile) {
// Handle the userProfile
$("#userProfile").html(userProfile);
}).catch(function (error) {
// Handle errors
if (error && error.message) {
console.error('Error fetching User Profile:', error.message);
} else {
console.error('An error occurred while fetching user profile:', error);
}
});
}
$(document).ready(function () {
call_loading();
get_user_info();
get_user_basic_info();
});
</script>
</body>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script th:inline="javascript">
var loading_text_msg = getLoadingMessage(); // get Random loading message from base/script
var createdBy = /*[[${LoginUserId}]]*/'';
//alert(createdBy);
// Loading Div id
const loading = $("#userProfile");
function call_loading(){
loading.html(searchinfo("<b>"+loading_text_msg+"</b>"));
}
function remove_loading(){
loading.html("");
}
/* Get Complaints Data */
function get_user_basic_data(){
var apiUrl = '/election/api/getUserProfileBasic?userId='+createdBy;
//alert(apiUrl);
// Return a Promise
return new Promise(function(resolve, reject) {
$.ajax({
url: apiUrl,
type: 'GET',
/*dataType: 'json',*/
success: function(jsonResponse) {
// Resolve the Promise with the department list
resolve(jsonResponse);
},
error: function(xhr, status, error) {
// Reject the Promise with the error message
reject(error);
}
});
});
}
/* Get Complaints List */
function get_user_basic_info(){
get_user_basic_data().then(function(userProfile) {
// Handle the userProfile
$("#basicUserProfile").html(userProfile);
}).catch(function(error) {
// Handle errors
if (error && error.message) {
console.error('Error fetching User Profile:', error.message);
} else {
console.error('An error occurred while fetching user profile:', error);
}
});
}
/* Get Complaints Data */
function get_user_data(){
var apiUrl = '/election/api/getUserProfile?userId='+createdBy;
//alert(apiUrl);
// Return a Promise
return new Promise(function(resolve, reject) {
$.ajax({
url: apiUrl,
type: 'GET',
/*dataType: 'json',*/
success: function(jsonResponse) {
// Resolve the Promise with the department list
resolve(jsonResponse);
},
error: function(xhr, status, error) {
// Reject the Promise with the error message
reject(error);
}
});
});
}
/* Get Complaints List */
function get_user_info(){
get_user_data().then(function(userProfile) {
// Handle the userProfile
$("#userProfile").html(userProfile);
}).catch(function(error) {
// Handle errors
if (error && error.message) {
console.error('Error fetching User Profile:', error.message);
} else {
console.error('An error occurred while fetching user profile:', error);
}
});
}
$(document).ready(function() {
call_loading();
get_user_info();
get_user_basic_info();
});
</script>
</body>
</html>
</html>

236
src/main/resources/templates/login.html

@ -1,184 +1,70 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" dir=""> <html lang="en" dir="">
<html xmlns:th="http://www.thymeleaf.org"> <html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/login-head :: head}"></head>
<body style="background: url('images/login/Hall.jpg') no-repeat center center fixed;">
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div class="page-wrap">
<!-- Right vector image -->
<img src="images/login/Vector.png" class="vector-overlay">
<header class="election-header">
<div class="header-inner">
<div class="header-left">
<img src="images/login/logo.png" class="gcc-logo">
<div class="gcc-text">
GREATER <br> CHENNAI <br> CORPORATION
</div>
</div>
<div class="header-center">
Lok Sabha Elections 2026
</div>
<div class="header-right">
<img src="images/login/Election.png" class="election-logo">
</div>
</div>
</header>
<div class="hero">
<div class="left-col">
<!-- <div class="left-overlay"></div> -->
<div class="login-card">
<div class="text-center mb-3">
</div>
<h4 class="mb-3 text-center" style="letter-spacing:0.6px;color: white;font-weight: bold;">LOGIN</h4>
<!-- <div class="d-flex justify-content-center mb-3">
<div class="role-toggle">
<button id="roleAdmin" class="btn btn-outline-light active">Admin</button>
<button id="roleUser" class="btn btn-outline-light">User</button>
</div>
</div> -->
<div th:if="${param.error}" style="background: white;text-align: center;padding:4px;">
<p style="color: red;margin: 0px;">Invalid credentials...</p>
</div>
<form th:action="@{/election/login}" method="post">
<div class="mb-3">
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" required>
</div>
<div class="mb-3 input-eye">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>
<span class="eye" id="togglePwd"><i class="ik ik-eye-off"></i></i></span>
</div>
<!-- <div class="d-flex justify-content-between align-items-center mb-3">
<a href="#" style="color:rgba(255,255,255,0.8);text-decoration:underline">Reset password</a>
<div style="color:rgba(255,255,255,0.8);font-weight:600">&nbsp;</div>
</div> -->
<div class="mb-2 mt-4">
<button class="btn btn-login" id="btnLogin">Sign in</button>
</div>
</form>
</div>
</div>
<div class="right-col">
<div class="right-inner">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<div class="info-box">
<h5 style="margin-bottom:8px;font-weight: bold;">Information <small style="opacity:0.7;font-weight:400">Important</small></h5>
<p style="margin:0;color:rgba(255,255,255,0.8);font-size:12px">The birth and death certificates can be downloaded from this portal for the births
and deaths registered from 01.01.2018. Prior to 01.01.2018, respective local bodies may be approached for getting birth and death certificate.</p>
</div>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div class="news">
<h4 style="margin-top:18px;margin-bottom:8px">Latest News</h4>
<div class="news-list">
<div class="news-item">
<div>
<div class="title">The Hon'ble Chief Minister inaugurates public domain General
public can download birth / death certificates at free of cost</div>
<br>
<div class="meta">11 May 2024 </div>
</div>
</div>
<hr>
<div class="news-item">
<div>
<div class="title">New update about civil registration System rollout details and instructions</div>
<br>
<div class="meta">01 Mar 2024 </div>
</div>
</div>
<hr>
<div class="news-item">
<div>
<div class="title">Service improvements announced Important change in process and timings</div>
<br>
<div class="meta">10 Jan 2024</div>
</div>
</div>
<hr>
<div class="news-item">
<div>
<div class="title">Service improvements announced Important change in process and timings</div>
<br>
<div class="meta">10 Jan 2024</div>
</div>
</div>
<hr>
<div class="news-item">
<div>
<div class="title">Service improvements announced Important change in process and timings</div>
<br>
<div class="meta">10 Jan 2024</div>
</div>
</div>
<hr>
<div class="auth-wrapper">
<div class="container-fluid h-100">
<div class="row flex-row h-100 bg-white">
<div class="col-xl-8 col-lg-6 col-md-5 p-0 d-md-block d-lg-block d-sm-none d-none">
<div class="lavalite-bg" style="background-image: url('images/login-bg.jpg')">
<div class="lavalite-overlay"></div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-7 my-auto p-0">
<div class="authentication-form mx-auto text-center">
<div class="logo-centered">
<a href="/swm"><img src="images/logo.png" alt="Greater Chennai Corporation"
class="header-brand-img" width="100%"></a>
</div>
<h3>Greater Chennai Corporation</h3>
<p>Happy to see you again!</p>
<div th:if="${param.error}">
<p style="color: red;">Invalid credentials.</p>
</div>
<form th:action="@{/swm/login}" method="post">
<div class="form-group">
<input type="text" class="form-control" id="username" name="username"
placeholder="Username" required="" value="">
<i class="ik ik-user"></i>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password"
placeholder="Password" required="" value="">
<i class="ik ik-lock"></i>
</div>
<div class="row">
<div class="col text-left">
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="item_checkbox"
name="item_checkbox" value="option1">
<span class="custom-control-label">&nbsp;Remember Me</span>
</label>
</div>
<div class="col text-right">
<a href="#">Forgot Password ?</a>
</div>
</div>
<div class="sign-btn text-center">
<button class="btn btn-theme">Sign In</button>
</div>
</form>
<div class="register">
<p>Don't have an account? <a href="#">Create an account</a></p>
</div>
</div>
</div>
</div> </div>
<div style="margin-top:18px">
<a href="#" class="btn btn-sm btn-outline-light">Pre - Registration <span style="margin-left:8px">🔗</span></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="site-footer">
<div>Designed and Developed by EDP Cell, Greater Chennai Corporation / Cheif Registrar of Births and Deaths, Tamil Nadu</div>
<div>© Copyright 2025 Greater Chennai Corporation. All Rights Reserved.</div>
<div><span class="visitor">Visitor Count : <strong>2702035</strong></span></div>
</footer>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
// Toggle password visibility
$('#togglePwd').on('click', function () {
const inp = $('#password');
<script th:replace="~{fragments/modules/base/script :: script}"></script>
</body>
if (inp.attr('type') === 'password') {
inp.attr('type', 'text');
$(this).html('<i class="ik ik-eye"></i>');
} else {
inp.attr('type', 'password');
$(this).html('<i class="ik ik-eye-off"></i>');
}
});
</script>
</body>
</html>
</html>

529
src/main/resources/templates/modules/admin/user-group-access.html

@ -1,272 +1,279 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head> <head th:replace="~{fragments/modules/base/head :: head}"></head>
<body>
<!--[if lt IE 8]>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]--> <![endif]-->
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<i class="fa fa-id-badge bg-blue"></i>
<div class="d-inline">
<h5>User Group Access</h5>
<span>GCC Application Configuration</span>
</div>
</div>
</div>
<div class="col-lg-4">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="index"><i class="ik ik-home"></i></a>
</li>
<li class="breadcrumb-item" aria-current="page">Admin</li>
<li class="breadcrumb-item active" aria-current="page">User Group Access</li>
</ol>
</nav>
</div>
</div>
</div>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-12"></div>
<div class="input-group col-md-12 mb-0">
<label for="search_groupid" class="pt-2"> User Group: &nbsp;</label>
<select class="form-control select2" id="search_groupid" name="search_groupid">
<option value="">Please choose a User Group Name to retrieve data.</option>
<option th:each="userGroup: ${userGroupList}" th:value="${userGroup.id}" th:text="${userGroup.name}">-</option>
</select>
<span class="input-group-append">
<button type="button" id="groupSearchbtn" class="btn btn-success" onclick="showAccessTree();" data-toggle="tooltip" data-animation="true" data-placement="top" data-original-title="Search" title="">
<i class="ik ik-search me-1"></i> Search
</button>
</span>
</div>
</div>
</div>
<div class="card-body">
<div class="col-sm-12">
<div id="loadaccesstree"></div>
<!-- <div th:utext="${accessHTML}"></div> -->
</div>
</div>
<div class="card-footer">
<div class="col-sm-12 text-right">
<button type="reset" class="btn btn-secondary btn-sm" data-dismiss="modal" onclick="return closeModel();"><i class="ik ik-x-square"></i>Close</button>
<button type="submit" class="btn btn-success btn-sm" id="savebtn" onclick="return getCheckedData()"><i class="ik ik-save"></i>Save</button>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<i class="fa fa-id-badge bg-blue"></i>
<div class="d-inline">
<h5>User Group Access</h5>
<span>GCC Application Configuration</span>
</div>
</div>
</div>
<div class="col-lg-4">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="index"><i class="ik ik-home"></i></a>
</li>
<li class="breadcrumb-item" aria-current="page">Admin</li>
<li class="breadcrumb-item active" aria-current="page">User Group Access</li>
</ol>
</nav>
</div>
</div>
</div>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-12"></div>
<div class="input-group col-md-12 mb-0">
<label for="search_groupid" class="pt-2"> User Group: &nbsp;</label>
<select class="form-control select2" id="search_groupid"
name="search_groupid">
<option value="">Please choose a User Group Name to retrieve data.
</option>
<option th:each="userGroup: ${userGroupList}" th:value="${userGroup.id}"
th:text="${userGroup.name}">-</option>
</select>
<span class="input-group-append">
<button type="button" id="groupSearchbtn" class="btn btn-success"
onclick="showAccessTree();" data-toggle="tooltip"
data-animation="true" data-placement="top"
data-original-title="Search" title="">
<i class="ik ik-search me-1"></i> Search
</button>
</span>
</div> </div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script>
(function($){
$.fn.extend({
// Tree Check By Paranet (Check All)
checktree: function(){
$(this)
.addClass('checktree-root')
.on('change', 'input[type="checkbox"]', function(e){
e.stopPropagation();
e.preventDefault();
checkParents($(this));
checkChildren($(this));
})
;
var checkParents = function (c)
{
var parentLi = c.parents('ul:eq(0)').parents('li:eq(0)');
if (parentLi.length)
{
var siblingsChecked = parseInt($('input[type="checkbox"]:checked', c.parents('ul:eq(0)')).length),
rootCheckbox = parentLi.find('input[type="checkbox"]:eq(0)')
;
if (c.is(':checked'))
rootCheckbox.prop('checked', true)
else if (siblingsChecked === 0)
rootCheckbox.prop('checked', false);
checkParents(rootCheckbox);
}
}
var checkChildren = function (c)
{
var childLi = $('ul li input[type="checkbox"]', c.parents('li:eq(0)'));
if (childLi.length)
childLi.prop('checked', c.is(':checked'));
}
}
});
})(jQuery);
callMenuTreeAccess = function(groupId,groupName){
const loadaccesstree = $("#loadaccesstree");
const searchBtn = $("#groupSearchbtn");
const savebtn = $("#savebtn");
const apiUrl = "/election/api/getAccessTree?groupId="+groupId+"&groupName="+groupName;
$.ajax({
url: apiUrl,
type: 'GET',
dataType: 'text',
success: function(Response) {
// Handle the API response data here
//console.log('Data from API:', Response);
// Parse the JSON response into a JavaScript object
var data = Response;
if(data.ResultStatus=="False")
{
loadaccesstree.html("<center>"+nodata(data.Message)+"</center>");
searchBtn.prop("disabled", false);
searchBtn.html('<i class="ik ik-search me-1"></i> Search');
}
else{
loadaccesstree.html(data);
$('#tree').checktree();
// Enable the button
searchBtn.prop("disabled", false);
searchBtn.html('<i class="ik ik-search me-1"></i> Search');
savebtn.prop("disabled", false);
</div>
</div>
<div class="card-body">
<div class="col-sm-12">
<div id="loadaccesstree"></div>
<!-- <div th:utext="${accessHTML}"></div> -->
</div>
</div>
<div class="card-footer">
<div class="col-sm-12 text-right">
<button type="reset" class="btn btn-secondary btn-sm" data-dismiss="modal"
onclick="return closeModel();"><i class="ik ik-x-square"></i>Close</button>
<button type="submit" class="btn btn-success btn-sm" id="savebtn"
onclick="return getCheckedData()"><i class="ik ik-save"></i>Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script>
(function ($) {
$.fn.extend({
// Tree Check By Paranet (Check All)
checktree: function () {
$(this)
.addClass('checktree-root')
.on('change', 'input[type="checkbox"]', function (e) {
e.stopPropagation();
e.preventDefault();
checkParents($(this));
checkChildren($(this));
})
;
var checkParents = function (c) {
var parentLi = c.parents('ul:eq(0)').parents('li:eq(0)');
if (parentLi.length) {
var siblingsChecked = parseInt($('input[type="checkbox"]:checked', c.parents('ul:eq(0)')).length),
rootCheckbox = parentLi.find('input[type="checkbox"]:eq(0)')
;
if (c.is(':checked'))
rootCheckbox.prop('checked', true)
else if (siblingsChecked === 0)
rootCheckbox.prop('checked', false);
checkParents(rootCheckbox);
} }
},
error: function(xhr, status, error) {
// Handle errors here
console.error('Error fetching data:', xhr.status, error);
if (xhr.status == 404) {
// Handle 404 error specifically
loadaccesstree.html(nodata("<b>Unable to fetch data. Please try again later.<br>Error 404: Resource not found. Please check the URL.</b>"));
} else {
// Handle other errors
loadaccesstree.html(nodata("<b>Error: Unable to fetch data. Please try again later.</b>"));
}
// Enable the button
searchBtn.prop("disabled", false);
searchBtn.html('<i class="ik ik-search me-1"></i> Search');
}
});
}
// Load Access Tree
showAccessTree = function(){
const loadaccesstree = $("#loadaccesstree");
const selectedGroup = $('#search_groupid');
const selectedGroupId = selectedGroup.val();
const selectedGroupName = selectedGroup.find('option:selected').text();
const searchBtn = $("#groupSearchbtn");
const savebtn = $("#savebtn");
call_loading('loadaccesstree','start');
savebtn.prop("disabled", true); // Stop Save button
if(selectedGroupId>0){
// Disable the button to prevent multiple clicks
searchBtn.prop("disabled", true);
// Show the loading icon on the button
searchBtn.html('<i class="fas fa-spinner fa-spin"></i>');
callMenuTreeAccess(selectedGroupId,selectedGroupName);
}
var checkChildren = function (c) {
var childLi = $('ul li input[type="checkbox"]', c.parents('li:eq(0)'));
if (childLi.length)
childLi.prop('checked', c.is(':checked'));
}
} }
else{
loadaccesstree.html(searchinfo("<b>Please select and search for a User Group to continue.</b>"));
});
})(jQuery);
callMenuTreeAccess = function (groupId, groupName) {
const loadaccesstree = $("#loadaccesstree");
const searchBtn = $("#groupSearchbtn");
const savebtn = $("#savebtn");
const apiUrl = "/swm/api/getAccessTree?groupId=" + groupId + "&groupName=" + groupName;
$.ajax({
url: apiUrl,
type: 'GET',
dataType: 'text',
success: function (Response) {
// Handle the API response data here
//console.log('Data from API:', Response);
// Parse the JSON response into a JavaScript object
var data = Response;
if (data.ResultStatus == "False") {
loadaccesstree.html("<center>" + nodata(data.Message) + "</center>");
searchBtn.prop("disabled", false);
searchBtn.html('<i class="ik ik-search me-1"></i> Search');
}
else {
loadaccesstree.html(data);
$('#tree').checktree();
// Enable the button
searchBtn.prop("disabled", false);
searchBtn.html('<i class="ik ik-search me-1"></i> Search');
savebtn.prop("disabled", false);
}
},
error: function (xhr, status, error) {
// Handle errors here
console.error('Error fetching data:', xhr.status, error);
if (xhr.status == 404) {
// Handle 404 error specifically
loadaccesstree.html(nodata("<b>Unable to fetch data. Please try again later.<br>Error 404: Resource not found. Please check the URL.</b>"));
} else {
// Handle other errors
loadaccesstree.html(nodata("<b>Error: Unable to fetch data. Please try again later.</b>"));
}
// Enable the button
searchBtn.prop("disabled", false);
searchBtn.html('<i class="ik ik-search me-1"></i> Search');
} }
});
}
// Load Access Tree
showAccessTree = function () {
const loadaccesstree = $("#loadaccesstree");
const selectedGroup = $('#search_groupid');
const selectedGroupId = selectedGroup.val();
const selectedGroupName = selectedGroup.find('option:selected').text();
const searchBtn = $("#groupSearchbtn");
const savebtn = $("#savebtn");
call_loading('loadaccesstree', 'start');
savebtn.prop("disabled", true); // Stop Save button
if (selectedGroupId > 0) {
// Disable the button to prevent multiple clicks
searchBtn.prop("disabled", true);
// Show the loading icon on the button
searchBtn.html('<i class="fas fa-spinner fa-spin"></i>');
callMenuTreeAccess(selectedGroupId, selectedGroupName);
} }
showAccessTree();
var getCheckedData = function() {
var checkedData = [];
$('input[type="checkbox"]:checked', "#tree").each(function() {
checkedData.push($(this).val());
});
// Push Group ID
const selectedGroup = $('#search_groupid');
const selectedGroupId = selectedGroup.val();;
console.log(checkedData);
submitCheckedData(checkedData,selectedGroupId);
return false;//checkedData;
};
var submitCheckedData = function(checkedData, groupId) {
// Perform your AJAX request here using checkedData
// Replace the URL and other options with your actual API endpoint and data
const apiUrl = "/election/api/saveGroupAccessData";
const selectedGroup = $('#search_groupid');
const selectedGroupName = selectedGroup.find('option:selected').text();
$.ajax({
url: apiUrl,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ checkedData: checkedData, groupId: groupId }),
success: function(response) {
// Handle the success response
console.log('API response:', response);
Swal.fire(
'User Group Access!',
'Access has been successfully mapped to the User Group (' + selectedGroupName + ')!',
'success'
).then(() => {
location.reload();
});
},
error: function(error) {
// Handle the error response
console.error('API error:', error);
}
});
};
</script>
</body>
else {
loadaccesstree.html(searchinfo("<b>Please select and search for a User Group to continue.</b>"));
}
}
showAccessTree();
var getCheckedData = function () {
var checkedData = [];
$('input[type="checkbox"]:checked', "#tree").each(function () {
checkedData.push($(this).val());
});
// Push Group ID
const selectedGroup = $('#search_groupid');
const selectedGroupId = selectedGroup.val();;
console.log(checkedData);
submitCheckedData(checkedData, selectedGroupId);
return false;//checkedData;
};
var submitCheckedData = function (checkedData, groupId) {
// Perform your AJAX request here using checkedData
// Replace the URL and other options with your actual API endpoint and data
const apiUrl = "/swm/api/saveGroupAccessData";
const selectedGroup = $('#search_groupid');
const selectedGroupName = selectedGroup.find('option:selected').text();
$.ajax({
url: apiUrl,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ checkedData: checkedData, groupId: groupId }),
success: function (response) {
// Handle the success response
console.log('API response:', response);
Swal.fire(
'User Group Access!',
'Access has been successfully mapped to the User Group (' + selectedGroupName + ')!',
'success'
).then(() => {
location.reload();
});
},
error: function (error) {
// Handle the error response
console.error('API error:', error);
}
});
};
</script>
</body>
</html> </html>

448
src/main/resources/templates/modules/admin/user-list.html

@ -1,226 +1,240 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head> <head th:replace="~{fragments/modules/base/head :: head}"></head>
<body>
<!--[if lt IE 8]>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]--> <![endif]-->
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header">
<div class="row align-items-end">
<div class="col-lg-6">
<div class="page-header-title">
<i class="fa fa-user bg-blue"></i>
<div class="d-inline">
<h5>User List</h5>
<span>GCC Application Configuration</span>
</div>
</div>
</div>
<div class="col-lg-6">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="/index"><i class="ik ik-home"></i></a>
</li>
<li class="breadcrumb-item">Admin</li>
<li class="breadcrumb-item active" aria-current="page">User List</li>
</ol>
</nav>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<div>
<table id="assetDatatable" class="table table-striped table-bordered table-hover dataTable" role="grid" width="100%">
<thead class="thead-dark">
<tr class="table-bordered">
<th class="text-center no-sort">S.No</th>
<th class="text-center">Name</th>
<th class="text-center">E-mail</th>
<th class="text-center">Mobile</th>
<th class="text-center">Username</th>
<th class="text-center">Role</th>
<th class="text-center">Access Group</th>
<th class="text-center" width="10%">Status</th>
<th class="text-center" width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr th:each="userlistData, i : ${userlist}" class="${userlist}">
<td th:utext="${i.count}">0</td>
<td th:utext="${userlistData.userid.name}"></td>
<td th:utext="${userlistData.userid.email}"></td>
<td th:utext="${userlistData.userid.phone}"></td>
<td th:text="${userlistData.username}"></td>
<td th:utext="${userlistData.roles}" class="text-center"></td>
<td th:text="${userlistData.usergroup_id.name}"></td>
<td style="text-transform: capitalize;" th:utext="${userlistData.isActive} ? 'Active' : 'Inactive'" th:class="${userlistData.isActive} ? 'text-center text-green' : 'text-center text-red'"></td>
<td class="text-center">
<a th:href="@{#}" th:onclick="return callUserDetails([[${userlistData.id}]]);" data-toggle="tooltip" data-animation="true" data-placement="top" title="View User Details" data-original-title="View User Details"><i class="ik ik-file-text text-green" style="font-size: 18px;"></i></a>
</td>
</tr>
</tbody>
<tfoot class="thead-dark">
<tr class="table-bordered">
<th class="text-center no-sort">S.No</th>
<th class="text-center">Name</th>
<th class="text-center">E-mail</th>
<th class="text-center">Mobile</th>
<th class="text-center">Username</th>
<th class="text-center">Role</th>
<th class="text-center">Access Group</th>
<th class="text-center" width="10%">Status</th>
<th class="text-center" width="10%">Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<div th:replace="~{fragments/modules/admin/modal-box :: div}"></div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script th:inline="javascript">
//var qrAssetFeedbackApiUrl = "[[${qrAssetFeedbackApiUrl}]]";
$(document).ready(function() {
var exportTitle = "GCC Application User List";
// DataTables buttons configuration
var buttons = [
{
extend: 'pageLength',
className: 'btn btn-warning'
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header">
<div class="row align-items-end">
<div class="col-lg-6">
<div class="page-header-title">
<i class="fa fa-user bg-blue"></i>
<div class="d-inline">
<h5>User List</h5>
<span>GCC Application Configuration</span>
</div>
</div>
</div>
<div class="col-lg-6">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="/index"><i class="ik ik-home"></i></a>
</li>
<li class="breadcrumb-item">Admin</li>
<li class="breadcrumb-item active" aria-current="page">User List</li>
</ol>
</nav>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<div>
<table id="assetDatatable"
class="table table-striped table-bordered table-hover dataTable" role="grid"
width="100%">
<thead class="thead-dark">
<tr class="table-bordered">
<th class="text-center no-sort">S.No</th>
<th class="text-center">Name</th>
<th class="text-center">E-mail</th>
<th class="text-center">Mobile</th>
<th class="text-center">Username</th>
<th class="text-center">Role</th>
<th class="text-center">Access Group</th>
<th class="text-center" width="10%">Status</th>
<th class="text-center" width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr th:each="userlistData, i : ${userlist}" class="${userlist}">
<td th:utext="${i.count}">0</td>
<td th:utext="${userlistData.userid.name}"></td>
<td th:utext="${userlistData.userid.email}"></td>
<td th:utext="${userlistData.userid.phone}"></td>
<td th:text="${userlistData.username}"></td>
<td th:utext="${userlistData.roles}" class="text-center"></td>
<td th:text="${userlistData.usergroup_id.name}"></td>
<td style="text-transform: capitalize;"
th:utext="${userlistData.isActive} ? 'Active' : 'Inactive'"
th:class="${userlistData.isActive} ? 'text-center text-green' : 'text-center text-red'">
</td>
<td class="text-center">
<a th:href="@{#}"
th:onclick="return callUserDetails([[${userlistData.id}]]);"
data-toggle="tooltip" data-animation="true"
data-placement="top" title="View User Details"
data-original-title="View User Details"><i
class="ik ik-file-text text-green"
style="font-size: 18px;"></i></a>
</td>
</tr>
</tbody>
<tfoot class="thead-dark">
<tr class="table-bordered">
<th class="text-center no-sort">S.No</th>
<th class="text-center">Name</th>
<th class="text-center">E-mail</th>
<th class="text-center">Mobile</th>
<th class="text-center">Username</th>
<th class="text-center">Role</th>
<th class="text-center">Access Group</th>
<th class="text-center" width="10%">Status</th>
<th class="text-center" width="10%">Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<div th:replace="~{fragments/modules/admin/modal-box :: div}"></div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script th:inline="javascript">
//var qrAssetFeedbackApiUrl = "[[${qrAssetFeedbackApiUrl}]]";
$(document).ready(function () {
var exportTitle = "GCC Application User List";
// DataTables buttons configuration
var buttons = [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
title: exportTitle
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
title: exportTitle
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
title: exportTitle
}
];
$('#assetDatatable').DataTable({
/* Disable initial sort */
aaSorting: [],
columnDefs: [
{ targets: 'no-sort', orderable: false }
],
dom: 'Bftip',
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', '500 rows', 'Show all']
],
scrollY: '50vh',
fixedColumns: {
left: 1,
right: 1
},
buttons: [buttons],
responsive: true,
searching: false,
select: false,
processing: false,
});
});
// For view user details
function callUserDetails(userid) {
$("#profilehtml").html(searchinfo("<b>Retrieving Information, Please Wait...<div id=\"loadingimg\"></div></b>"));
call_loading("loadingimg", "start");
$('#viewUserDetails').modal({
backdrop: 'static',
keyboard: false
})
$('#viewUserDetails').modal('show');
var userProfileHtml = "";
getUserDetails(userid).then(response => {
// Handle the success response
$("#profilehtml").html(response);
})
.catch(error => {
// Handle the error response
$("#profilehtml").html(error); s
});
}
function getUserDetails(userid) {
const apiUrl = "/swm/api/getUserProfile";
return new Promise((resolve, reject) => {
$.ajax({
url: apiUrl,
type: 'GET',
dataType: 'text',
data: { userId: userid },
success: function (response) {
// Handle the success response
resolve(response);
}, },
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
title: exportTitle
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
title: exportTitle
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
title: exportTitle
}
];
$('#assetDatatable').DataTable( {
/* Disable initial sort */
aaSorting: [],
columnDefs: [
{ targets: 'no-sort', orderable: false }
],
dom: 'Bftip',
lengthMenu: [
[ 50, 100, 200, 500, -1 ],
[ '50 rows', '100 rows', '200 rows','500 rows', 'Show all' ]
],
scrollY: '50vh',
fixedColumns: {
left: 1,
right: 1
},
buttons: [buttons],
responsive: true,
searching: false,
select: false,
processing: false,
} );
} );
// For view user details
function callUserDetails(userid){
$("#profilehtml").html(searchinfo("<b>Retrieving Information, Please Wait...<div id=\"loadingimg\"></div></b>"));
call_loading("loadingimg","start");
$('#viewUserDetails').modal({
backdrop: 'static',
keyboard: false
})
$('#viewUserDetails').modal('show');
var userProfileHtml = "";
getUserDetails(userid).then(response => {
// Handle the success response
$("#profilehtml").html(response);
})
.catch(error => {
// Handle the error response
$("#profilehtml").html(error);
});
}
function getUserDetails(userid){
const apiUrl = "/election/api/getUserProfile";
return new Promise((resolve, reject) => {
$.ajax({
url: apiUrl,
type: 'GET',
dataType: 'text',
data: { userId: userid},
success: function(response) {
// Handle the success response
resolve(response);
},
error: function(error) {
// Handle the error response
console.error('API error:', error);
reject(error);
}
});
error: function (error) {
// Handle the error response
console.error('API error:', error);
reject(error);
}
}); });
}
</script>
</body>
});
}
</script>
</body>
</html> </html>

209
src/main/resources/templates/modules/dataentry/batchbyid.html

@ -1,209 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
#batchDetailscard label{
/* font-size: medium; */
font-weight: bold;
}
#batchDetailscard span{
font-size: 12px;
}
.btncontainer button{
width: 50%;
}
</style>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header mb-2">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<!-- <i class="far fa-calendar-plus bg-blue"></i> -->
<div class="d-inline">
<h5>Batch Information</h5>
<span>View batch details </span>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row mt-2 mb-2" style="padding: 10px;border: 1px solid green;background-color: rgba(144, 238, 144, 0.4);">
<div class="col-md-4">
<p style="margin-bottom: 2px;font-size: medium;font-weight: bold;">Application <span id="c_completed_plus"></span> of <span id="c_noof_application"></span></p>
<p style="margin-bottom: 2px;font-size: 12px;"><span id="c_completed"></span>&nbsp;saved&nbsp;.&nbsp;<span id="c_pending"></span>&nbsp;remaining</p>
</div>
<div class="col-md-4">
</div>
<div class="col-md-4" style="text-align: right;font-weight: bold;font-size:x-large;">
<span id="cc_completed_plus"></span>/<span id="cc_noof_application"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card" id="batchDetailscard">
<div class="card-header">
<span style="font-weight: bold;">Batch Information</span>
</div>
<div class="card-body">
<div class="row mb-3" style="row-gap:15px;">
<div class="col-md-3 col-sm-12">
<label for="batch_id" >Batch ID&nbsp;:</label>
</div>
<div class="col-md-9 col-sm-12">
<span id="batch_id" th:text="${batchdetails.id}"></span>
</div>
<div class="col-md-3 col-sm-12">
<label for="receiving_date" >Receiving Date&nbsp;:</label>
</div>
<div class="col-md-9 col-sm-12">
<span th:text="${batchdetails.received_date}"></span>
</div>
<div class="col-md-3 col-sm-12">
<label for="batch_dept" >Department&nbsp;:</label>
</div>
<div class="col-md-9 col-sm-12">
<span th:text="${batchdetails.dept_name}"></span>
</div>
<div class="col-md-3 col-sm-12">
<label for="office_name" >Office Name&nbsp;:</label>
</div>
<div class="col-md-9 col-sm-12">
<span th:text="${batchdetails.office_name}"></span>
</div>
<div class="col-md-3 col-sm-12">
<label for="no_of_app" >No of Applications&nbsp;:</label>
</div>
<div class="col-md-9 col-sm-12">
<span th:text="${batchdetails.noof_application}"></span>
</div>
</div>
<div class="row mt-4 btncontainer">
<div class="col-12 d-flex justify-content-center">
<button class="btn btn-secondary" onclick="goback()" >Back</button>
<button class="btn btn-primary mx-2"
th:onclick="'gotoNewEntry('
+ ${batchdetails.id} + ','
+ ${batchdetails.dept_id} + ','
+ ${batchdetails.office_id} + ')'">
Add New Entry
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
$(document).ready(function() {
let batch_id=document.getElementById("batch_id").textContent;
getstatuscounts(batch_id);
});
function getstatuscounts(batchId){
$('#pageLoader').show();
fetch('/election/api/dataentry/batch/getbatchbyId?id=' + batchId)
.then(response => response.json())
.then(result => {
if (result.status !== "success") {
console.error("API error:", result.message);
return;
}
let data = result.data;
console.log("Details:", data);
// Example: set values into input fields
document.getElementById("c_noof_application").textContent = data.noof_application;
document.getElementById("cc_noof_application").textContent = data.noof_application;
document.getElementById("c_completed").textContent = data.completed;
document.getElementById("c_pending").textContent = data.pending;
let completedCount = parseInt(data.completed) || 0;
let completedPlusOne = completedCount + 1;
document.getElementById("c_completed_plus").textContent = completedPlusOne;
document.getElementById("cc_completed_plus").textContent = completedPlusOne;
})
.catch(error => {
console.error("Error fetching batch counts details:", error);
})
.finally(() => {
$('#pageLoader').hide(); // ALWAYS hide loader
});
}
function gotoNewEntry(batchId, deptId, officeId) {
sessionStorage.setItem("batchId", batchId);
sessionStorage.setItem("deptId", deptId);
sessionStorage.setItem("officeId", officeId);
window.location.href = "/election/dataentry/newentry";
}
function goback(){
window.location.href="/election/dataentry/batches";
}
</script>
</body>
</html>

322
src/main/resources/templates/modules/dataentry/batches.html

@ -1,322 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header mb-2">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<!-- <i class="far fa-calendar-plus bg-blue"></i> -->
<div class="d-inline">
<h5>Batches</h5>
<span>View and manage application batches</span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<span style="font-weight: bold;">Batches List</span>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="batchDatatable"
class="table table-striped table-bordered table-hover dataTable"
role="grid">
<thead class="thead-dark">
<tr role="row">
<th class="text-center">S.No</th>
<th class="text-center">Batch ID</th>
<th class="text-center">Receiving Date</th>
<th class="text-center">Department</th>
<th class="text-center">Office Name</th>
<th class="text-center">Applications</th>
<th class="text-center">Completed</th>
<th class="text-center">Pending</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#batchDatatable').DataTable({
dom: 'Bftip',
columnDefs: [
{ targets: 'no-sort', orderable: false }
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: '50vh',
scrollX: true,
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn'
}
],
fixedHeader: true,
autoWidth: true,
responsive: false,
searching: true,
select: false,
processing: false
});
getbatchdetails();
});
function getbatchdetails(){
$('#pageLoader').show();
$.ajax({
type: "GET",
url: `/election/api/dataentry/batch/getBatchDetails`, // Append query string to URL
contentType: "application/json",
success: function (response) {
console.log("API Response:", response);
$('#pageLoader').hide();
if (response.status === "success") {
//console.log("Details Array:", response.data);
// Ensure details is an array and has at least one entry
if (Array.isArray(response.data) && response.data) {
let table = $('#batchDatatable').DataTable({
destroy: true,
searching: true,
autoWidth: true,
paging: true,
info: true,
data: response.data,
columns: [
{
data: null,
render: (data, type, row, meta) => meta.row + 1,
className: 'text-center'
},
{ data: 'id', defaultContent: '-', className: 'text-center' },
{ data: 'rec_date', defaultContent: '-', className: 'text-center' },
{ data: 'dept_name', defaultContent: '-', className: 'text-center' },
{ data: 'office_name', defaultContent: '-', className: 'text-center' },
{ data: 'noof_application', defaultContent: '-', className: 'text-center' },
{ data: 'completed', defaultContent: '-', className: 'text-center' },
{ data: 'pending', defaultContent: '-', className: 'text-center' },
{
data: 'id',
className: 'text-center',
render: function (data, type, row) {
return `
<button class="btn btn-primary btn-sm"
onclick="gotodetailspage('${row.id}', '${row.pending}')">
New Entry
</button>
`;
}
}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn',
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
filename: function () {
return 'batch_details_' + getTimestamp();
}
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
filename: function () {
return 'batch_details_' + getTimestamp();
}
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
filename: function () {
return 'batch_details_' + getTimestamp();
}
}
],
columnDefs: [
{ targets: 'no-sort', orderable: false }
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: '80vh',
scrollX: true,
responsive: false,
searching: true
});
}
else{
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text:'Something went wrong!'
});
}
}
else if (response.status === "error") {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
else {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
},
error: function (error) {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
});
}
function gotodetailspage(batchid, pending) {
if (Number(pending) === 0) {
Swal.fire({
title: "No Pending Entries",
text: "All entries are completed for this batch.",
icon: "warning"
});
return; // stop redirect
}
// else proceed
window.location.href = '/election/dataentry/batchbyid?batchid=' + batchid;
}
function getTimestamp() {
const now = new Date();
const yyyy = now.getFullYear();
const mm = String(now.getMonth() + 1).padStart(2, '0');
const dd = String(now.getDate()).padStart(2, '0');
const hh = String(now.getHours()).padStart(2, '0');
const mi = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
return `${yyyy}${mm}${dd}_${hh}${mi}${ss}`;
}
</script>
</body>
</html>

43
src/main/resources/templates/modules/dataentry/dashboard.html

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
</script>
</body>
</html>

1025
src/main/resources/templates/modules/dataentry/newentry.html
File diff suppressed because it is too large
View File

43
src/main/resources/templates/modules/dataentry/notices.html

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
</script>
</body>
</html>

1191
src/main/resources/templates/modules/dataentry/updateform.html
File diff suppressed because it is too large
View File

582
src/main/resources/templates/modules/dataentry/updation.html

@ -1,582 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
.width1{
width: 120px;
}
.width2{
width: 150px;
}
</style>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header mb-2">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<!-- <i class="far fa-calendar-plus bg-blue"></i> -->
<div class="d-inline">
<h5>Updation</h5>
<span>View and manage application batches </span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<span>Fill in the details </span>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-3 col-sm-12">
<label class="form-label" for="unique_num">Unique Number</label>
<input type="text" class="form-control" id="unique_num">
</div>
<div class="col-md-1 col-sm-12 text-center pt-4">
<span style="font-weight: bold;">OR</span>
</div>
<div class="col-md-3 col-sm-12">
<label class="form-label" for="batch_num">Batch No</label>
<input type="text" class="form-control" id="batch_num">
</div>
<div class="col-md-1 col-sm-12 text-center pt-4">
<span style="font-weight: bold;">OR</span>
</div>
<div class="col-md-3 col-sm-12">
<label class="form-label" for="mobile_num">Mobile Number</label>
<input type="text" class="form-control" id="mobile_num">
</div>
</div>
<div class="row mt-3">
<div class="col-12 d-flex justify-content-center">
<button type="submit" id="searchBtn"
class="btn btn-primary mx-2">Search</button>
<button class="btn btn-danger mx-2" id="resetBtn"
name="reset">Reset</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row" id="detailscard">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="DetailsDatatable"
class="table table-striped table-bordered table-hover dataTable"
role="grid">
<thead class="thead-dark">
<tr role="row">
<th class="text-center">S.No</th>
<th class="text-center">Unique No/Batch No</th>
<th class="text-center width1">Name / Pay Scale / Cur.Basic / Grade Pay</th>
<th class="text-center">Sex</th>
<th class="text-center">Designation</th>
<th class="text-center">State / Central</th>
<th class="text-center width2">Office Address</th>
<th class="text-center">Mobile Number</th>
<th class="text-center">Residential Address</th>
<th class="text-center">Native Constituency</th>
<th class="text-center">Residential Constituency</th>
<th class="text-center">Working Constituency</th>
<th class="text-center">Enrolled - Part / Sl.No / EPIC / Assembly Constituency</th>
<th class="text-center">Photo</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
$(document).ready(function() {
// MOBILE NO: exactly 10 digits
$('#mobile_num').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
// Max 10 digits
if (this.value.length > 10) {
this.value = this.value.slice(0, 10);
}
});
$('#unique_num').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
});
$('#batch_num').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
});
var table = $('#DetailsDatatable').DataTable({
dom: 'Bftip',
columnDefs: [
{ width: "150px", targets: 2 }, // Name / Pay Scale column
{ width: "150px", targets: 6 }, // Office Address column
{ width: "150px", targets: 8 },
{ width: "150px", targets: 12 }
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: '50vh',
scrollX: true,
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn'
}
],
fixedHeader: true,
autoWidth: true,
responsive: false,
searching: true,
select: false,
processing: false
});
});
document.getElementById('resetBtn').addEventListener('click', function (e) {
location.reload();
});
document.getElementById('searchBtn').addEventListener('click', function (e) {
$('#pageLoader').show();
let unique_num = document.getElementById('unique_num').value;
let mobile_num = document.getElementById('mobile_num').value;
let batch_num = document.getElementById('batch_num').value;
console.log(unique_num,",",mobile_num,",",batch_num);
if(!unique_num && !mobile_num && !batch_num){
$('#pageLoader').hide();
Swal.fire({
icon: 'warning',
title: 'For Search, Any One Is Required ',
text: 'Please Enter required details',
showConfirmButton: true,
timer: 3000
});
e.preventDefault();
return;
}
if(mobile_num){
// Rule 1: Must be exactly 10 digits & must not start with 0
if (!/^[1-9][0-9]{9}$/.test(mobile_num)) {
$('#pageLoader').hide();
Swal.fire({
icon: 'warning',
title: 'Invalid Mobile Number',
text: 'Mobile number must be 10 digits and cannot start with 0.'
});
return;
}
// Rule 2: Reject sequential numbers like 1234567890
if (mobile_num === "1234567890") {
$('#pageLoader').hide();
Swal.fire({
icon: 'warning',
title: 'Invalid Mobile Number',
text: 'Sequential numbers like 1234567890 are not allowed.'
});
return;
}
// Rule 3: Reject all digits same (1111111111, 2222222222, etc.)
if (/^(\d)\1{9}$/.test(mobile_num)) {
$('#pageLoader').hide();
Swal.fire({
icon: 'warning',
title: 'Invalid Mobile Number',
text: 'All digits cannot be the same.'
});
return;
}
}
$.ajax({
type: "GET",
url: `/election/api/dataentry/update/getbymobanduniq`,
data:{
mobilenum:mobile_num,
uniquenum:unique_num,
batch_num:batch_num
},
contentType: "application/json",
success: function (response) {
console.log("API Response:", response);
$('#pageLoader').hide();
if (response.status === "success") {
console.log("Details Array:", response.data);
// Convert object → array
let records = response.data || [];
console.log("Table Records:", records);
let table = $('#DetailsDatatable').DataTable({
destroy: true,
searching: true,
autoWidth: true,
paging: true,
info: true,
data: records,
columns: [
{
data: null,
render: (data, type, row, meta) => meta.row + 1,
className: 'text-center'
},
{ data: null,
className: 'text-center' ,
render: r => `${r.slno || '-'}<br>/ ${r.batch_no || '-'}`
},
{ data: null,
className: 'text-center width1' ,
render: r => `
${r.name || '-'}<br>
<small>
${r.pay_scale || '-'} /
${r.basic_pay || '-'} /
${r.grade_pay || '-'}
</small>`
},
{ data: 'sex',className: 'text-center' },
{ data: 'new_designation',className: 'text-center' },
{ data: 'govt_type',className: 'text-center' },
{ data: null,
className: 'text-center width2' ,
render: r => `${r.office_name || '-'}<br>/ <small>${r.office_address || '-'}</small>`
},
{ data: 'r_mobile_no' ,className: 'text-center' },
{ data: 'res_address', className: 'text-center' },
{ data: null,
className: 'text-center' ,
render: r => `${r.native_ac_no || '-'} - ${r.native_assembly || '-'}`
},
{ data: null,
className: 'text-center' ,
render: r => `${r.reside_ac_no || '-'} - ${r.res_assembly || '-'}`
},
{ data: null,
className: 'text-center' ,
render: r => `${r.work_ac_no || '-'} - ${r.work_assembly || '-'}`
},
{
data: null,
className: 'text-center',
render: r => `
Part: ${r.elector_part_no || '-'}<br>
Sl: ${r.elector_sl_no || '-'}<br>
${r.elector_epic_no || '-'}<br>${r.elector_ac_no || '-'}-
${r.enrolled_assembly || '-'}`
},
{
data: 'img_full_path',
className: 'text-center',
render: function (url, type, row) {
if (!url) {
return `<span style="color:red;">No Image</span>`;
}
return `
<img src="${url}"
style="height: 100px; width: 100px; object-fit: cover; border:1px solid #ccc;"
alt="Photo">
`;
}
},
{
data: null,
className: 'text-center',
render: function (data) {
let id = data.id;
let dept = data.dept;
let desigId = data.designation_id;
let officeId = data.office_id;
let batchId = data.batch_id;
return `
<button class="btn btn-primary btn-sm"
onclick="goToUpdateForm('${id}','${dept}','${desigId}','${officeId}','${batchId}')">
Update
</button>
`;
}
}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
filename: function () {
return 'polling_personnel_details_' + getTimestamp();
}
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
filename: function () {
return 'polling_personnel_details_' + getTimestamp();
}
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
title:'Polling Personnel Details',
filename: function () {
return 'polling_personnel_details_' + getTimestamp();
},
orientation: 'landscape', // ⭐ important line
pageSize: 'A4',
customize: function (doc) {
doc.pageOrientation = 'landscape';
// Reduce page margins to use full width
doc.pageMargins = [10, 10, 10, 10];
// Reduce default font size so columns fit
doc.defaultStyle.fontSize = 7;
doc.styles.tableHeader.fontSize = 8;
// ⭐ Force table to shrink inside page
doc.content[1].table.widths = [
20, // S.No
30, // Unique/Batch
60, // Name / Pay Scale
20, // Sex
60, // Designation
30, // State / Central
100, // Office Address
40, // Mobile
90, // Residence Address
60, // Native
60, // Reside
60, // Work
70, // Enrolled
50 // Photo
];
// ⭐ Remove large default paddings
var objLayout = {};
objLayout['hLineWidth'] = function(i) { return 0.3; };
objLayout['vLineWidth'] = function(i) { return 0.3; };
objLayout['hLineColor'] = function(i) { return '#000'; };
objLayout['vLineColor'] = function(i) { return '#000'; };
objLayout['paddingLeft'] = function(i) { return 2; };
objLayout['paddingRight'] = function(i) { return 2; };
objLayout['paddingTop'] = function(i) { return 2; };
objLayout['paddingBottom'] = function(i) { return 2; };
doc.content[1].layout = objLayout;
}
}
],
columnDefs: [
{ width: "150px", targets: 2},
{ width: "150px", targets: 6},
{ width: "120px", targets: 8},
{ width: "150px", targets: 12} ,
{ width: "150px", targets: 12}
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: '80vh',
scrollX: true,
responsive: false,
searching: true
});
}
else if (response.status === "no_data") {
$('#pageLoader').hide();
Swal.fire({
icon: 'info',
title: 'No Data',
text: response.data || 'Something went wrong!'
});
}
else if (response.status === "error") {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
else {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
},
error: function (error) {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
});
});
function getTimestamp() {
const now = new Date();
const yyyy = now.getFullYear();
const mm = String(now.getMonth() + 1).padStart(2, '0');
const dd = String(now.getDate()).padStart(2, '0');
const hh = String(now.getHours()).padStart(2, '0');
const mi = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
return `${yyyy}${mm}${dd}_${hh}${mi}${ss}`;
}
function goToUpdateForm(id, dept, designationId, officeId, batchId) {
// Save values in sessionStorage
sessionStorage.setItem("upd_id", id);
sessionStorage.setItem("upd_dept", dept);
sessionStorage.setItem("upd_office_id", officeId);
sessionStorage.setItem("upd_batch_id", batchId);
// Redirect to form page
window.location.href = "/election/dataentry/updateform";
}
</script>
</body>
</html>

875
src/main/resources/templates/modules/dataentry/verification.html

@ -1,875 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
</style>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header mb-2">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<!-- <i class="far fa-calendar-plus bg-blue"></i> -->
<div class="d-inline">
<h5 >Verification Checklist</h5>
<span>Review and verify applicant information</span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card" style="margin-top: 15px;">
<div class="card-body">
<input type="hidden" id="loginUserId" th:value="${loginUserId}">
<div class="form-group">
<div class="row" style="row-gap:10px;">
<div class="col-sm-12 col-md-3">
<label class="form-label" for="batchno">Batch No</label>
<input type="text" class="form-control" id="batchno" placeholder="Enter Batch No" required>
</div>
<!-- Start SLNO -->
<div class="col-sm-12 col-md-4">
<label class="form-label" for="serialno">
SLNO
</label>
<input type="text" class="form-control" id="startSerialno" placeholder="Enter From SLNO" required>
</div>
<!-- TO (Optional Text) -->
<div class="col-sm-12 col-md-1 text-center">
<label class="form-label d-block">&nbsp;</label>
<span class="fw-bold">To</span>
<small class="text-muted d-block">(Optional)</small>
</div>
<!-- End SLNO -->
<div class="col-sm-12 col-md-4">
<label class="form-label" for="serialno">&nbsp;</label>
<input type="text" class="form-control" id="endSerialno" placeholder="Enter To SLNO">
</div>
</div>
<br>
<div class="row" style="row-gap:10px;">
<div class="col-sm-12 col-md-4" >
<label class="form-label" for="mobilenumber">Mobile Number</label>
<input type="text" class="form-control" id="mobilenumber" placeholder="Enter Mobile Number" required>
</div>
<!-- Department -->
<div class="col-sm-12 col-md-4">
<label class="form-label" for="department">Department
</label>
<select class="form-control" id="department" required>
<option value=""> Select Department </option>
</select>
</div>
<!-- Office Name -->
<div class="col-sm-12 col-md-4">
<label class="form-label" for="officename">Office Name
</label>
<select class="form-control" id="officename" required>
<option value="">Select Office Name </option>
</select>
</div>
</div>
<br>
<div class="row" style="row-gap:10px;">
<!-- Left Side: Label + Radio Buttons -->
<div class="col-sm-12 col-md-8">
<label class="form-label d-block">Not Exist</label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="notExistOption" id="voterId" value="voterid">
<label class="form-check-label" for="voterId">EPIC Number</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="notExistOption" id="mobile" value="mobile">
<label class="form-check-label" for="mobile">Mobile Number</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="notExistOption" id="both" value="both">
<label class="form-check-label" for="both">Both</label>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary mx-2" id="searchBtn">Search</button>
<button type="reset" class="btn btn-danger mx-2" id="resetBtn">Reset</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- verification data table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3><b>Applicants for Checklist</b></h3>
</div>
<div class="card-body">
<table id="batchDatatable" class="table table-striped table-bordered table-hover dataTable" role="grid" >
<thead class="thead-dark" >
<tr role="row">
<th class="text-center">S.No</th>
<th class="text-center">Unique No / Batch No</th>
<th class="text-center">Name / Pay Scale / Cur.Basic /Grade Pay</th>
<th class="text-center">Sex</th>
<th class="text-center">Designation</th>
<th class="text-center">State /Central</th>
<th class="text-center">Office Address</th>
<th class="text-center">Mobile</th>
<th class="text-center">Residential Address</th>
<th class="text-center">Native Constituency</th>
<th class="text-center">Residential Constituency</th>
<th class="text-center">Working Constituency</th>
<th class="text-center">Enrolled - Part / Sl.No / EPIC /
Assembly Constituency</th>
<th class="text-center">Photo & Signature</th>
<!--<th class="text-center">Verification</th>-->
</tr>
</thead>
<tbody style="text-align:center;">
</tbody>
</table>
<div class="row mt-3">
<div class="col-12 d-flex justify-content-center">
<button id="printBtn" class="btn btn-primary mt-2">
<i class="fa fa-print"></i> Print
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
document.getElementById('resetBtn').addEventListener('click', function () {
event.preventDefault();
location.reload();
});
$(document).ready(function () {
// MOBILE NO: exactly 10 digits
$('#mobilenumber').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
// Max 10 digits
if (this.value.length > 10) {
this.value = this.value.slice(0, 10);
}
});
$('#startSerialno').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
});
$('#endSerialno').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
});
$('#batchno').on('input', function () {
// Allow only digits
this.value = this.value.replace(/\D/g, '');
});
var table = $('#batchDatatable').DataTable({
dom: 'Bftip',
// columnDefs: [
// { targets: 'no-sort', orderable: false }
columnDefs: [
{ width: "150px", targets: 1 }, // Name / Pay Scale column
{ width: "150px", targets: 2 }, // Office Address column
{ width: "250px", targets: 6 },
{width: "150px", targets: 12},
{width: "100px", targets: 7},
{width: "200px", targets: 8}
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: '80vh',
scrollX: true,
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn'
}
],
fixedHeader: true,
autoWidth: true,
responsive: false,
searching: true,
select: false,
processing: false
});
$.ajax({
url: "/election/api/dataentryadmin/getalldepartments",
method: "GET",
success: function (data) {
console.log("Departments data:", data);
let department = $("#department");
department.empty().append('<option value="">-- Select Department --</option>');
data.forEach(dept => {
department.append(`<option value="${dept.dept_id}">${dept.dept_name}</option>`);
});
}
});
// load office name
$("#department").on("change", function () {
let deptId = $(this).val();
console.log("dpetId",deptId)
$("#officename").empty().append('<option value="">-- Select Office Name --</option>');
if (deptId !== "") {
$.ajax({
url: "/election/api/dataentryadmin/getallofficenames",
method: "GET",
data: { deptId: deptId }, // <-- Correct parameter name
success: function (data) {
console.log("data",data)
data.forEach(o => {
$("#officename").append(
`<option value="${o.id}">${o.office_name}</option>`
);
});
}
});
}
});
$(document).ready(function () {
const initialParams = new URLSearchParams({
batchNo: "",
fromSLno: "",
toSLno: "",
mobileNo: "",
category: "",
officeName: "",
notExist: ""
});
loadApplicants(initialParams.toString());
});
function loadApplicants(paramString) {
$('#pageLoader').show();
$.ajax({
type: "GET",
url: `/election/api/checklistadmin/getApplicants?${paramString}`,
success: function (response) {
console.log("API Response:", response);
$('#pageLoader').hide();
if (response.message === "success" && Array.isArray(response.data)) {
$('#batchDatatable').DataTable({
destroy: true,
searching: true,
autoWidth: true,
paging: true,
info: true,
data: response.data,
columns: [
{ data: null, className: 'text-center', render: (d,t,r,m) => m.row + 1 },
{
data: null,
className: "text-center",
render: r => `${r.slno || '-'}<br>/ ${r.batch_no || '-'}`
},
{
data: null,
className: "text-center",
render: r => `
${r.name || '-'}<br>
<small>
${r.pay_scale || '-'} /
${r.basic_pay || '-'} /
${r.grade_pay || '-'}
</small>`
},
{ data: 'sex', className: 'text-center' },
{ data: 'new_designation', className: 'text-center' },
{ data: 'govt_type', className: 'text-center' },
{ data: 'address', className: 'text-center' },
{
data: null,
className: 'text-center',
render: r => `${r.r_mobile_no || ''}`
},
{
data: null,
className: 'text-center',
render: r => `${r.r_address1 || ''} ${r.r_address2 || ''} ${r.r_address3 || ''} - ${r.r_pincode || ''}`
},
{ data: null,
className: 'text-center',
render : r => `${r.native_ac_no || ''} - ${r.native_constituency || ''}`
},
{ data: null,
className: 'text-center',
render : r => `${r.reside_ac_no || ''} - ${r.residential_constituency || ''}`
},
{ data: null,
className: 'text-center',
render : r => `${r.work_ac_no || ''} - ${r.working_constituency || ''}`
},
{
data: null,
className: 'text-center',
render: r => `
Part: ${r.elector_part_no || '-'}<br>
Sl: ${r.elector_sl_no || '-'}<br>
${r.elector_epic_no || '-'}<br>${r.elector_ac_no || '-'}-
${r.elector_constituency || '-'}`
},
{ data: null, className: 'text-center', render: () => `<span class="badge bg-secondary">N/A</span>` },
/*{
data: 'poll_person_verify',
className: 'text-center',
render: function (flag, type, row) {
if (flag == 1) {
return `<span class="badge bg-success px-3 py-2"">Verified</span>`;
} else {
return `
<input type="checkbox"
class="verify-checkbox"
value="${row.id}">
`;
}
}
}*/
/*{
data: null,
className: 'text-center',
render: function (data, type, row) {
return `<button class="btn btn-warning btn-sm" onclick="verifyApplicant(${row.id})">
Verify
</button>`;
}
}*/
],
dom: 'Bfrtip',
buttons: [
{ extend: 'pageLength', className: 'btn btn-warning' },
{ extend: 'copyHtml5', className: 'btn btn-secondary' },
{ extend: 'excelHtml5', className: 'btn btn-secondary' },
{ extend: 'csvHtml5', className: 'btn btn-secondary' },
{ extend: 'pdfHtml5', className: 'btn btn-secondary' }
],
columnDefs: [
{ width: "150px", targets: 1 },
{ width: "150px", targets: 2 },
{ width: "250px", targets: 6 },
{width: "150px", targets: 12},
{width: "100px", targets: 7},
{width: "200px", targets: 8}
],
scrollY: '80vh',
scrollX: true,
responsive: false
});
} else {
Swal.fire("No Data", "No records found", "warning");
}
},
error: function (xhr) {
$('#pageLoader').hide();
console.log(" Server Error:", xhr.responseText);
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Server error! Check console.',
confirmButtonText: 'OK',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
}).then(() => {
location.reload(); // optional action
});
}
});
}
document.getElementById('searchBtn').addEventListener('click', function () {
let batchNo = document.getElementById('batchno').value || "";
let fromSLno = document.getElementById('startSerialno').value || "";
let toSLno = document.getElementById('endSerialno').value || "";
let mobileNo = document.getElementById('mobilenumber').value || "";
let category = document.getElementById('department').value || "";
let officeName = document.getElementById('officename').value || "";
let notExistRadio = document.querySelector('input[name="notExistOption"]:checked');
let notExist = notExistRadio ? notExistRadio.value : "";
if (
!batchNo &&
!fromSLno &&
!toSLno &&
!mobileNo &&
!category &&
!officeName &&
!notExist
) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please select at least one field to search.',
confirmButtonText: 'OK',
allowOutsideClick: false,
allowEscapeKey: false
});
return;
}
if (!fromSLno && toSLno) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please Enter SL No (From) to search.',
confirmButtonText: 'OK',
allowOutsideClick: false,
allowEscapeKey: false
});
return;
}
if(mobileNo){
// Rule 1: Must be exactly 10 digits & must not start with 0
if (!/^[1-9][0-9]{9}$/.test(mobileNo)) {
$('#pageLoader').hide();
$('#saveBtn').prop('disabled', false).text('Update');
Swal.fire({
icon: 'warning',
title: 'Invalid Mobile Number',
text: 'Mobile number must be 10 digits and cannot start with 0.'
});
return;
}
// Rule 2: Reject sequential numbers like 1234567890
if (mobileNo === "1234567890") {
$('#pageLoader').hide();
$('#saveBtn').prop('disabled', false).text('Update');
Swal.fire({
icon: 'warning',
title: 'Invalid Mobile Number',
text: 'Sequential numbers like 1234567890 are not allowed.'
});
return;
}
// Rule 3: Reject all digits same (1111111111, 2222222222, etc.)
if (/^(\d)\1{9}$/.test(mobileNo)) {
$('#pageLoader').hide();
$('#saveBtn').prop('disabled', false).text('Update');
Swal.fire({
icon: 'warning',
title: 'Invalid Mobile Number',
text: 'All digits cannot be the same.'
});
return;
}
}
const params = new URLSearchParams({
batchNo,
fromSLno,
toSLno,
mobileNo,
category,
officeName,
notExist
});
loadApplicants(params.toString());
});
});
/* $(document).on("change", ".verify-checkbox", function () {
let checkedCount = $(".verify-checkbox:checked").length;
if (checkedCount > 0) {
$("#verifySelectedBtn").show();
} else {
$("#verifySelectedBtn").hide();
}
});*/
/*$("#verifySelectedBtn").click(function () {
let selectedIds = [];
$(".verify-checkbox:checked").each(function () {
selectedIds.push($(this).val());
});
if (selectedIds.length === 0) {
Swal.fire("Warning", "Select at least one record", "warning");
return;
}
Swal.fire({
title: "Confirm Verification?",
text: `Verify ${selectedIds.length} applicant(s)?`,
icon: "question",
showCancelButton: true,
confirmButtonText: "Yes, Verify",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
}).then((result) => {
if (!result.isConfirmed) return;
$.ajax({
url: "/election/api/checklistadmin/verifyApplicants",
type: "POST",
traditional: true,
data: { id: selectedIds },
success: function (response) {
if (response === "success") {
Swal.fire({
icon: "success",
title: "Success",
text: "Applicants Verified Successfully",
confirmButtonText: "OK",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
}).then((result) => {
if (result.isConfirmed) {
location.reload(); // ✅ Reload ONLY after OK click
}
});
$("#verifySelectedBtn").hide();
}
},
error: function () {
Swal.fire({
icon: "error",
title: "Error",
text: "Verification Failed",
confirmButtonText: "OK",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
});
}
});
});
});*/
$(document).on("click", "#printBtn", function () {
let table = $('#batchDatatable').DataTable();
let rows = table.rows({ search: 'applied' }).nodes();
let thead = $(".dataTables_scrollHead thead").clone();
let printTable = `
<table border="1" style="width:100%; border-collapse:collapse; text-align:center; font-size:12px;">
${thead.prop("outerHTML")}
<tbody>
`;
rows.each(function (row) {
printTable += `<tr>${row.innerHTML}</tr>`;
});
printTable += `</tbody></table>`;
let printWindow = window.open("", "", "width=1200,height=800");
printWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Verification Checklist</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
<style>
@page {
size: landscape;
}
body {
padding: 20px;
font-family: Arial, sans-serif;
font-size: 14px;
}
h4 {
text-align: center;
margin-bottom: 20px;
font-size: 20px;
font-weight: bold;
}
th, td {
border: 1px solid #000;
padding: 8px;
text-align: center;
vertical-align: top;
white-space: normal;
word-wrap: break-word;
overflow-wrap: break-word;
font-size: 15px;
}
th:nth-child(7),
td:nth-child(7) {
width: 220px;
text-align: left;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
font-size: 13px;
}
input[type="checkbox"] {
display: none;
}
button {
display: none;
}
thead {
display: table-header-group;
}
</style>
</head>
<body>
<h4>Verification Checklist Report</h4>
${printTable}
<script>
window.onload = function () {
window.print();
window.close();
};
<\/script>
</body>
</html>
`);
printWindow.document.close();
});
</script>
</body>
</html>

43
src/main/resources/templates/modules/dataentry_admin/attendance.html

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
</script>
</body>
</html>

412
src/main/resources/templates/modules/dataentry_admin/batches.html

@ -1,412 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header mb-2">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<!-- <i class="far fa-calendar-plus bg-blue"></i> -->
<div class="d-inline">
<h5 >Create New Batch</h5>
<span>Create a new batch for application bundle intake</span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card" style="margin-top: 15px;">
<div class="col-lg-8" style="margin-top: 25px;">
<h3>Batch Information</h3>
<span>Fill in the details for the new application batch</span>
</div>
<div class="card-body">
<input type="hidden" id="loginUserId" th:value="${loginUserId}">
<div class="form-group">
<div class="row">
<div class="col-sm-12 col-md-6">
<label class="form-label" for="receivedate">Receiving Date<span
class="text-danger">*</span></label>
<input type="date" class="form-control" id="receivedate" onclick="this.showPicker()" required>
</div>
<!-- Department -->
<div class="col-sm-12 col-md-6">
<label class="form-label" for="department">Department
<span class="text-danger">*</span>
</label>
<select class="form-control" id="department" required>
<option value=""> Select Department </option>
</select>
</div>
<!-- Office Name -->
<div class="col-sm-12 col-md-6" style="margin-top: 15px;">
<label class="form-label" for="officename">Office Name
<span class="text-danger">*</span>
</label>
<select class="form-control" id="officename" required>
<option value="">Select Office Name </option>
</select>
</div>
<div class="col-sm-12 col-md-6" style="margin-top: 15px;">
<label class="form-label" for="noofapplication">Number of Applications<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="noofapplication" required>
</div>
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary " id="createdBtn">Create Batch</button>
<button type="reset" class="btn btn-secondary ml-2" id="resetBtn">Reset</button></div>
</div>
</div>
</div>
</div>
<!-- Batch List Table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3><b>All Batches</b></h3>
</div>
<div class="card-body">
<table id="batchDatatable" class="table table-striped table-bordered table-hover dataTable" role="grid" >
<thead class="thead-dark">
<tr role="row">
<th class="text-center">S.No</th>
<th class="text-center">Batch ID</th>
<th class="text-center">Receiving Date</th>
<th class="text-center">Department</th>
<th class="text-center">Office Name</th>
<th class="text-center">No Of Application</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody style="text-align:center;">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<div th:replace="~{fragments/modules/base/app_module_menu_box :: div}"></div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<!-- modal box -->
<div class="modal fade" id="editBatchModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Batch Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<input type="hidden" id="edit_batch_id">
<div class="col-md-6 mb-4">
<label class="form-label">Receive Date</label>
<input type="date" class="form-control" id="edit_receivedate" readonly>
</div>
<div class="col-md-6 mb-4">
<label class="form-label">Department</label>
<input type="text" class="form-control" id="edit_department" readonly>
</div>
<div class="col-md-12 mb-4">
<label class="form-label">Office Name</label>
<input type="text" class="form-control" id="edit_officename" readonly>
</div>
<div class="col-md-6">
<label class="form-label">Number of Applications <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="edit_noofapplication">
</div>
</div>
</div>
<div class="row mb-2 mt-2">
<div class="col-md-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary mx-2" onclick="updateBatch()">Update</button>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
// ✅ Reset Button
document.getElementById('resetBtn').addEventListener('click', function (e) {
e.preventDefault();
location.reload();
});
// ✅ Disable Future Dates
document.addEventListener("DOMContentLoaded", function () {
var today = new Date().toISOString().split('T')[0];
document.getElementById("receivedate").setAttribute("max", today);
});
$(document).ready(function () {
// ✅✅✅ SINGLE & CORRECT DataTable Initialization
var batchTable = $('#batchDatatable').DataTable({
dom: 'Bftip',
autoWidth: false,
responsive: false,
scrollX: true,
scrollY: '80vh',
scrollCollapse: true,
fixedHeader: true,
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
buttons: [
{ extend: 'pageLength', className: 'btn btn-warning' },
{ extend: 'copyHtml5', className: 'btn btn-secondary' },
{ extend: 'excelHtml5', className: 'btn btn-secondary' },
{ extend: 'csvHtml5', className: 'btn btn-secondary' },
{ extend: 'pdfHtml5', className: 'btn btn-secondary' }
],
ajax: {
url: "/election/api/dataentryadmin/getallbatches",
type: "GET",
dataSrc: ""
},
columns: [
{
data: null,
className: "text-center",
render: (d, t, r, m) => m.row + 1
},
{ data: "id", className: "text-center" },
{ data: "rec_date", className: "text-center" },
{ data: "dept_name", className: "text-center" },
{ data: "office_name", className: "text-center" },
{ data: "noof_application", className: "text-center" },
{
data: "id",
className: "text-center",
render: d => `<button class="btn btn-primary btn-sm" onclick="editBatch(${d})">Edit</button>`
}
],
columnDefs: [
{ targets: "_all", className: "text-center" }
]
});
// ✅ Load Departments
$.ajax({
url: "/election/api/dataentryadmin/getalldepartments",
method: "GET",
success: function (data) {
let department = $("#department");
department.empty().append('<option value="">-- Select Department --</option>');
data.forEach(dept => {
department.append(`<option value="${dept.dept_id}">${dept.dept_name}</option>`);
});
}
});
});
// ✅ Load Office Names Based on Department
$("#department").on("change", function () {
let deptId = $(this).val();
$("#officename").empty().append('<option value="">-- Select Office Name --</option>');
if (deptId !== "") {
$.ajax({
url: "/election/api/dataentryadmin/getallofficenames",
method: "GET",
data: { deptId: deptId },
success: function (data) {
data.forEach(o => {
$("#officename").append(`<option value="${o.id}">${o.office_name}</option>`);
});
}
});
}
});
// ✅ Create Batch
$("#createdBtn").click(function () {
let receivedate = $("#receivedate").val();
let department = $("#department").val();
let officename = $("#officename").val();
let noofapplication = $("#noofapplication").val();
let loginUserId = $("#loginUserId").val();
if (!receivedate || !department || !officename || !noofapplication || noofapplication <= 0) {
Swal.fire("Validation Error", "All fields are mandatory and must be valid.", "warning");
return;
}
$.ajax({
url: "/election/api/dataentryadmin/savebatchdeatils",
type: "POST",
data: {
receivedate,
department,
officename,
noofapplication,
userid: loginUserId
},
success: function (response) {
Swal.fire({
icon: "success",
title: "Batch Created Successfully!",
text: "Reference ID is: " + response
}).then(() => location.reload());
},
error: function (xhr) {
Swal.fire("Error", "Failed to save data: " + xhr.responseText, "error");
}
});
});
// ✅ Load Edit Modal
function editBatch(batchId) {
$.ajax({
url: "/election/api/dataentryadmin/getbatchbyId",
type: "GET",
data: { id: batchId },
success: function (data) {
$("#edit_batch_id").val(data.id);
$("#edit_receivedate").val(data.rec_date);
$("#edit_department").val(data.dept_name);
$("#edit_officename").val(data.office_name);
$("#edit_noofapplication").val(data.noof_application);
$("#editBatchModal").modal('show');
},
error: function () {
Swal.fire("Error!", "Unable to load batch details", "error");
}
});
}
// ✅ Update Batch
function updateBatch() {
let id = $("#edit_batch_id").val();
let noof_application = $("#edit_noofapplication").val();
let userId = $("#loginUserId").val();
if (!noof_application || noof_application <= 0) {
Swal.fire("Validation Error", "Enter a valid number of applications", "warning");
return;
}
$.ajax({
url: "/election/api/dataentryadmin/updatebatch",
type: "POST",
data: {
id,
noofapplication: noof_application,
userId
},
success: function () {
Swal.fire("Success", "Batch Updated Successfully", "success").then(() => {
$("#editBatchModal").modal("hide");
$('#batchDatatable').DataTable().ajax.reload(null, false);
});
},
error: function () {
Swal.fire("Error", "Failed to update batch", "error");
}
});
}
</script>
</body>
</html>

43
src/main/resources/templates/modules/dataentry_admin/dashboard.html

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
</script>
</body>
</html>

43
src/main/resources/templates/modules/dataentry_admin/others.html

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
</style>
</head>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script type="text/javascript">
</script>
</body>
</html>

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

Loading…
Cancel
Save