From 538a96515ac0f8af5a040ca5f88425896ad2f268 Mon Sep 17 00:00:00 2001 From: yoganandhan Date: Mon, 19 Jan 2026 11:58:10 +0530 Subject: [PATCH] first commit --- .vscode/settings.json | 3 + pom.xml | 9 +- .../controller/BatchApiController.java | 102 -- .../controller/ChecklistApiController.java | 34 - .../controller/Maincontroller.java | 69 - .../controller/TrainingApiController.java | 48 - .../admindataentry/service/BatchService.java | 137 -- .../service/ChecklistService.java | 139 -- .../service/TrainingService.java | 59 - .../configuration/DataSourceConfig.java | 94 - .../configuration/SecurityConfig.java | 89 - .../configuration/ThymeleafConfig.java | 31 - .../election/configuration/WebMvcConfig.java | 74 - .../election/controller/APIController.java | 470 ----- .../election/controller/AdminController.java | 148 -- .../election/controller/MainController.java | 37 - .../election/controller/MenuController.java | 167 -- .../controller/BatchAPIController.java | 260 --- .../dataentry/controller/Maincontroller.java | 108 -- .../controller/UpdationAPIController.java | 175 -- .../dataentry/service/BatchAPIService.java | 214 --- .../dataentry/service/UpdationService.java | 302 ---- .../election/interceptor/AppInterceptor.java | 321 ---- .../repository/AppModuleRepository.java | 30 - .../repository/SubMenuItemRepository.java | 34 - .../com/gcc/election/service/Base64Util.java | 37 - .../SwmApplication.java} | 6 +- .../configuration/AppConfig.java | 7 +- .../configuration/DataSourceConfig.java | 90 + .../configuration/JacksonConfiguration.java | 9 +- .../configuration/SecurityConfig.java | 93 + .../configuration/ThymeleafConfig.java | 33 + .../configuration/WebMvcConfig.java | 71 + .../controller/APIController.java | 491 ++++++ .../controller/AdminController.java | 157 ++ .../controller/CustomErrorController.java | 60 +- .../controller/DateTimeUtil.java | 23 +- .../controller/FileController.java | 30 +- .../controller/MainController.java | 36 + .../controller/MenuController.java | 184 ++ .../controller/login.java | 6 +- .../entity/AppModuleAccessEntity.java | 62 +- .../entity/AppModuleEntity.java | 80 +- .../entity/AppUserEntity.java | 87 +- .../entity/AppUserGroupEntity.java | 62 +- .../entity/MenuItemAccessEntity.java | 70 +- .../entity/MenuItemEntity.java | 96 +- .../entity/SubMenuItemAccessEntity.java | 79 +- .../entity/SubMenuItemEntity.java | 104 +- .../entity/UserActivityLog.java | 16 +- .../entity/UserInfoEntity.java | 41 +- .../interceptor/AppInterceptor.java | 331 ++++ .../modeldata/ErrorResponse.java | 28 +- .../repository/AppModuleAccessRepository.java | 28 +- .../repository/AppModuleRepository.java | 28 + .../repository/AppUserGroupRepository.java | 10 +- .../repository/AppUserRepository.java | 18 +- .../repository/MenuItemAccessRepository.java | 30 +- .../repository/MenuItemRepository.java | 20 +- .../SubMenuItemAccessRepository.java | 34 +- .../repository/SubMenuItemRepository.java | 33 + .../repository/UserActivityLogRepository.java | 6 +- .../repository/UserInfoRepository.java | 8 +- .../gcc/swm_services/service/Base64Util.java | 37 + .../service/CustomUserDetails.java | 19 +- .../service/CustomUserDetailsService.java | 81 +- .../service/LoginUserInfo.java | 188 +- .../service/UserActivityService.java | 8 +- .../service/UserActivityTimelineService.java | 11 +- .../swm/controller/AdminController.java | 163 ++ .../swm/controller/DropDownApiController.java | 35 + .../swm/controller/MainController.java | 70 + .../swm/controller/SwmAdminApiController.java | 118 ++ .../swm/controller/SwmApiController.java | 193 +++ .../swm/service/AddDetailsService.java | 362 ++++ .../swm/service/DropDownService.java | 37 + src/main/resources/application-dev.properties | 2 +- .../resources/application-prod.properties | 2 +- src/main/resources/application.properties | 4 +- .../fragments/modules/base/footer.html | 14 +- .../fragments/modules/base/head.html | 1541 +++++++++------- .../fragments/modules/base/header.html | 68 +- .../fragments/modules/base/login-head.html | 1543 ++++++++++------- .../fragments/modules/base/script.html | 644 +++---- src/main/resources/templates/index.html | 301 ++-- src/main/resources/templates/login.html | 236 +-- .../modules/admin/user-group-access.html | 529 +++--- .../templates/modules/admin/user-list.html | 448 ++--- .../modules/dataentry/batchbyid.html | 209 --- .../templates/modules/dataentry/batches.html | 322 ---- .../modules/dataentry/dashboard.html | 43 - .../templates/modules/dataentry/newentry.html | 1025 ----------- .../templates/modules/dataentry/notices.html | 43 - .../modules/dataentry/updateform.html | 1191 ------------- .../templates/modules/dataentry/updation.html | 582 ------- .../modules/dataentry/verification.html | 875 ---------- .../modules/dataentry_admin/attendance.html | 43 - .../modules/dataentry_admin/batches.html | 412 ----- .../modules/dataentry_admin/dashboard.html | 43 - .../modules/dataentry_admin/others.html | 43 - .../modules/dataentry_admin/training.html | 514 ------ .../modules/dataentry_admin/updation.html | 43 - .../modules/dataentry_admin/verification.html | 774 --------- .../templates/modules/swm/approvelist.html | 484 ++++++ .../templates/modules/swm/biocng.html | 810 +++++++++ .../templates/modules/swm/biogas.html | 816 +++++++++ .../templates/modules/swm/cdwaste.html | 431 +++++ .../templates/modules/swm/eachreport.html | 628 +++++++ .../templates/modules/swm/gwtcwaste.html | 505 ++++++ .../templates/modules/swm/incinerator.html | 484 ++++++ .../resources/templates/modules/swm/mcc.html | 484 ++++++ .../resources/templates/modules/swm/mrf.html | 481 +++++ .../templates/modules/swm/plastingbaling.html | 476 +++++ .../templates/modules/swm/reports.html | 597 +++++++ .../templates/modules/swm/requestlist.html | 396 +++++ .../templates/modules/swm/windrow.html | 475 +++++ .../election/ElectionApplicationTests.java | 13 - 117 files changed, 13131 insertions(+), 12523 deletions(-) create mode 100644 .vscode/settings.json delete mode 100644 src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java delete mode 100644 src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java delete mode 100644 src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java delete mode 100644 src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java delete mode 100644 src/main/java/com/gcc/election/admindataentry/service/BatchService.java delete mode 100644 src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java delete mode 100644 src/main/java/com/gcc/election/admindataentry/service/TrainingService.java delete mode 100644 src/main/java/com/gcc/election/configuration/DataSourceConfig.java delete mode 100644 src/main/java/com/gcc/election/configuration/SecurityConfig.java delete mode 100644 src/main/java/com/gcc/election/configuration/ThymeleafConfig.java delete mode 100644 src/main/java/com/gcc/election/configuration/WebMvcConfig.java delete mode 100644 src/main/java/com/gcc/election/controller/APIController.java delete mode 100644 src/main/java/com/gcc/election/controller/AdminController.java delete mode 100644 src/main/java/com/gcc/election/controller/MainController.java delete mode 100644 src/main/java/com/gcc/election/controller/MenuController.java delete mode 100644 src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java delete mode 100644 src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java delete mode 100644 src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java delete mode 100644 src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java delete mode 100644 src/main/java/com/gcc/election/dataentry/service/UpdationService.java delete mode 100644 src/main/java/com/gcc/election/interceptor/AppInterceptor.java delete mode 100644 src/main/java/com/gcc/election/repository/AppModuleRepository.java delete mode 100644 src/main/java/com/gcc/election/repository/SubMenuItemRepository.java delete mode 100644 src/main/java/com/gcc/election/service/Base64Util.java rename src/main/java/com/gcc/{election/ElectionApplication.java => swm_services/SwmApplication.java} (61%) rename src/main/java/com/gcc/{election => swm_services}/configuration/AppConfig.java (84%) create mode 100644 src/main/java/com/gcc/swm_services/configuration/DataSourceConfig.java rename src/main/java/com/gcc/{election => swm_services}/configuration/JacksonConfiguration.java (78%) create mode 100644 src/main/java/com/gcc/swm_services/configuration/SecurityConfig.java create mode 100644 src/main/java/com/gcc/swm_services/configuration/ThymeleafConfig.java create mode 100644 src/main/java/com/gcc/swm_services/configuration/WebMvcConfig.java create mode 100644 src/main/java/com/gcc/swm_services/controller/APIController.java create mode 100644 src/main/java/com/gcc/swm_services/controller/AdminController.java rename src/main/java/com/gcc/{election => swm_services}/controller/CustomErrorController.java (80%) rename src/main/java/com/gcc/{election => swm_services}/controller/DateTimeUtil.java (65%) rename src/main/java/com/gcc/{election => swm_services}/controller/FileController.java (71%) create mode 100644 src/main/java/com/gcc/swm_services/controller/MainController.java create mode 100644 src/main/java/com/gcc/swm_services/controller/MenuController.java rename src/main/java/com/gcc/{election => swm_services}/controller/login.java (74%) rename src/main/java/com/gcc/{election => swm_services}/entity/AppModuleAccessEntity.java (64%) rename src/main/java/com/gcc/{election => swm_services}/entity/AppModuleEntity.java (60%) rename src/main/java/com/gcc/{election => swm_services}/entity/AppUserEntity.java (63%) rename src/main/java/com/gcc/{election => swm_services}/entity/AppUserGroupEntity.java (61%) rename src/main/java/com/gcc/{election => swm_services}/entity/MenuItemAccessEntity.java (63%) rename src/main/java/com/gcc/{election => swm_services}/entity/MenuItemEntity.java (61%) rename src/main/java/com/gcc/{election => swm_services}/entity/SubMenuItemAccessEntity.java (64%) rename src/main/java/com/gcc/{election => swm_services}/entity/SubMenuItemEntity.java (61%) rename src/main/java/com/gcc/{election => swm_services}/entity/UserActivityLog.java (79%) rename src/main/java/com/gcc/{election => swm_services}/entity/UserInfoEntity.java (65%) create mode 100644 src/main/java/com/gcc/swm_services/interceptor/AppInterceptor.java rename src/main/java/com/gcc/{election => swm_services}/modeldata/ErrorResponse.java (60%) rename src/main/java/com/gcc/{election => swm_services}/repository/AppModuleAccessRepository.java (76%) create mode 100644 src/main/java/com/gcc/swm_services/repository/AppModuleRepository.java rename src/main/java/com/gcc/{election => swm_services}/repository/AppUserGroupRepository.java (63%) rename src/main/java/com/gcc/{election => swm_services}/repository/AppUserRepository.java (75%) rename src/main/java/com/gcc/{election => swm_services}/repository/MenuItemAccessRepository.java (72%) rename src/main/java/com/gcc/{election => swm_services}/repository/MenuItemRepository.java (52%) rename src/main/java/com/gcc/{election => swm_services}/repository/SubMenuItemAccessRepository.java (66%) create mode 100644 src/main/java/com/gcc/swm_services/repository/SubMenuItemRepository.java rename src/main/java/com/gcc/{election => swm_services}/repository/UserActivityLogRepository.java (80%) rename src/main/java/com/gcc/{election => swm_services}/repository/UserInfoRepository.java (69%) create mode 100644 src/main/java/com/gcc/swm_services/service/Base64Util.java rename src/main/java/com/gcc/{election => swm_services}/service/CustomUserDetails.java (79%) rename src/main/java/com/gcc/{election => swm_services}/service/CustomUserDetailsService.java (54%) rename src/main/java/com/gcc/{election => swm_services}/service/LoginUserInfo.java (58%) rename src/main/java/com/gcc/{election => swm_services}/service/UserActivityService.java (76%) rename src/main/java/com/gcc/{election => swm_services}/service/UserActivityTimelineService.java (70%) create mode 100644 src/main/java/com/gcc/swm_services/swm/controller/AdminController.java create mode 100644 src/main/java/com/gcc/swm_services/swm/controller/DropDownApiController.java create mode 100644 src/main/java/com/gcc/swm_services/swm/controller/MainController.java create mode 100644 src/main/java/com/gcc/swm_services/swm/controller/SwmAdminApiController.java create mode 100644 src/main/java/com/gcc/swm_services/swm/controller/SwmApiController.java create mode 100644 src/main/java/com/gcc/swm_services/swm/service/AddDetailsService.java create mode 100644 src/main/java/com/gcc/swm_services/swm/service/DropDownService.java delete mode 100644 src/main/resources/templates/modules/dataentry/batchbyid.html delete mode 100644 src/main/resources/templates/modules/dataentry/batches.html delete mode 100644 src/main/resources/templates/modules/dataentry/dashboard.html delete mode 100644 src/main/resources/templates/modules/dataentry/newentry.html delete mode 100644 src/main/resources/templates/modules/dataentry/notices.html delete mode 100644 src/main/resources/templates/modules/dataentry/updateform.html delete mode 100644 src/main/resources/templates/modules/dataentry/updation.html delete mode 100644 src/main/resources/templates/modules/dataentry/verification.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/attendance.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/batches.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/dashboard.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/others.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/training.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/updation.html delete mode 100644 src/main/resources/templates/modules/dataentry_admin/verification.html create mode 100644 src/main/resources/templates/modules/swm/approvelist.html create mode 100644 src/main/resources/templates/modules/swm/biocng.html create mode 100644 src/main/resources/templates/modules/swm/biogas.html create mode 100644 src/main/resources/templates/modules/swm/cdwaste.html create mode 100644 src/main/resources/templates/modules/swm/eachreport.html create mode 100644 src/main/resources/templates/modules/swm/gwtcwaste.html create mode 100644 src/main/resources/templates/modules/swm/incinerator.html create mode 100644 src/main/resources/templates/modules/swm/mcc.html create mode 100644 src/main/resources/templates/modules/swm/mrf.html create mode 100644 src/main/resources/templates/modules/swm/plastingbaling.html create mode 100644 src/main/resources/templates/modules/swm/reports.html create mode 100644 src/main/resources/templates/modules/swm/requestlist.html create mode 100644 src/main/resources/templates/modules/swm/windrow.html delete mode 100644 src/test/java/com/gcc/election/ElectionApplicationTests.java diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c5f3f6b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "interactive" +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 69f3143..6804ce2 100644 --- a/pom.xml +++ b/pom.xml @@ -10,9 +10,9 @@ com.gcc - election + rdo_login 0.0.1-SNAPSHOT - election + rdo_login Project for Allocating polling persons @@ -101,11 +101,6 @@ spring-boot-starter-test test - - in.gov.chennaicorporation - gccoffice - 0.0.1 - diff --git a/src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java b/src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java deleted file mode 100644 index 06c66dd..0000000 --- a/src/main/java/com/gcc/election/admindataentry/controller/BatchApiController.java +++ /dev/null @@ -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> getDepartments() { - - return batchService.getAllDepartment(); - } - - - @GetMapping("/getallofficenames") - public List> getofficebydept(@RequestParam int deptId) { - return batchService.getAllOfficenames(deptId); - } - - // save the batch creation details - - @PostMapping("/savebatchdeatils") - public ResponseEntity 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> getAllBatches() { - return batchService.getAllBatches(); - } - - - - -// modal box data - - - @GetMapping("/getbatchbyId") - public ResponseEntity getBatchById(@RequestParam int id) { - Map 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()); - } - } - - -} diff --git a/src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java b/src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java deleted file mode 100644 index b6cc466..0000000 --- a/src/main/java/com/gcc/election/admindataentry/controller/ChecklistApiController.java +++ /dev/null @@ -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 id) { - return checklistService.verifyApplicants(id); - } -} - - diff --git a/src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java b/src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java deleted file mode 100644 index e043929..0000000 --- a/src/main/java/com/gcc/election/admindataentry/controller/Maincontroller.java +++ /dev/null @@ -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"; - } - - -} diff --git a/src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java b/src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java deleted file mode 100644 index 7badb8c..0000000 --- a/src/main/java/com/gcc/election/admindataentry/controller/TrainingApiController.java +++ /dev/null @@ -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> getAllConstituency() { - return trainingService.getAllConstituency(); - } - - - @GetMapping("getAllCentre") - public List> getAllCentre() { - return trainingService.getAllCentre(); - } - - - @GetMapping("getAddressByCode") - public List> getAddressByCode(int code) { - return trainingService.getAddressByCode(code); - } - - - @GetMapping("getAllCategory") - public List> getAllCategory() { - return trainingService.getAllCategory(); - } - - - - -} diff --git a/src/main/java/com/gcc/election/admindataentry/service/BatchService.java b/src/main/java/com/gcc/election/admindataentry/service/BatchService.java deleted file mode 100644 index 9f90ab8..0000000 --- a/src/main/java/com/gcc/election/admindataentry/service/BatchService.java +++ /dev/null @@ -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> 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> 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> 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 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); - } - -} diff --git a/src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java b/src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java deleted file mode 100644 index aa6e4d6..0000000 --- a/src/main/java/com/gcc/election/admindataentry/service/ChecklistService.java +++ /dev/null @@ -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 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 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> 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 verifyApplicants(List 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"); - } - -} diff --git a/src/main/java/com/gcc/election/admindataentry/service/TrainingService.java b/src/main/java/com/gcc/election/admindataentry/service/TrainingService.java deleted file mode 100644 index 3acfdf0..0000000 --- a/src/main/java/com/gcc/election/admindataentry/service/TrainingService.java +++ /dev/null @@ -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> getAllConstituency() { - String sql = " SELECT * FROM ac_list_all where dist_no = '2' "; - System.out.println("sql"+sql); - return jdbcTemplate.queryForList(sql); - } - - - public List> getAllCentre() { - String sql = " SELECT c_code,c_name FROM trgcen "; - System.out.println("sql"+sql); - return jdbcTemplate.queryForList(sql); - } - - public List> 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> getAllCategory() { - String sql = " select distinct(category) from designation ORDER BY " + - " LENGTH(category)," + - " category; "; - System.out.println("sql"+sql); - return jdbcTemplate.queryForList(sql); - } - - - - - - - -} diff --git a/src/main/java/com/gcc/election/configuration/DataSourceConfig.java b/src/main/java/com/gcc/election/configuration/DataSourceConfig.java deleted file mode 100644 index 6695a3f..0000000 --- a/src/main/java/com/gcc/election/configuration/DataSourceConfig.java +++ /dev/null @@ -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; -} - - -} diff --git a/src/main/java/com/gcc/election/configuration/SecurityConfig.java b/src/main/java/com/gcc/election/configuration/SecurityConfig.java deleted file mode 100644 index 184c724..0000000 --- a/src/main/java/com/gcc/election/configuration/SecurityConfig.java +++ /dev/null @@ -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(); - } -} diff --git a/src/main/java/com/gcc/election/configuration/ThymeleafConfig.java b/src/main/java/com/gcc/election/configuration/ThymeleafConfig.java deleted file mode 100644 index 39f47f5..0000000 --- a/src/main/java/com/gcc/election/configuration/ThymeleafConfig.java +++ /dev/null @@ -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; -// } -// -//} diff --git a/src/main/java/com/gcc/election/configuration/WebMvcConfig.java b/src/main/java/com/gcc/election/configuration/WebMvcConfig.java deleted file mode 100644 index 1b08789..0000000 --- a/src/main/java/com/gcc/election/configuration/WebMvcConfig.java +++ /dev/null @@ -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 +"/"); - } -} diff --git a/src/main/java/com/gcc/election/controller/APIController.java b/src/main/java/com/gcc/election/controller/APIController.java deleted file mode 100644 index 159c9b8..0000000 --- a/src/main/java/com/gcc/election/controller/APIController.java +++ /dev/null @@ -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 getAppUserEntities; - - @Autowired - private HttpServletRequest request; - - @Autowired - private AppUserRepository appUserRepository; - - @Autowired - private LoginUserInfo loginUserInfo; - - List getActivityLogs; - @Autowired - private UserActivityLogRepository userActivityLogRepository; - - List getAppModuleAccessEntities; - List getMenuItemAccessEntities; - List getSubMenuItemAccessEntities; - - @Autowired - private AppModuleAccessRepository appModuleAccessRepository; - @Autowired - private MenuItemAccessRepository menuItemAccessRepository; - @Autowired - private SubMenuItemAccessRepository subMenuItemAccessRepository; - - List getAppModuleEntities; - List getMenuItemEntities; - List getSubMenuItemEntities; - - @Autowired - private AppModuleRepository appModuleRepository; - @Autowired - private MenuItemRepository menuItemRepository; - @Autowired - private SubMenuItemRepository subMenuItemRepository; - - @Autowired - public APIController( - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository, - UserActivityLogRepository userActivityLogRepository) { - - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - - this.appModuleAccessRepository = appModuleAccessRepository; - this.menuItemAccessRepository = menuItemAccessRepository; - this.subMenuItemAccessRepository = subMenuItemAccessRepository; - this.userActivityLogRepository = userActivityLogRepository; - - } - - // Encode to Base64 - @GetMapping(value="/encodeBase64") - public static String encodeBase64(@RequestParam String string) { - String value=string; - byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes()); - return new String(encodedBytes); - } - - // Decode from Base64 - @GetMapping(value="/decodeBase64") - public static String decodeBase64(@RequestParam String string) { - String encodedValue=string; - byte[] decodedBytes = Base64.getDecoder().decode(encodedValue); - return new String(decodedBytes); - } - - @GetMapping(value="/getAccessTree") - public String getAccessTreeHTML(@RequestParam String groupId,@RequestParam String groupName) { - - getAppModuleEntities = appModuleRepository.showAll(); - - String accessHTML = ""; - String accessTableHTML = ""; - //String MenuHTML = ""; - String isSelected = ""; - //String subMenuHTML = ""; - - String groupNameHTML = ""+groupName+""; - for (AppModuleEntity moduleName : getAppModuleEntities) { - - // ID to check - Integer desiredId = moduleName.getId(); - - // Check if the ID exists in the list of entities - getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId,desiredId.toString()); - // Check Module Id Access - if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; } - - accessHTML = accessHTML+"
  •  "; - - - getMenuItemEntities = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); - - String subMenuHTML = ""; - for (MenuItemEntity menuItem : getMenuItemEntities) { - - String mmid = desiredId+"_"+menuItem.getId(); - // Check if the ID exists in the list of entities - getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString()); - // Check Module Id Access - if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { isSelected = "checked"; } else { isSelected = ""; } - - if(menuItem.getHasSub()) { - - getSubMenuItemEntities = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getSubMenuItemEntities) { - String isSelected2 = ""; - String smid = desiredId+"_"+menuItem.getId()+"_"+subMenuItem.getId(); - // Check if the ID exists in the list of entities - getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, desiredId.toString(),menuItem.getId().toString(),subMenuItem.getId().toString()); - // Check Module Id Access - if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { isSelected2 = "checked"; } else { isSelected2 = ""; } - - subSubMenuHTML = subSubMenuHTML+"
  •  
  • "; - } - if(subSubMenuHTML.equals("")) - { - subMenuHTML = subMenuHTML+"
  •  
  • "; - } - else { - subMenuHTML = subMenuHTML+"
  •  
      "+subSubMenuHTML+"
  • "; - } - - } - else { - subMenuHTML = subMenuHTML+"
  •  
  • "; - } - } - - accessHTML = accessHTML+"
      "+subMenuHTML+"
    "; - subMenuHTML = ""; - - } - - accessTableHTML = groupNameHTML+"
      "+accessHTML+"
    "; - - return accessTableHTML; - } - - @PostMapping("/saveGroupAccessData") - public String saveGroupAccessData(@RequestBody Map requestBody) { - @SuppressWarnings("unchecked") - List checkedData = (List) requestBody.get("checkedData"); - String groupId = (String) requestBody.get("groupId"); - String dataType[]= {"","", "module","menu","submenu"}; - if (groupId != null) { - System.out.println("groupid value: " + groupId); - - // Set isActive = false based on groupId - appModuleAccessRepository.updateActiveStatus(false,groupId); - menuItemAccessRepository.updateActiveStatus(false,groupId); - subMenuItemAccessRepository.updateActiveStatus(false,groupId); - - // Now update as per input data - if (checkedData != null) { - for (String data : checkedData) { - System.out.println(data); - - // m_x -> Module Value (moduleId) -> 2 - // mm_x_x -> Menu Value (moduleId,menuId) ->3 - // sm_x_x_x -> SubMenu Value (moduleId, menuId, submenuId) ->4 - - String[] dataValue = data.split("_"); - Integer dataLength = dataValue.length; - System.out.println(dataLength +" ==> "+dataType[dataLength]); - - if(dataValue.length==2) { // Module - // Check if the ID exists in the list of entities - getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, dataValue[1]); - if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { - appModuleAccessRepository.update(true,groupId,dataValue[1]); - } - else { - appModuleAccessRepository.insert(groupId,dataValue[1]); - } - } - else if(dataValue.length==3) { // Menu - // Check if the ID exists in the list of entities - getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2]); - if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { - menuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2]); - } - else { - menuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2]); - } - } - else if(dataValue.length==4) { // SubMenu - // Check if the ID exists in the list of entities - getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, dataValue[1], dataValue[2], dataValue[3]); - if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { - subMenuItemAccessRepository.update(true,groupId,dataValue[1],dataValue[2],dataValue[3]); - } - else { - subMenuItemAccessRepository.insert(groupId,dataValue[1],dataValue[2],dataValue[3]); - } - } - - } - } - - } - - return ""; - } - - @GetMapping(value="/getUserProfileBasic") - public String getUserProfileBasic(@RequestParam String userId) { - //String userHtml =""; - String userProfileHtml =""; - //String userProfileTimelineHtml =""; - getAppUserEntities = appUserRepository.showById(userId); - for (AppUserEntity appUserEntity : getAppUserEntities) { - - userProfileHtml = "" - + " " - + "
    " - + "
    " - + "
    " - + " \n" - + "

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

    \n" - + "

    Front End Developer

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

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

    \n" - + "

    Front End Developer

    \n" - + "

    "+userIp+"

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

    "; - } - userTimeLineHTML = "" - + "
    " - + "
    " - + userTimeLineHTML - + "
    " - + "
    "; - - return userTimeLineHTML; - } - - - public String dateFormat(String timestampString) { - //String timestampString = "2023-12-28T16:21:24"; - LocalDateTime timestamp = LocalDateTime.parse(timestampString, DateTimeFormatter.ISO_DATE_TIME); - - // Define the desired date-time format - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a"); - - // Format the timestamp - String formattedTimestamp = timestamp.format(formatter); - - //System.out.println(formattedTimestamp); - return formattedTimestamp.toUpperCase(); - } - - public String getUserIP() { - String ipAddress = request.getHeader("X-Forwarded-For"); - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("WL-Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("HTTP_CLIENT_IP"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR"); - } - if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getRemoteAddr(); - } - return ipAddress; - } - - @GetMapping(value="/passwordGenerator") - public String passwordGenerator(@RequestParam(value = "password", required = false) String password) { - BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - String rawPassword = password; - String encodedPassword = passwordEncoder.encode(rawPassword); - return encodedPassword; - } - - @PostMapping(value="/resetPassword") - public String resetPassword( - @RequestParam(value = "", required = false) String userid, - @RequestParam(value = "", required = false) String oldpassword, - @RequestParam(value = "", required = false) String newpassword - ) { - - System.out.println(userid+" : "+oldpassword+" : "+newpassword); - - String oldPasswordTxt=oldpassword; //passwordGenerator(oldpassword); - String newPasswordTxt=newpassword; //passwordGenerator(newpassword); - String rawPasswordTxt=newpassword; - - System.out.println(oldPasswordTxt+" : "+newPasswordTxt+" : "+rawPasswordTxt); - - String response = loginUserInfo.resetPassword(userid,oldPasswordTxt,newPasswordTxt,rawPasswordTxt); - return response; - } - - @PostMapping(value="/userCheck") - public List> userCheck( - @RequestParam(value = "", required = false) String usernametxt, - @RequestParam(value = "", required = false) String passwordtxt - ) { - - System.out.println("HRM Service : "+usernametxt+" : "+passwordtxt); - - List> response = loginUserInfo.userCheck(usernametxt,passwordtxt); - return response; - } - -// @GetMapping(value="/getDailyKural") -// public List getDailyKural() { -// return loginUserInfo.getDailyContent(); -// } -} diff --git a/src/main/java/com/gcc/election/controller/AdminController.java b/src/main/java/com/gcc/election/controller/AdminController.java deleted file mode 100644 index 9762856..0000000 --- a/src/main/java/com/gcc/election/controller/AdminController.java +++ /dev/null @@ -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 getUser() { - List appUserEntities; - appUserEntities = appUserRepository.showAll(); - return appUserEntities; - } - - public List getUserGroup() { - List appUserGroupEntities; - appUserGroupEntities = appUserGroupRepository.findAll(); - return appUserGroupEntities; - } - - public String getAccessTreeHTML() { - - //List getAppModuleAccessEntities; - List getAppModuleEntities; - - getAppModuleEntities = appModuleRepository.showAll(); - - String accessHTML = ""; - String accessTableHTML = ""; - //String MenuHTML = ""; - //String subMenuHTML = ""; - for (AppModuleEntity moduleName : getAppModuleEntities) { - - accessHTML = accessHTML+"
  •  "; - - List getMenuItems; - getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); - - String subMenuHTML = ""; - for (MenuItemEntity menuItem : getMenuItems) { - - if(menuItem.getHasSub()) { - - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - subSubMenuHTML = subSubMenuHTML+"
  • "; - } - if(subSubMenuHTML.equals("")) - { - subMenuHTML = subMenuHTML+"
  • "; - } - else { - subMenuHTML = subMenuHTML+"
    • "+subSubMenuHTML+"
  • "; - } - - } - else { - subMenuHTML = subMenuHTML+"
  • "; - } - } - - accessHTML = accessHTML+"
      "+subMenuHTML+"
    "; - subMenuHTML = ""; - } - - accessTableHTML = "
      "+accessHTML+"
    "; - - return accessTableHTML; - } -} diff --git a/src/main/java/com/gcc/election/controller/MainController.java b/src/main/java/com/gcc/election/controller/MainController.java deleted file mode 100644 index 9ec2d7b..0000000 --- a/src/main/java/com/gcc/election/controller/MainController.java +++ /dev/null @@ -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"; - } -} diff --git a/src/main/java/com/gcc/election/controller/MenuController.java b/src/main/java/com/gcc/election/controller/MenuController.java deleted file mode 100644 index 91d552a..0000000 --- a/src/main/java/com/gcc/election/controller/MenuController.java +++ /dev/null @@ -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 getAppModuleAccessEntities; - List getAppModuleEntities; - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - getAppModuleEntities = appModuleRepository.showAll(); - } - else { - getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId()); - - String[] checkModuleId = new String[getAppModuleAccessEntities.size()]; - int i=0; - for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) { - checkModuleId[i]=accessEntity.getModuleId().getId().toString(); - i++; - } - getAppModuleEntities = appModuleRepository.showAllById(checkModuleId); - } - - String menuHTML = ""; - menuHTML = ""; - for (AppModuleEntity moduleName : getAppModuleEntities) { - - menuHTML = menuHTML+"
    "+moduleName.getName()+"
    "; - - List getMenuItems; - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); - } - else { - List getMenuItemAccess = menuItemAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId(), moduleName.getId().toString()); - - String[] checkMenuId = new String[getMenuItemAccess.size()]; - int j=0; - for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) { - checkMenuId[j]=menuAccessEntity.getMenuItemId().getId().toString(); - j++; - } - getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(moduleName.getId(),checkMenuId); - } - String subMenuHTML = ""; - for (MenuItemEntity menuItem : getMenuItems) { - if(menuItem.getHasSub()) { - if(LoginUserInfo.getUserRole().equals("ADMIN")) { - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - String target = ""; - System.err.println(subMenuItem.getExtenalLink()); - if(subMenuItem.getExtenalLink()) { - target = " target=\"_blank\""; - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - else { - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - - } - if(subSubMenuHTML.equals("")) - { - subMenuHTML = subMenuHTML+""; - } - else { - subMenuHTML = subMenuHTML+"
    "+menuItem.getName()+"
    "+subSubMenuHTML+"
    "; - } - } - else { - List getSubMenuItemAccess = subMenuItemAccessRepository.findByUserGroupIDAccess(LoginUserInfo.getUserGroupId(), moduleName.getId().toString(), menuItem.getId().toString()); - - String[] checkSubMenuId = new String[getSubMenuItemAccess.size()]; - if(checkSubMenuId.length>0) - { - int k=0; - for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) { - checkSubMenuId[k]=subMenuItemAccessEntity.getSubMenuItemId().getId().toString(); - k++; - } - - List getMenuSubItems = subMenuItemRepository.getSubMenuItemByMenuItemIdAccess(menuItem.getId(),checkSubMenuId); - String subSubMenuHTML = ""; - for (SubMenuItemEntity subMenuItem : getMenuSubItems) { - String target = ""; - System.err.println(subMenuItem.getExtenalLink()); - if(subMenuItem.getExtenalLink()) { - target = " target=\"_blank\""; - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - else { - subSubMenuHTML = subSubMenuHTML+""+subMenuItem.getName()+""; - } - } - subMenuHTML = subMenuHTML+"
    "+menuItem.getName()+"
    "+subSubMenuHTML+"
    "; - } - else { - subMenuHTML = subMenuHTML+""; - } - } - - } - else { - if(menuItem.getOrderby()>0) { - subMenuHTML = subMenuHTML+""+menuItem.getName()+""; - } - } - } - - menuHTML = menuHTML+subMenuHTML+"
    "; - } - - return menuHTML; - } -} diff --git a/src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java b/src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java deleted file mode 100644 index ae05070..0000000 --- a/src/main/java/com/gcc/election/dataentry/controller/BatchAPIController.java +++ /dev/null @@ -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> list = batchAPIService.getBatchDetails(); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @GetMapping("/getbatchbyId") - public ResponseEntity getBatchById(@RequestParam String id) { - - try { - Map list = batchAPIService.getBatchById(id); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @GetMapping("/getAllDesignations") - public ResponseEntity getAllDesignations(){ - try { - List> list = batchAPIService.getAllDesignations(); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - - - @GetMapping("/getPayDetails") - public ResponseEntity getPayDetails(@RequestParam int DesgId) { - try { - Map list = batchAPIService.getPayDetailsByDesgId(DesgId); - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - - } - } - - @GetMapping("/getAllDistricts") - public ResponseEntity getAllDistricts(){ - try { - List> list = batchAPIService.getAllDistricts(); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @GetMapping("/getAllAclist") - public ResponseEntity getAllAcList(){ - try { - List> list = batchAPIService.getAllAcList(); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @GetMapping("/getOfficeDetailsById") - public ResponseEntity getOfficeDetailsById(@RequestParam int officeId){ - - - try { - List> list = batchAPIService.getOfficeDetailsById(officeId); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @PostMapping("/savenewentry") - public ResponseEntity> 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 - )); - } - - -} diff --git a/src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java b/src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java deleted file mode 100644 index 08907e7..0000000 --- a/src/main/java/com/gcc/election/dataentry/controller/Maincontroller.java +++ /dev/null @@ -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 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"; - } -} diff --git a/src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java b/src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java deleted file mode 100644 index a0f8fdd..0000000 --- a/src/main/java/com/gcc/election/dataentry/controller/UpdationAPIController.java +++ /dev/null @@ -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> list=upservice.getbymobanduniq(mobilenum,uniquenum,batch_num); - - Map 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 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> list = upservice.getPollingDetailsById(id); - - Map response = new HashMap<>(); - response.put("status", "success"); - response.put("data", list); - - return ResponseEntity.ok(response); - - } catch (Exception ex) { - ex.printStackTrace(); - - Map error = new HashMap<>(); - error.put("status", "error"); - error.put("message", ex.getMessage()); - - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); - } - } - - @PostMapping("/updateppdetailsbyid") - public ResponseEntity> 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" - )); - } - - - } - -} diff --git a/src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java b/src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java deleted file mode 100644 index 070b53d..0000000 --- a/src/main/java/com/gcc/election/dataentry/service/BatchAPIService.java +++ /dev/null @@ -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> 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 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> 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 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> 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> 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> 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); - } - - - - - -} diff --git a/src/main/java/com/gcc/election/dataentry/service/UpdationService.java b/src/main/java/com/gcc/election/dataentry/service/UpdationService.java deleted file mode 100644 index 26f8f15..0000000 --- a/src/main/java/com/gcc/election/dataentry/service/UpdationService.java +++ /dev/null @@ -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> 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 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> 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 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"; - } - - - } - -} diff --git a/src/main/java/com/gcc/election/interceptor/AppInterceptor.java b/src/main/java/com/gcc/election/interceptor/AppInterceptor.java deleted file mode 100644 index de67aac..0000000 --- a/src/main/java/com/gcc/election/interceptor/AppInterceptor.java +++ /dev/null @@ -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 getAppModuleAccessEntities; - List getMenuItemAccessEntities; - List getSubMenuItemAccessEntities; - - private AppModuleAccessRepository appModuleAccessRepository; - private MenuItemAccessRepository menuItemAccessRepository; - private SubMenuItemAccessRepository subMenuItemAccessRepository; - - List getAppModuleEntities; - List getMenuItemEntities; - List getSubMenuItemEntities; - - private AppModuleRepository appModuleRepository; - private MenuItemRepository menuItemRepository; - private SubMenuItemRepository subMenuItemRepository; - - private final Environment environment; - - - @Autowired - public AppInterceptor(AppModuleAccessRepository appModuleAccessRepository, - MenuItemAccessRepository menuItemAccessRepository, - SubMenuItemAccessRepository subMenuItemAccessRepository, - AppModuleRepository appModuleRepository, - MenuItemRepository menuItemRepository, - SubMenuItemRepository subMenuItemRepository, - Environment environment) { - - this.appModuleAccessRepository = appModuleAccessRepository; - this.menuItemAccessRepository = menuItemAccessRepository; - this.subMenuItemAccessRepository = subMenuItemAccessRepository; - - this.appModuleRepository = appModuleRepository; - this.menuItemRepository = menuItemRepository; - this.subMenuItemRepository = subMenuItemRepository; - - this.environment = environment; - } - - private boolean isLoginPage(HttpServletRequest request) { - RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/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); - } - } - } - } - } -} diff --git a/src/main/java/com/gcc/election/repository/AppModuleRepository.java b/src/main/java/com/gcc/election/repository/AppModuleRepository.java deleted file mode 100644 index 34abf33..0000000 --- a/src/main/java/com/gcc/election/repository/AppModuleRepository.java +++ /dev/null @@ -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{ - - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `modules` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`", nativeQuery = true) - List showAll(); - - @Query(value = "SELECT * FROM `modules` WHERE `id` IN (:checkModuleid) AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id`", nativeQuery = true) - List showAllById(String[] checkModuleid); - - @Query(value = "SELECT * FROM `modules` WHERE (`module_path` = :module_path) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByModulePath(String module_path); -} diff --git a/src/main/java/com/gcc/election/repository/SubMenuItemRepository.java b/src/main/java/com/gcc/election/repository/SubMenuItemRepository.java deleted file mode 100644 index 4ad68d1..0000000 --- a/src/main/java/com/gcc/election/repository/SubMenuItemRepository.java +++ /dev/null @@ -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{ - - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true) - List getSubMenuItemByModuleId(@Param("module_id") int module_id); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `menuitem_id`=:menuitem_id ORDER BY `orderby`", nativeQuery = true) - List getSubMenuItemByMenuItemId(@Param("menuitem_id") int menuitem_id); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`menuitem_id`=:menuitem_id AND `id` IN (:checkSubMenuid)) ORDER BY `orderby`", nativeQuery = true) - List getSubMenuItemByMenuItemIdAccess(@Param("menuitem_id") int menuitem_id,String[] checkSubMenuid); - - @Query(value = "SELECT * FROM `submenuitem` WHERE (`url`=:url) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByUrl(@Param("url") String url); -} diff --git a/src/main/java/com/gcc/election/service/Base64Util.java b/src/main/java/com/gcc/election/service/Base64Util.java deleted file mode 100644 index 707edb2..0000000 --- a/src/main/java/com/gcc/election/service/Base64Util.java +++ /dev/null @@ -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 ""; - } - } -} diff --git a/src/main/java/com/gcc/election/ElectionApplication.java b/src/main/java/com/gcc/swm_services/SwmApplication.java similarity index 61% rename from src/main/java/com/gcc/election/ElectionApplication.java rename to src/main/java/com/gcc/swm_services/SwmApplication.java index d1d77d7..e983cf3 100644 --- a/src/main/java/com/gcc/election/ElectionApplication.java +++ b/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.autoconfigure.SpringBootApplication; @SpringBootApplication -public class ElectionApplication { +public class SwmApplication { public static void main(String[] args) { - SpringApplication.run(ElectionApplication.class, args); + SpringApplication.run(SwmApplication.class, args); } } diff --git a/src/main/java/com/gcc/election/configuration/AppConfig.java b/src/main/java/com/gcc/swm_services/configuration/AppConfig.java similarity index 84% rename from src/main/java/com/gcc/election/configuration/AppConfig.java rename to src/main/java/com/gcc/swm_services/configuration/AppConfig.java index f5f1974..9eb5b8d 100644 --- a/src/main/java/com/gcc/election/configuration/AppConfig.java +++ b/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.Configuration; @@ -7,10 +7,9 @@ import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { - - @Bean + @Bean public RestTemplate restTemplate() { return new RestTemplate(); } - + } diff --git a/src/main/java/com/gcc/swm_services/configuration/DataSourceConfig.java b/src/main/java/com/gcc/swm_services/configuration/DataSourceConfig.java new file mode 100644 index 0000000..d320251 --- /dev/null +++ b/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; + } + +} diff --git a/src/main/java/com/gcc/election/configuration/JacksonConfiguration.java b/src/main/java/com/gcc/swm_services/configuration/JacksonConfiguration.java similarity index 78% rename from src/main/java/com/gcc/election/configuration/JacksonConfiguration.java rename to src/main/java/com/gcc/swm_services/configuration/JacksonConfiguration.java index 2852249..1c2a36f 100644 --- a/src/main/java/com/gcc/election/configuration/JacksonConfiguration.java +++ b/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.Configuration; @@ -7,14 +6,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - @Configuration public class JacksonConfiguration { - @Bean + @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during serialization + objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during + // serialization objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Serialize dates as Strings objectMapper.registerModule(new JavaTimeModule()); // Register JavaTimeModule for Java 8 Date/Time support return objectMapper; diff --git a/src/main/java/com/gcc/swm_services/configuration/SecurityConfig.java b/src/main/java/com/gcc/swm_services/configuration/SecurityConfig.java new file mode 100644 index 0000000..37ad948 --- /dev/null +++ b/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(); + } +} diff --git a/src/main/java/com/gcc/swm_services/configuration/ThymeleafConfig.java b/src/main/java/com/gcc/swm_services/configuration/ThymeleafConfig.java new file mode 100644 index 0000000..7b1a2f1 --- /dev/null +++ b/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; +// } +// +// } diff --git a/src/main/java/com/gcc/swm_services/configuration/WebMvcConfig.java b/src/main/java/com/gcc/swm_services/configuration/WebMvcConfig.java new file mode 100644 index 0000000..57c5229 --- /dev/null +++ b/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 + "/"); + } +} diff --git a/src/main/java/com/gcc/swm_services/controller/APIController.java b/src/main/java/com/gcc/swm_services/controller/APIController.java new file mode 100644 index 0000000..7e15962 --- /dev/null +++ b/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 getAppUserEntities; + + @Autowired + private HttpServletRequest request; + + @Autowired + private AppUserRepository appUserRepository; + + @Autowired + private LoginUserInfo loginUserInfo; + + List getActivityLogs; + @Autowired + private UserActivityLogRepository userActivityLogRepository; + + List getAppModuleAccessEntities; + List getMenuItemAccessEntities; + List getSubMenuItemAccessEntities; + + @Autowired + private AppModuleAccessRepository appModuleAccessRepository; + @Autowired + private MenuItemAccessRepository menuItemAccessRepository; + @Autowired + private SubMenuItemAccessRepository subMenuItemAccessRepository; + + List getAppModuleEntities; + List getMenuItemEntities; + List getSubMenuItemEntities; + + @Autowired + private AppModuleRepository appModuleRepository; + @Autowired + private MenuItemRepository menuItemRepository; + @Autowired + private SubMenuItemRepository subMenuItemRepository; + + @Autowired + public APIController( + AppModuleRepository appModuleRepository, + MenuItemRepository menuItemRepository, + SubMenuItemRepository subMenuItemRepository, + AppModuleAccessRepository appModuleAccessRepository, + MenuItemAccessRepository menuItemAccessRepository, + SubMenuItemAccessRepository subMenuItemAccessRepository, + UserActivityLogRepository userActivityLogRepository) { + + this.appModuleRepository = appModuleRepository; + this.menuItemRepository = menuItemRepository; + this.subMenuItemRepository = subMenuItemRepository; + + this.appModuleAccessRepository = appModuleAccessRepository; + this.menuItemAccessRepository = menuItemAccessRepository; + this.subMenuItemAccessRepository = subMenuItemAccessRepository; + this.userActivityLogRepository = userActivityLogRepository; + + } + + // Encode to Base64 + @GetMapping(value = "/encodeBase64") + public static String encodeBase64(@RequestParam String string) { + String value = string; + byte[] encodedBytes = Base64.getEncoder().encode(value.getBytes()); + return new String(encodedBytes); + } + + // Decode from Base64 + @GetMapping(value = "/decodeBase64") + public static String decodeBase64(@RequestParam String string) { + String encodedValue = string; + byte[] decodedBytes = Base64.getDecoder().decode(encodedValue); + return new String(decodedBytes); + } + + @GetMapping(value = "/getAccessTree") + public String getAccessTreeHTML(@RequestParam String groupId, @RequestParam String groupName) { + + getAppModuleEntities = appModuleRepository.showAll(); + + String accessHTML = ""; + String accessTableHTML = ""; + // String MenuHTML = ""; + String isSelected = ""; + // String subMenuHTML = ""; + + String groupNameHTML = "" + groupName + ""; + for (AppModuleEntity moduleName : getAppModuleEntities) { + + // ID to check + Integer desiredId = moduleName.getId(); + + // Check if the ID exists in the list of entities + getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, desiredId.toString()); + // Check Module Id Access + if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { + isSelected = "checked"; + } else { + isSelected = ""; + } + + accessHTML = accessHTML + "
  •  "; + + getMenuItemEntities = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); + + String subMenuHTML = ""; + for (MenuItemEntity menuItem : getMenuItemEntities) { + + String mmid = desiredId + "_" + menuItem.getId(); + // Check if the ID exists in the list of entities + getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, desiredId.toString(), + menuItem.getId().toString()); + // Check Module Id Access + if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { + isSelected = "checked"; + } else { + isSelected = ""; + } + + if (menuItem.getHasSub()) { + + getSubMenuItemEntities = subMenuItemRepository.getSubMenuItemByMenuItemId(menuItem.getId()); + String subSubMenuHTML = ""; + for (SubMenuItemEntity subMenuItem : getSubMenuItemEntities) { + String isSelected2 = ""; + String smid = desiredId + "_" + menuItem.getId() + "_" + subMenuItem.getId(); + // Check if the ID exists in the list of entities + getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, + desiredId.toString(), menuItem.getId().toString(), subMenuItem.getId().toString()); + // Check Module Id Access + if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { + isSelected2 = "checked"; + } else { + isSelected2 = ""; + } + + subSubMenuHTML = subSubMenuHTML + "
  •  
  • "; + } + if (subSubMenuHTML.equals("")) { + subMenuHTML = subMenuHTML + "
  •  
  • "; + } else { + subMenuHTML = subMenuHTML + "
  •  
      " + + subSubMenuHTML + "
  • "; + } + + } else { + subMenuHTML = subMenuHTML + "
  •  
  • "; + } + } + + accessHTML = accessHTML + "
      " + subMenuHTML + "
    "; + subMenuHTML = ""; + + } + + accessTableHTML = groupNameHTML + "
      " + + accessHTML + "
    "; + + return accessTableHTML; + } + + @PostMapping("/saveGroupAccessData") + public String saveGroupAccessData(@RequestBody Map requestBody) { + @SuppressWarnings("unchecked") + List checkedData = (List) requestBody.get("checkedData"); + String groupId = (String) requestBody.get("groupId"); + String dataType[] = { "", "", "module", "menu", "submenu" }; + if (groupId != null) { + System.out.println("groupid value: " + groupId); + + // Set isActive = false based on groupId + appModuleAccessRepository.updateActiveStatus(false, groupId); + menuItemAccessRepository.updateActiveStatus(false, groupId); + subMenuItemAccessRepository.updateActiveStatus(false, groupId); + + // Now update as per input data + if (checkedData != null) { + for (String data : checkedData) { + System.out.println(data); + + // m_x -> Module Value (moduleId) -> 2 + // mm_x_x -> Menu Value (moduleId,menuId) ->3 + // sm_x_x_x -> SubMenu Value (moduleId, menuId, submenuId) ->4 + + String[] dataValue = data.split("_"); + Integer dataLength = dataValue.length; + System.out.println(dataLength + " ==> " + dataType[dataLength]); + + if (dataValue.length == 2) { // Module + // Check if the ID exists in the list of entities + getAppModuleAccessEntities = appModuleAccessRepository.findByAll(groupId, dataValue[1]); + if (getAppModuleAccessEntities != null && !getAppModuleAccessEntities.isEmpty()) { + appModuleAccessRepository.update(true, groupId, dataValue[1]); + } else { + appModuleAccessRepository.insert(groupId, dataValue[1]); + } + } else if (dataValue.length == 3) { // Menu + // Check if the ID exists in the list of entities + getMenuItemAccessEntities = menuItemAccessRepository.findByAll(groupId, dataValue[1], + dataValue[2]); + if (getMenuItemAccessEntities != null && !getMenuItemAccessEntities.isEmpty()) { + menuItemAccessRepository.update(true, groupId, dataValue[1], dataValue[2]); + } else { + menuItemAccessRepository.insert(groupId, dataValue[1], dataValue[2]); + } + } else if (dataValue.length == 4) { // SubMenu + // Check if the ID exists in the list of entities + getSubMenuItemAccessEntities = subMenuItemAccessRepository.findByAll(groupId, dataValue[1], + dataValue[2], dataValue[3]); + if (getSubMenuItemAccessEntities != null && !getSubMenuItemAccessEntities.isEmpty()) { + subMenuItemAccessRepository.update(true, groupId, dataValue[1], dataValue[2], dataValue[3]); + } else { + subMenuItemAccessRepository.insert(groupId, dataValue[1], dataValue[2], dataValue[3]); + } + } + + } + } + + } + + return ""; + } + + @GetMapping(value = "/getUserProfileBasic") + public String getUserProfileBasic(@RequestParam String userId) { + // String userHtml =""; + String userProfileHtml = ""; + // String userProfileTimelineHtml =""; + getAppUserEntities = appUserRepository.showById(userId); + for (AppUserEntity appUserEntity : getAppUserEntities) { + + userProfileHtml = "" + + " " + + "
    " + + "
    " + + "
    " + + " \n" + + "

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

    \n" + + "

    Front End Developer

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

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

    \n" + + "

    Front End Developer

    \n" + + "

    " + userIp + "

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

    "; + } + userTimeLineHTML = "" + + "
    " + + "
    " + + userTimeLineHTML + + "
    " + + "
    "; + + return userTimeLineHTML; + } + + public String dateFormat(String timestampString) { + // String timestampString = "2023-12-28T16:21:24"; + LocalDateTime timestamp = LocalDateTime.parse(timestampString, DateTimeFormatter.ISO_DATE_TIME); + + // Define the desired date-time format + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a"); + + // Format the timestamp + String formattedTimestamp = timestamp.format(formatter); + + // System.out.println(formattedTimestamp); + return formattedTimestamp.toUpperCase(); + } + + public String getUserIP() { + String ipAddress = request.getHeader("X-Forwarded-For"); + if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("WL-Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("HTTP_CLIENT_IP"); + } + if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getRemoteAddr(); + } + return ipAddress; + } + + @GetMapping(value = "/passwordGenerator") + public String passwordGenerator(@RequestParam(value = "password", required = false) String password) { + BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + String rawPassword = password; + String encodedPassword = passwordEncoder.encode(rawPassword); + return encodedPassword; + } + + @PostMapping(value = "/resetPassword") + public String resetPassword( + @RequestParam(value = "", required = false) String userid, + @RequestParam(value = "", required = false) String oldpassword, + @RequestParam(value = "", required = false) String newpassword) { + + System.out.println(userid + " : " + oldpassword + " : " + newpassword); + + String oldPasswordTxt = oldpassword; // passwordGenerator(oldpassword); + String newPasswordTxt = newpassword; // passwordGenerator(newpassword); + String rawPasswordTxt = newpassword; + + System.out.println(oldPasswordTxt + " : " + newPasswordTxt + " : " + rawPasswordTxt); + + String response = loginUserInfo.resetPassword(userid, oldPasswordTxt, newPasswordTxt, rawPasswordTxt); + return response; + } + + @PostMapping(value = "/userCheck") + public List> userCheck( + @RequestParam(value = "", required = false) String usernametxt, + @RequestParam(value = "", required = false) String passwordtxt) { + + System.out.println("HRM Service : " + usernametxt + " : " + passwordtxt); + + List> response = loginUserInfo.userCheck(usernametxt, passwordtxt); + return response; + } + + // @GetMapping(value="/getDailyKural") + // public List getDailyKural() { + // return loginUserInfo.getDailyContent(); + // } +} diff --git a/src/main/java/com/gcc/swm_services/controller/AdminController.java b/src/main/java/com/gcc/swm_services/controller/AdminController.java new file mode 100644 index 0000000..5012fa5 --- /dev/null +++ b/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 getUser() { + List appUserEntities; + appUserEntities = appUserRepository.showAll(); + return appUserEntities; + } + + public List getUserGroup() { + List appUserGroupEntities; + appUserGroupEntities = appUserGroupRepository.findAll(); + return appUserGroupEntities; + } + + public String getAccessTreeHTML() { + + // List getAppModuleAccessEntities; + List getAppModuleEntities; + + getAppModuleEntities = appModuleRepository.showAll(); + + String accessHTML = ""; + String accessTableHTML = ""; + // String MenuHTML = ""; + // String subMenuHTML = ""; + for (AppModuleEntity moduleName : getAppModuleEntities) { + + accessHTML = accessHTML + "
  •  "; + + List getMenuItems; + getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); + + String subMenuHTML = ""; + for (MenuItemEntity menuItem : getMenuItems) { + + if (menuItem.getHasSub()) { + + List getMenuSubItems = subMenuItemRepository + .getSubMenuItemByMenuItemId(menuItem.getId()); + String subSubMenuHTML = ""; + for (SubMenuItemEntity subMenuItem : getMenuSubItems) { + subSubMenuHTML = subSubMenuHTML + "
  • "; + } + if (subSubMenuHTML.equals("")) { + subMenuHTML = subMenuHTML + "
  • "; + } else { + subMenuHTML = subMenuHTML + "
    • " + subSubMenuHTML + "
  • "; + } + + } else { + subMenuHTML = subMenuHTML + "
  • "; + } + } + + accessHTML = accessHTML + "
      " + subMenuHTML + "
    "; + subMenuHTML = ""; + } + + accessTableHTML = "
      " + accessHTML + "
    "; + + return accessTableHTML; + } +} diff --git a/src/main/java/com/gcc/election/controller/CustomErrorController.java b/src/main/java/com/gcc/swm_services/controller/CustomErrorController.java similarity index 80% rename from src/main/java/com/gcc/election/controller/CustomErrorController.java rename to src/main/java/com/gcc/swm_services/controller/CustomErrorController.java index 02c8d62..bffcd61 100644 --- a/src/main/java/com/gcc/election/controller/CustomErrorController.java +++ b/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.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.ResponseBody; -import com.gcc.election.modeldata.ErrorResponse; - - +import com.gcc.swm_services.modeldata.ErrorResponse; @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 PAGE_NAME_MAP = new HashMap<>(); - + public String getPageName(Integer statusCode) { if (statusCode != null) { return PAGE_NAME_MAP.getOrDefault(statusCode, "errorPage"); @@ -31,18 +29,20 @@ public class CustomErrorController implements ErrorController{ return "errorPage"; } } - + // Handle errors for web applications, return HTML error pages @RequestMapping(value = ERROR_PATH, produces = "text/html") public String handleWebError(HttpServletRequest request, Model model) { // Retrieve error information from the request - // HttpStatus status = HttpStatus.valueOf((Integer) request.getAttribute("javax.servlet.error.status_code")); - //Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); + // 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"); if (statusCode == null) { - // Add the error message to the model + // Add the error message to the model model.addAttribute("errorStatus", "Error 403"); model.addAttribute("errorError", "403 - Access Denied"); model.addAttribute("errorMessage", "Oops, You don`t have permission to access this page."); @@ -50,7 +50,7 @@ public class CustomErrorController implements ErrorController{ // You may choose to set default values or redirect to a generic error page return "error-403"; } - + HttpStatus status = (statusCode != null) ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR; Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); @@ -59,41 +59,38 @@ public class CustomErrorController implements ErrorController{ Integer errorStatus = 404; String errorError = "Internal Server Error"; String errorMessage = "An error occurred"; // Default error message - + String pageName = new CustomErrorController().getPageName(status.value()); - + // Print error information to the console if (status != null) { - errorStatus = status.value(); + errorStatus = status.value(); errorError = status.getReasonPhrase(); - - System.err.println("HTTP Status: " + status +"\n" - +"Status Code: "+status.value()+"\n"+ "Status Error: " - +status.getReasonPhrase() - +"Page Name: "+pageName); - + + System.err.println("HTTP Status: " + status + "\n" + + "Status Code: " + status.value() + "\n" + "Status Error: " + + status.getReasonPhrase() + + "Page Name: " + pageName); + // Check if the status code if (status == HttpStatus.NOT_FOUND) { errorPage = "error-404"; // 400 Error Page - } - else if (status == HttpStatus.INTERNAL_SERVER_ERROR) { + } else if (status == HttpStatus.INTERNAL_SERVER_ERROR) { errorPage = "error-500"; // 500 Error page - } - else { - errorPage = "error"; //// Other Error page + } else { + errorPage = "error"; //// Other Error page } } if (throwable != null) { - // Retrieve the exception message + // Retrieve the exception message errorMessage = throwable.getMessage(); throwable.printStackTrace(); } - + // Add the error message to the model model.addAttribute("errorStatus", errorStatus); model.addAttribute("errorError", errorError); model.addAttribute("errorMessage", errorMessage); - return errorPage; // Return the name of your custom HTML error page (without the .html extension) } @@ -120,7 +117,6 @@ public class CustomErrorController implements ErrorController{ return ResponseEntity.status(status).body(errorResponse); } - @GetMapping(ERROR_PATH) public String handleError() { return "error-404"; // Return the name of your custom error page (without the .html extension) diff --git a/src/main/java/com/gcc/election/controller/DateTimeUtil.java b/src/main/java/com/gcc/swm_services/controller/DateTimeUtil.java similarity index 65% rename from src/main/java/com/gcc/election/controller/DateTimeUtil.java rename to src/main/java/com/gcc/swm_services/controller/DateTimeUtil.java index 3d05f34..6f2ce9c 100644 --- a/src/main/java/com/gcc/election/controller/DateTimeUtil.java +++ b/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 java.time.LocalDateTime; import java.time.format.DateTimeFormatter; - @Service public class DateTimeUtil { - public static String getCurrentDateTime() { + public static String getCurrentDateTime() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss"); LocalDateTime now = LocalDateTime.now(); return now.format(formatter); } - public static String getCurrentYear() { + + public static String getCurrentYear() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy"); LocalDateTime now = LocalDateTime.now(); return now.format(formatter); } - public static String getCurrentMonth() { + + public static String getCurrentMonth() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM"); LocalDateTime now = LocalDateTime.now(); return now.format(formatter); } - public static String getCurrentDay() { + + public static String getCurrentDay() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd"); LocalDateTime now = LocalDateTime.now(); return now.format(formatter); } - public static String getCurrentDateTimeMysql() { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); - return now.format(formatter); + + public static String getCurrentDateTimeMysql() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime now = LocalDateTime.now(); + return now.format(formatter); } } diff --git a/src/main/java/com/gcc/election/controller/FileController.java b/src/main/java/com/gcc/swm_services/controller/FileController.java similarity index 71% rename from src/main/java/com/gcc/election/controller/FileController.java rename to src/main/java/com/gcc/swm_services/controller/FileController.java index 626b78f..8f78a7a 100644 --- a/src/main/java/com/gcc/election/controller/FileController.java +++ b/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.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.servlet.HandlerMapping; - - import java.nio.file.Path; import java.nio.file.Paths; @@ -20,24 +18,25 @@ import javax.servlet.http.HttpServletRequest; @Controller public class FileController { - - @Value("${file.upload.directory}") + + @Value("${file.upload.directory}") private String uploadDirectory; - @GetMapping("/election/files/{directoryPath}/**") + @GetMapping("/swm/files/{directoryPath}/**") public ResponseEntity serveFile(@PathVariable String directoryPath, HttpServletRequest request) { - String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); - System.out.println(fullPath.toString()+"\n"+directoryPath.length()+"\n directoryPath:"+directoryPath); - //String relativePath = fullPath.substring(directoryPath.length() + 1); // Adding 1 for the trailing '/' - String relativePath = fullPath.replace("/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; Path path = Paths.get(filePath).normalize(); System.out.println(path.toString()); Resource resource; - try { + try { resource = new UrlResource(path.toUri()); if (resource.exists() || resource.isReadable()) { - MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; + MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; // Determine content type based on file extension String fileName = resource.getFilename(); if (fileName != null) { @@ -60,9 +59,10 @@ public class FileController { } } 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); } else { return ResponseEntity.notFound().build(); diff --git a/src/main/java/com/gcc/swm_services/controller/MainController.java b/src/main/java/com/gcc/swm_services/controller/MainController.java new file mode 100644 index 0000000..4708907 --- /dev/null +++ b/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"; + } +} diff --git a/src/main/java/com/gcc/swm_services/controller/MenuController.java b/src/main/java/com/gcc/swm_services/controller/MenuController.java new file mode 100644 index 0000000..713957b --- /dev/null +++ b/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 getAppModuleAccessEntities; + List getAppModuleEntities; + if (LoginUserInfo.getUserRole().equals("ADMIN")) { + getAppModuleEntities = appModuleRepository.showAll(); + } else { + getAppModuleAccessEntities = appModuleAccessRepository.findByUserGroupID(LoginUserInfo.getUserGroupId()); + + String[] checkModuleId = new String[getAppModuleAccessEntities.size()]; + int i = 0; + for (AppModuleAccessEntity accessEntity : getAppModuleAccessEntities) { + checkModuleId[i] = accessEntity.getModuleId().getId().toString(); + i++; + } + getAppModuleEntities = appModuleRepository.showAllById(checkModuleId); + } + + String menuHTML = ""; + menuHTML = ""; + for (AppModuleEntity moduleName : getAppModuleEntities) { + + menuHTML = menuHTML + "
    " + moduleName.getName() + + "
    "; + + List getMenuItems; + if (LoginUserInfo.getUserRole().equals("ADMIN")) { + getMenuItems = menuItemRepository.getMenuItemByModuleId(moduleName.getId()); + } else { + List getMenuItemAccess = menuItemAccessRepository + .findByUserGroupID(LoginUserInfo.getUserGroupId(), moduleName.getId().toString()); + + String[] checkMenuId = new String[getMenuItemAccess.size()]; + int j = 0; + for (MenuItemAccessEntity menuAccessEntity : getMenuItemAccess) { + checkMenuId[j] = menuAccessEntity.getMenuItemId().getId().toString(); + j++; + } + getMenuItems = menuItemRepository.getMenuItemByModuleIdAccess(moduleName.getId(), checkMenuId); + } + String subMenuHTML = ""; + for (MenuItemEntity menuItem : getMenuItems) { + if (menuItem.getHasSub()) { + if (LoginUserInfo.getUserRole().equals("ADMIN")) { + List getMenuSubItems = subMenuItemRepository + .getSubMenuItemByMenuItemId(menuItem.getId()); + String subSubMenuHTML = ""; + for (SubMenuItemEntity subMenuItem : getMenuSubItems) { + String target = ""; + System.err.println(subMenuItem.getExtenalLink()); + if (subMenuItem.getExtenalLink()) { + target = " target=\"_blank\""; + subSubMenuHTML = subSubMenuHTML + "" + subMenuItem.getName() + ""; + } else { + subSubMenuHTML = subSubMenuHTML + "" + subMenuItem.getName() + ""; + } + + } + if (subSubMenuHTML.equals("")) { + subMenuHTML = subMenuHTML + + ""; + } else { + subMenuHTML = subMenuHTML + + "
    " + menuItem.getName() + + "
    " + subSubMenuHTML + "
    "; + } + } else { + List getSubMenuItemAccess = subMenuItemAccessRepository + .findByUserGroupIDAccess(LoginUserInfo.getUserGroupId(), moduleName.getId().toString(), + menuItem.getId().toString()); + + String[] checkSubMenuId = new String[getSubMenuItemAccess.size()]; + if (checkSubMenuId.length > 0) { + int k = 0; + for (SubMenuItemAccessEntity subMenuItemAccessEntity : getSubMenuItemAccess) { + checkSubMenuId[k] = subMenuItemAccessEntity.getSubMenuItemId().getId().toString(); + k++; + } + + List getMenuSubItems = subMenuItemRepository + .getSubMenuItemByMenuItemIdAccess(menuItem.getId(), checkSubMenuId); + String subSubMenuHTML = ""; + for (SubMenuItemEntity subMenuItem : getMenuSubItems) { + String target = ""; + System.err.println(subMenuItem.getExtenalLink()); + if (subMenuItem.getExtenalLink()) { + target = " target=\"_blank\""; + subSubMenuHTML = subSubMenuHTML + "" + subMenuItem.getName() + ""; + } else { + subSubMenuHTML = subSubMenuHTML + "" + subMenuItem.getName() + ""; + } + } + subMenuHTML = subMenuHTML + + "
    " + menuItem.getName() + + "
    " + subSubMenuHTML + "
    "; + } else { + subMenuHTML = subMenuHTML + + ""; + } + } + + } else { + if (menuItem.getOrderby() > 0) { + subMenuHTML = subMenuHTML + "" + + menuItem.getName() + ""; + } + } + } + + menuHTML = menuHTML + subMenuHTML + "
    "; + } + + return menuHTML; + } +} diff --git a/src/main/java/com/gcc/election/controller/login.java b/src/main/java/com/gcc/swm_services/controller/login.java similarity index 74% rename from src/main/java/com/gcc/election/controller/login.java rename to src/main/java/com/gcc/swm_services/controller/login.java index 46ce082..67ec929 100644 --- a/src/main/java/com/gcc/election/controller/login.java +++ b/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.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -@RequestMapping("/election") -@Controller("electionLoginController") +@RequestMapping("/swm") +@Controller("swmLoginController") public class login { @GetMapping("/login") diff --git a/src/main/java/com/gcc/election/entity/AppModuleAccessEntity.java b/src/main/java/com/gcc/swm_services/entity/AppModuleAccessEntity.java similarity index 64% rename from src/main/java/com/gcc/election/entity/AppModuleAccessEntity.java rename to src/main/java/com/gcc/swm_services/entity/AppModuleAccessEntity.java index 80b582b..fa27e9c 100644 --- a/src/main/java/com/gcc/election/entity/AppModuleAccessEntity.java +++ b/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.Entity; @@ -17,100 +16,85 @@ public class AppModuleAccessEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - + @Column(name = "id", nullable = false) + private Integer id; + @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) - @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 Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public AppUserGroupEntity getUserGroupId() { return userGroupId; } - public void setUserGroupId(AppUserGroupEntity userGroupId) { this.userGroupId = userGroupId; } - public AppModuleEntity getModuleId() { return moduleId; } - public void setModuleId(AppModuleEntity moduleId) { this.moduleId = moduleId; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/AppModuleEntity.java b/src/main/java/com/gcc/swm_services/entity/AppModuleEntity.java similarity index 60% rename from src/main/java/com/gcc/election/entity/AppModuleEntity.java rename to src/main/java/com/gcc/swm_services/entity/AppModuleEntity.java index 5f6ce04..3ff7aaf 100644 --- a/src/main/java/com/gcc/election/entity/AppModuleEntity.java +++ b/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.Entity; @@ -7,130 +7,110 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; - @Entity @Table(name = "modules") public class AppModuleEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "module_path",nullable = false) - private String modulePath; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0") - private Integer orderby; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "module_path", nullable = false) + private String modulePath; + + @Column(name = "icon", nullable = true) + private String icon; + + @Column(name = "orderby", nullable = false, columnDefinition = "INTEGER default 0") + private Integer orderby; + + @Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false") + private Boolean isDelete; + + @Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true") + private Boolean isActive; + + @Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0") + private Integer createdBy; + + @Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") + private String cDate; + public AppModuleEntity() { - - } + } public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getModulePath() { return modulePath; } - public String getIcon() { return icon; } - public void setIcon(String icon) { this.icon = icon; } - public void setModulePath(String modulePath) { this.modulePath = modulePath; } - - + public Integer getOrderby() { return orderby; } - public void setOrderby(Integer orderby) { this.orderby = orderby; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/AppUserEntity.java b/src/main/java/com/gcc/swm_services/entity/AppUserEntity.java similarity index 63% rename from src/main/java/com/gcc/election/entity/AppUserEntity.java rename to src/main/java/com/gcc/swm_services/entity/AppUserEntity.java index 8327bd5..da2146d 100644 --- a/src/main/java/com/gcc/election/entity/AppUserEntity.java +++ b/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.Entity; @@ -10,146 +10,123 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; - - @Entity @Table(name = "appusers") public class AppUserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - + @Column(name = "id", nullable = false) + private Integer id; + @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "userid", referencedColumnName = "userid") - private UserInfoEntity userid; - + @JoinColumn(name = "userid", referencedColumnName = "userid") + private UserInfoEntity userid; + @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "usergroup_id", referencedColumnName = "id") - private AppUserGroupEntity usergroup_id; - - @Column(name = "username",nullable = false) - private String username; - - @Column(name = "password",nullable = false) - private String password; - - @Column(name = "roles",nullable = false) - private String roles; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - + @JoinColumn(name = "usergroup_id", referencedColumnName = "id") + private AppUserGroupEntity usergroup_id; + + @Column(name = "username", nullable = false) + private String username; + + @Column(name = "password", nullable = false) + private String password; + + @Column(name = "roles", nullable = false) + private String roles; + + @Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false") + private Boolean isDelete; + + @Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true") + private Boolean isActive; + + @Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0") + private Integer createdBy; + + @Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") + private String cDate; + public AppUserEntity() { - + } - public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public UserInfoEntity getUserid() { return userid; } - public void setUserid(UserInfoEntity userid) { this.userid = userid; } - public AppUserGroupEntity getUsergroup_id() { return usergroup_id; } - public void setUsergroup_id(AppUserGroupEntity usergroup_id) { this.usergroup_id = usergroup_id; } - public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } - public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } - public String getRoles() { return roles; } - public void setRoles(String roles) { this.roles = roles; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/AppUserGroupEntity.java b/src/main/java/com/gcc/swm_services/entity/AppUserGroupEntity.java similarity index 61% rename from src/main/java/com/gcc/election/entity/AppUserGroupEntity.java rename to src/main/java/com/gcc/swm_services/entity/AppUserGroupEntity.java index e4e55be..1e1309d 100644 --- a/src/main/java/com/gcc/election/entity/AppUserGroupEntity.java +++ b/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.Entity; @@ -14,98 +13,83 @@ public class AppUserGroupEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "icon", nullable = true) + private String icon; + + @Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false") + private Boolean isDelete; + + @Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true") + private Boolean isActive; + + @Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0") + private Integer createdBy; + + @Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") + private String cDate; + public AppUserGroupEntity() { - - } + } public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getIcon() { return icon; } - public void setIcon(String icon) { this.icon = icon; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/MenuItemAccessEntity.java b/src/main/java/com/gcc/swm_services/entity/MenuItemAccessEntity.java similarity index 63% rename from src/main/java/com/gcc/election/entity/MenuItemAccessEntity.java rename to src/main/java/com/gcc/swm_services/entity/MenuItemAccessEntity.java index 8303991..05ad0e4 100644 --- a/src/main/java/com/gcc/election/entity/MenuItemAccessEntity.java +++ b/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.Entity; @@ -17,114 +16,97 @@ public class MenuItemAccessEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - + @Column(name = "id", nullable = false) + private Integer id; + @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) - @JoinColumn(name = "menuitem_id", referencedColumnName = "id") - private MenuItemEntity menuItemId; - + @JoinColumn(name = "menuitem_id", referencedColumnName = "id") + private MenuItemEntity menuItemId; + @ManyToOne - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - + @JoinColumn(name = "module_id", referencedColumnName = "id") + private AppModuleEntity moduleId; + + @Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false") + private Boolean isDelete; + + @Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true") + private Boolean isActive; + + @Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0") + private Integer createdBy; + + @Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") + private String cDate; + public MenuItemAccessEntity() { - - } + } public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public AppUserGroupEntity getUserGroupId() { return userGroupId; } - public void setUserGroupId(AppUserGroupEntity userGroupId) { this.userGroupId = userGroupId; } - public MenuItemEntity getMenuItemId() { return menuItemId; } - public void setMenuItemId(MenuItemEntity menuItemId) { this.menuItemId = menuItemId; } - public AppModuleEntity getModuleId() { return moduleId; } - public void setModuleId(AppModuleEntity moduleId) { this.moduleId = moduleId; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/MenuItemEntity.java b/src/main/java/com/gcc/swm_services/entity/MenuItemEntity.java similarity index 61% rename from src/main/java/com/gcc/election/entity/MenuItemEntity.java rename to src/main/java/com/gcc/swm_services/entity/MenuItemEntity.java index 4724022..446413d 100644 --- a/src/main/java/com/gcc/election/entity/MenuItemEntity.java +++ b/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.Entity; @@ -17,151 +16,128 @@ public class MenuItemEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - + @Column(name = "id", nullable = false) + private Integer id; + @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "module_id", referencedColumnName = "id") - private AppModuleEntity moduleId; - - @Column(name = "name",nullable = false) - private String name; - - @Column(name = "url",nullable = false) - private String url; - - @Column(name = "icon",nullable = true) - private String icon; - - @Column(name = "orderby",nullable = false, columnDefinition = "INTEGER default 0") - private Integer orderby; - - @Column(name = "ishassub",nullable = false, columnDefinition = "Boolean default false") - private Boolean hasSub; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; - - + @JoinColumn(name = "module_id", referencedColumnName = "id") + private AppModuleEntity moduleId; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "url", nullable = false) + private String url; + + @Column(name = "icon", nullable = true) + private String icon; + + @Column(name = "orderby", nullable = false, columnDefinition = "INTEGER default 0") + private Integer orderby; + + @Column(name = "ishassub", nullable = false, columnDefinition = "Boolean default false") + private Boolean hasSub; + + @Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false") + private Boolean isDelete; + + @Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true") + private Boolean isActive; + + @Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0") + private Integer createdBy; + + @Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") + private String cDate; + public MenuItemEntity() { - - } + } public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public AppModuleEntity getModuleId() { return moduleId; } - public void setModuleId(AppModuleEntity moduleId) { this.moduleId = moduleId; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getUrl() { return url; } - public void setUrl(String url) { this.url = url; } - public String getIcon() { return icon; } - public Integer getOrderby() { return orderby; } - public void setOrderby(Integer orderby) { this.orderby = orderby; } - - + public void setIcon(String icon) { this.icon = icon; } - public Boolean getHasSub() { return hasSub; } - public void setHasSub(Boolean hasSub) { this.hasSub = hasSub; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/SubMenuItemAccessEntity.java b/src/main/java/com/gcc/swm_services/entity/SubMenuItemAccessEntity.java similarity index 64% rename from src/main/java/com/gcc/election/entity/SubMenuItemAccessEntity.java rename to src/main/java/com/gcc/swm_services/entity/SubMenuItemAccessEntity.java index dd9b34f..ebe8e59 100644 --- a/src/main/java/com/gcc/election/entity/SubMenuItemAccessEntity.java +++ b/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.Entity; @@ -17,129 +16,109 @@ public class SubMenuItemAccessEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - + @Column(name = "id", nullable = false) + private Integer id; + @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) - @JoinColumn(name = "submenuitem_id", referencedColumnName = "id") - private SubMenuItemEntity subMenuItemId; - + @JoinColumn(name = "submenuitem_id", referencedColumnName = "id") + private SubMenuItemEntity subMenuItemId; + @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) - @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 Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public AppUserGroupEntity getUserGroupId() { return userGroupId; } - public void setUserGroupId(AppUserGroupEntity userGroupId) { this.userGroupId = userGroupId; } - public SubMenuItemEntity getSubMenuItemId() { return subMenuItemId; } - public void setSubMenuItemId(SubMenuItemEntity subMenuItemId) { this.subMenuItemId = subMenuItemId; } - - public AppModuleEntity getModuleId() { return moduleId; } - public void setModuleId(AppModuleEntity moduleId) { this.moduleId = moduleId; } - public MenuItemEntity getMenuItemId() { return menuItemId; } - public void setMenuItemId(MenuItemEntity menuItemId) { this.menuItemId = menuItemId; } - public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } diff --git a/src/main/java/com/gcc/election/entity/SubMenuItemEntity.java b/src/main/java/com/gcc/swm_services/entity/SubMenuItemEntity.java similarity index 61% rename from src/main/java/com/gcc/election/entity/SubMenuItemEntity.java rename to src/main/java/com/gcc/swm_services/entity/SubMenuItemEntity.java index d0dee34..a569131 100644 --- a/src/main/java/com/gcc/election/entity/SubMenuItemEntity.java +++ b/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.Entity; @@ -18,163 +17,140 @@ public class SubMenuItemEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id",nullable = false) - private Integer id; - + @Column(name = "id", nullable = false) + private Integer id; + @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) - @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 Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } - public AppModuleEntity getModuleId() { return moduleId; } - public void setModuleId(AppModuleEntity moduleId) { this.moduleId = moduleId; } - public MenuItemEntity getMenuItemId() { return menuItemId; } - public void setMenuItemId(MenuItemEntity menuItemId) { this.menuItemId = menuItemId; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getUrl() { return url; } - public void setUrl(String url) { this.url = url; } - public String getIcon() { return icon; } - public void setIcon(String icon) { this.icon = icon; } - public Integer getOrderby() { return orderby; } - public void setOrderby(Integer orderby) { this.orderby = orderby; } - - + public Boolean getIsDelete() { return isDelete; } - public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } - public Boolean getIsActive() { return isActive; } - public void setIsActive(Boolean isActive) { this.isActive = isActive; } - public Integer getCreatedBy() { return createdBy; } - public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } - public String getcDate() { return cDate; } - public void setcDate(String cDate) { this.cDate = cDate; } + public Boolean getExtenalLink() { return extenalLink; } - public void setExtenalLink(Boolean extenalLink) { this.extenalLink = extenalLink; } diff --git a/src/main/java/com/gcc/election/entity/UserActivityLog.java b/src/main/java/com/gcc/swm_services/entity/UserActivityLog.java similarity index 79% rename from src/main/java/com/gcc/election/entity/UserActivityLog.java rename to src/main/java/com/gcc/swm_services/entity/UserActivityLog.java index f6fcff2..c2d0308 100644 --- a/src/main/java/com/gcc/election/entity/UserActivityLog.java +++ b/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 javax.persistence.Entity; @@ -9,23 +8,22 @@ import javax.persistence.Id; import javax.persistence.Table; - @Entity @Table(name = "user_activity_log") public class UserActivityLog { @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 Long getId() { diff --git a/src/main/java/com/gcc/election/entity/UserInfoEntity.java b/src/main/java/com/gcc/swm_services/entity/UserInfoEntity.java similarity index 65% rename from src/main/java/com/gcc/election/entity/UserInfoEntity.java rename to src/main/java/com/gcc/swm_services/entity/UserInfoEntity.java index 9e71da4..aedfe70 100644 --- a/src/main/java/com/gcc/election/entity/UserInfoEntity.java +++ b/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.Entity; @@ -8,39 +8,38 @@ import javax.persistence.Id; import javax.persistence.Table; - @Entity @Table(name = "userinfo") public class UserInfoEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "userid",nullable = false) - private Integer userid; + @Column(name = "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") - private String email; + private String email; @Column(name = "phone") - private String phone; - - @Column(name = "isdelete",nullable = false, columnDefinition = "Boolean default false") - private Boolean isDelete; - - @Column(name = "isactive",nullable = false, columnDefinition = "Boolean default true") - private Boolean isActive; - - @Column(name = "created_by",nullable = false, columnDefinition = "Integer Default 0") - private Integer createdBy; - - @Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") - private String cDate; + private String phone; + + @Column(name = "isdelete", nullable = false, columnDefinition = "Boolean default false") + private Boolean isDelete; + + @Column(name = "isactive", nullable = false, columnDefinition = "Boolean default true") + private Boolean isActive; + + @Column(name = "created_by", nullable = false, columnDefinition = "Integer Default 0") + private Integer createdBy; + + @Column(name = "cdate", nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP") + private String cDate; public UserInfoEntity() { - + } public Integer getUserid() { diff --git a/src/main/java/com/gcc/swm_services/interceptor/AppInterceptor.java b/src/main/java/com/gcc/swm_services/interceptor/AppInterceptor.java new file mode 100644 index 0000000..da83a1e --- /dev/null +++ b/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 getAppModuleAccessEntities; + List getMenuItemAccessEntities; + List getSubMenuItemAccessEntities; + + private AppModuleAccessRepository appModuleAccessRepository; + private MenuItemAccessRepository menuItemAccessRepository; + private SubMenuItemAccessRepository subMenuItemAccessRepository; + + List getAppModuleEntities; + List getMenuItemEntities; + List getSubMenuItemEntities; + + private AppModuleRepository appModuleRepository; + private MenuItemRepository menuItemRepository; + private SubMenuItemRepository subMenuItemRepository; + + private final Environment environment; + + @Autowired + public AppInterceptor(AppModuleAccessRepository appModuleAccessRepository, + MenuItemAccessRepository menuItemAccessRepository, + SubMenuItemAccessRepository subMenuItemAccessRepository, + AppModuleRepository appModuleRepository, + MenuItemRepository menuItemRepository, + SubMenuItemRepository subMenuItemRepository, + Environment environment) { + + this.appModuleAccessRepository = appModuleAccessRepository; + this.menuItemAccessRepository = menuItemAccessRepository; + this.subMenuItemAccessRepository = subMenuItemAccessRepository; + + this.appModuleRepository = appModuleRepository; + this.menuItemRepository = menuItemRepository; + this.subMenuItemRepository = subMenuItemRepository; + + this.environment = environment; + } + + private boolean isLoginPage(HttpServletRequest request) { + RequestMatcher loginPageMatcher = new AntPathRequestMatcher("/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); + } + } + } + } + } +} diff --git a/src/main/java/com/gcc/election/modeldata/ErrorResponse.java b/src/main/java/com/gcc/swm_services/modeldata/ErrorResponse.java similarity index 60% rename from src/main/java/com/gcc/election/modeldata/ErrorResponse.java rename to src/main/java/com/gcc/swm_services/modeldata/ErrorResponse.java index b4f0fa3..3f7366d 100644 --- a/src/main/java/com/gcc/election/modeldata/ErrorResponse.java +++ b/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 { - + 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() { super(); diff --git a/src/main/java/com/gcc/election/repository/AppModuleAccessRepository.java b/src/main/java/com/gcc/swm_services/repository/AppModuleAccessRepository.java similarity index 76% rename from src/main/java/com/gcc/election/repository/AppModuleAccessRepository.java rename to src/main/java/com/gcc/swm_services/repository/AppModuleAccessRepository.java index b28a61b..cb66907 100644 --- a/src/main/java/com/gcc/election/repository/AppModuleAccessRepository.java +++ b/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; @@ -10,31 +10,31 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.AppModuleAccessEntity; - - +import com.gcc.swm_services.entity.AppModuleAccessEntity; @Repository @Transactional -public interface AppModuleAccessRepository extends JpaRepository{ +public interface AppModuleAccessRepository extends JpaRepository { @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) - List findByUserGroupID(@Param("usergroup_id") String usergroup_id); - + List findByUserGroupID(@Param("usergroup_id") String usergroup_id); + @Query(value = "SELECT * FROM `modules_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) - List findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id); - + List findByAll(@Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id); + @Modifying @Query(value = "INSERT INTO `modules_access`(`module_id`, `usergroup_id`) VALUES (:module_id,:usergroup_id)", nativeQuery = true) void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); - + @Modifying @Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id", nativeQuery = true) - void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); - + void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id); + @Modifying @Query(value = "UPDATE `modules_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); diff --git a/src/main/java/com/gcc/swm_services/repository/AppModuleRepository.java b/src/main/java/com/gcc/swm_services/repository/AppModuleRepository.java new file mode 100644 index 0000000..774122d --- /dev/null +++ b/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 { + + @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) + Integer getLastInsertedId(); + + @Query(value = "SELECT * FROM `modules` WHERE `isactive`=1 AND `isdelete`=0 ORDER BY `orderby`", nativeQuery = true) + List showAll(); + + @Query(value = "SELECT * FROM `modules` WHERE `id` IN (:checkModuleid) AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id`", nativeQuery = true) + List showAllById(String[] checkModuleid); + + @Query(value = "SELECT * FROM `modules` WHERE (`module_path` = :module_path) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) + List findByModulePath(String module_path); +} diff --git a/src/main/java/com/gcc/election/repository/AppUserGroupRepository.java b/src/main/java/com/gcc/swm_services/repository/AppUserGroupRepository.java similarity index 63% rename from src/main/java/com/gcc/election/repository/AppUserGroupRepository.java rename to src/main/java/com/gcc/swm_services/repository/AppUserGroupRepository.java index f71532f..76f5460 100644 --- a/src/main/java/com/gcc/election/repository/AppUserGroupRepository.java +++ b/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.Query; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.AppUserGroupEntity; +import com.gcc.swm_services.entity.AppUserGroupEntity; import javax.transaction.Transactional; @Repository @Transactional -public interface AppUserGroupRepository extends JpaRepository{ +public interface AppUserGroupRepository extends JpaRepository { - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) + @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) Integer getLastInsertedId(); } diff --git a/src/main/java/com/gcc/election/repository/AppUserRepository.java b/src/main/java/com/gcc/swm_services/repository/AppUserRepository.java similarity index 75% rename from src/main/java/com/gcc/election/repository/AppUserRepository.java rename to src/main/java/com/gcc/swm_services/repository/AppUserRepository.java index 341d411..7a08f55 100644 --- a/src/main/java/com/gcc/election/repository/AppUserRepository.java +++ b/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; @@ -8,7 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.AppUserEntity; +import com.gcc.swm_services.entity.AppUserEntity; import javax.transaction.Transactional; @@ -16,13 +14,13 @@ import javax.transaction.Transactional; @Transactional public interface AppUserRepository extends JpaRepository { @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) - Integer getLastInsertedId(); - + Integer getLastInsertedId(); + @Query(value = "SELECT * FROM `appusers`", nativeQuery = true) - List showAll(); - + List showAll(); + @Query(value = "SELECT * FROM `appusers` WHERE (userid=:userId AND `isdelete`=0)", nativeQuery = true) - List showById(String userId); - + List showById(String userId); + AppUserEntity findByUsername(String username); } diff --git a/src/main/java/com/gcc/election/repository/MenuItemAccessRepository.java b/src/main/java/com/gcc/swm_services/repository/MenuItemAccessRepository.java similarity index 72% rename from src/main/java/com/gcc/election/repository/MenuItemAccessRepository.java rename to src/main/java/com/gcc/swm_services/repository/MenuItemAccessRepository.java index a32556b..08cd332 100644 --- a/src/main/java/com/gcc/election/repository/MenuItemAccessRepository.java +++ b/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; @@ -10,7 +8,7 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.MenuItemAccessEntity; +import com.gcc.swm_services.entity.MenuItemAccessEntity; import javax.transaction.Transactional; @@ -19,22 +17,26 @@ import javax.transaction.Transactional; public interface MenuItemAccessRepository extends JpaRepository { @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) - List findByUserGroupID(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id); - + List findByUserGroupID(@Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id); + @Query(value = "SELECT * FROM `menuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id); - + List findByAll(@Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id); + @Modifying @Query(value = "INSERT INTO `menuitem_access`(`menuitem_id`, `module_id`, `usergroup_id`) VALUES (:menuitem_id,:module_id,:usergroup_id)", nativeQuery = true) - void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id); - + void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, + @Param("menuitem_id") String menuitem_id); + @Modifying @Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id", nativeQuery = true) - void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id); - + void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id); + @Modifying @Query(value = "UPDATE `menuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); diff --git a/src/main/java/com/gcc/election/repository/MenuItemRepository.java b/src/main/java/com/gcc/swm_services/repository/MenuItemRepository.java similarity index 52% rename from src/main/java/com/gcc/election/repository/MenuItemRepository.java rename to src/main/java/com/gcc/swm_services/repository/MenuItemRepository.java index 587cb35..e209991 100644 --- a/src/main/java/com/gcc/election/repository/MenuItemRepository.java +++ b/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; @@ -9,7 +7,7 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.MenuItemEntity; +import com.gcc.swm_services.entity.MenuItemEntity; import javax.transaction.Transactional; @@ -17,15 +15,15 @@ import javax.transaction.Transactional; @Transactional public interface MenuItemRepository extends JpaRepository { - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) + @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) Integer getLastInsertedId(); - - @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true) + + @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true) List getMenuItemByModuleId(@Param("module_id") int module_id); - - @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`module_id`=:module_id AND `id` IN (:checkMenuid)) ORDER BY `orderby`", nativeQuery = true) + + @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`module_id`=:module_id AND `id` IN (:checkMenuid)) ORDER BY `orderby`", nativeQuery = true) List getMenuItemByModuleIdAccess(@Param("module_id") int module_id, String[] checkMenuid); - - @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`url`=:url) LIMIT 0,1", nativeQuery = true) + + @Query(value = "SELECT * FROM `menuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`url`=:url) LIMIT 0,1", nativeQuery = true) List findByUrl(@Param("url") String url); } diff --git a/src/main/java/com/gcc/election/repository/SubMenuItemAccessRepository.java b/src/main/java/com/gcc/swm_services/repository/SubMenuItemAccessRepository.java similarity index 66% rename from src/main/java/com/gcc/election/repository/SubMenuItemAccessRepository.java rename to src/main/java/com/gcc/swm_services/repository/SubMenuItemAccessRepository.java index e0e2e33..8056d42 100644 --- a/src/main/java/com/gcc/election/repository/SubMenuItemAccessRepository.java +++ b/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; @@ -8,34 +8,40 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.SubMenuItemAccessEntity; +import com.gcc.swm_services.entity.SubMenuItemAccessEntity; import javax.transaction.Transactional; @Repository @Transactional -public interface SubMenuItemAccessRepository extends JpaRepository{ +public interface SubMenuItemAccessRepository extends JpaRepository { @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) - List findByUserGroupID(@Param("usergroup_id") String usergroup_id); - + List findByUserGroupID(@Param("usergroup_id") String usergroup_id); + @Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id) AND (`isactive`=1 AND `isdelete`=0)", nativeQuery = true) - List findByUserGroupIDAccess(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id); - + List findByUserGroupIDAccess(@Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id); + @Query(value = "SELECT * FROM `submenuitem_access` WHERE (`usergroup_id`=:usergroup_id AND `module_id`=:module_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) - List findByAll(@Param("usergroup_id") String usergroup_id,@Param("module_id") String module_id,@Param("menuitem_id") String menuitem_id,@Param("submenuitem_id") String submenuitem_id); - + List findByAll(@Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, + @Param("submenuitem_id") String submenuitem_id); + @Modifying @Query(value = "INSERT INTO `submenuitem_access`(`submenuitem_id`, `menuitem_id`, `module_id`, `usergroup_id`) VALUES (:submenuitem_id, :menuitem_id, :module_id, :usergroup_id)", nativeQuery = true) - void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id); + void insert(@Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, + @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id); @Modifying @Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `module_id`=:module_id AND `usergroup_id`=:usergroup_id AND `menuitem_id`=:menuitem_id AND `submenuitem_id`=:submenuitem_id", nativeQuery = true) - void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, @Param("submenuitem_id") String submenuitem_id); - + void update(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id, + @Param("module_id") String module_id, @Param("menuitem_id") String menuitem_id, + @Param("submenuitem_id") String submenuitem_id); + @Modifying @Query(value = "UPDATE `submenuitem_access` SET `isactive`=:isactive WHERE `usergroup_id`=:usergroup_id", nativeQuery = true) void updateActiveStatus(@Param("isactive") Boolean isactive, @Param("usergroup_id") String usergroup_id); diff --git a/src/main/java/com/gcc/swm_services/repository/SubMenuItemRepository.java b/src/main/java/com/gcc/swm_services/repository/SubMenuItemRepository.java new file mode 100644 index 0000000..3365604 --- /dev/null +++ b/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 { + + @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) + Integer getLastInsertedId(); + + @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `module_id`=:module_id ORDER BY `orderby`", nativeQuery = true) + List getSubMenuItemByModuleId(@Param("module_id") int module_id); + + @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND `menuitem_id`=:menuitem_id ORDER BY `orderby`", nativeQuery = true) + List getSubMenuItemByMenuItemId(@Param("menuitem_id") int menuitem_id); + + @Query(value = "SELECT * FROM `submenuitem` WHERE (`isactive`=1 AND `isdelete`=0) AND (`menuitem_id`=:menuitem_id AND `id` IN (:checkSubMenuid)) ORDER BY `orderby`", nativeQuery = true) + List getSubMenuItemByMenuItemIdAccess(@Param("menuitem_id") int menuitem_id, + String[] checkSubMenuid); + + @Query(value = "SELECT * FROM `submenuitem` WHERE (`url`=:url) AND (`isactive`=1 AND `isdelete`=0) LIMIT 0,1", nativeQuery = true) + List findByUrl(@Param("url") String url); +} diff --git a/src/main/java/com/gcc/election/repository/UserActivityLogRepository.java b/src/main/java/com/gcc/swm_services/repository/UserActivityLogRepository.java similarity index 80% rename from src/main/java/com/gcc/election/repository/UserActivityLogRepository.java rename to src/main/java/com/gcc/swm_services/repository/UserActivityLogRepository.java index 7d05f5b..52f10d5 100644 --- a/src/main/java/com/gcc/election/repository/UserActivityLogRepository.java +++ b/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 org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import com.gcc.election.entity.UserActivityLog; +import com.gcc.swm_services.entity.UserActivityLog; import javax.transaction.Transactional; diff --git a/src/main/java/com/gcc/election/repository/UserInfoRepository.java b/src/main/java/com/gcc/swm_services/repository/UserInfoRepository.java similarity index 69% rename from src/main/java/com/gcc/election/repository/UserInfoRepository.java rename to src/main/java/com/gcc/swm_services/repository/UserInfoRepository.java index 301ecdc..e7f129c 100644 --- a/src/main/java/com/gcc/election/repository/UserInfoRepository.java +++ b/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.stereotype.Repository; @@ -10,7 +8,7 @@ import javax.transaction.Transactional; @Repository @Transactional public interface UserInfoRepository { - - @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) + + @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true) Integer getLastInsertedId(); } diff --git a/src/main/java/com/gcc/swm_services/service/Base64Util.java b/src/main/java/com/gcc/swm_services/service/Base64Util.java new file mode 100644 index 0000000..8db5396 --- /dev/null +++ b/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 ""; + } + } +} diff --git a/src/main/java/com/gcc/election/service/CustomUserDetails.java b/src/main/java/com/gcc/swm_services/service/CustomUserDetails.java similarity index 79% rename from src/main/java/com/gcc/election/service/CustomUserDetails.java rename to src/main/java/com/gcc/swm_services/service/CustomUserDetails.java index b3dc949..11466c4 100644 --- a/src/main/java/com/gcc/election/service/CustomUserDetails.java +++ b/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.userdetails.UserDetails; @@ -8,9 +7,9 @@ import java.io.Serializable; import java.util.Collection; 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 password; @@ -22,12 +21,12 @@ public class CustomUserDetails implements UserDetails, Serializable{ private Map additionalAttributes; public CustomUserDetails(String username, String password, - Collection authorities, - boolean accountNonExpired, - boolean accountNonLocked, - boolean credentialsNonExpired, - boolean enabled, - Map additionalAttributes) { + Collection authorities, + boolean accountNonExpired, + boolean accountNonLocked, + boolean credentialsNonExpired, + boolean enabled, + Map additionalAttributes) { this.username = username; this.password = password; this.authorities = authorities; diff --git a/src/main/java/com/gcc/election/service/CustomUserDetailsService.java b/src/main/java/com/gcc/swm_services/service/CustomUserDetailsService.java similarity index 54% rename from src/main/java/com/gcc/election/service/CustomUserDetailsService.java rename to src/main/java/com/gcc/swm_services/service/CustomUserDetailsService.java index f155fd4..82b6f9a 100644 --- a/src/main/java/com/gcc/election/service/CustomUserDetailsService.java +++ b/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.List; @@ -12,17 +12,17 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; 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 -public class CustomUserDetailsService implements UserDetailsService{ +public class CustomUserDetailsService implements UserDetailsService { - private final AppUserRepository appUserRepository; + private final AppUserRepository appUserRepository; private final UserActivityService userActivityService; @Autowired - public CustomUserDetailsService(AppUserRepository appUserRepository,UserActivityService userActivityService ) { + public CustomUserDetailsService(AppUserRepository appUserRepository, UserActivityService userActivityService) { this.appUserRepository = appUserRepository; this.userActivityService = userActivityService; } @@ -30,58 +30,57 @@ public class CustomUserDetailsService implements UserDetailsService{ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { AppUserEntity appUserEntity = appUserRepository.findByUsername(username); - + userActivityService.logUserActivity("0", "Trying to Login with Username: " + username); - //System.out.println(username); + // System.out.println(username); 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"); } - + /* - 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(); // Ensure that the role starts with "ROLE_" if (!userRole.startsWith("ROLE_")) { userRole = "ROLE_" + userRole; - //System.out.println("User Role: "+userRole); + // System.out.println("User Role: "+userRole); } - + // Create a SimpleGrantedAuthority for the user role SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole); - + // Create a list to hold the authority/role List authorityList = new ArrayList<>(); authorityList.add(authority); - + // Construct CustomUserDetails instance with custom attributes CustomUserDetails userDetails = new CustomUserDetails( - appUserEntity.getUsername(), - appUserEntity.getPassword(), - authorityList, - true, - true, - true, - true, - Map.of("userid",appUserEntity.getUserid().getUserid(), - "usergroupid",appUserEntity.getUsergroup_id().getId(), - "userrole",appUserEntity.getRoles().toString() - ) - ); - - userActivityService.logUserActivity(appUserEntity.getUserid().getUserid().toString(), "Login Success:
    Username: "+appUserEntity.getUsername() - +"
    Role: "+appUserEntity.getRoles().toString() - +"
    Access Group: "+appUserEntity.getUsergroup_id().getName() - +"
    Access Group ID: "+appUserEntity.getUsergroup_id().getId()); - + appUserEntity.getUsername(), + appUserEntity.getPassword(), + authorityList, + true, + true, + true, + true, + Map.of("userid", appUserEntity.getUserid().getUserid(), + "usergroupid", appUserEntity.getUsergroup_id().getId(), + "userrole", appUserEntity.getRoles().toString())); + + userActivityService.logUserActivity(appUserEntity.getUserid().getUserid().toString(), + "Login Success:
    Username: " + appUserEntity.getUsername() + + "
    Role: " + appUserEntity.getRoles().toString() + + "
    Access Group: " + appUserEntity.getUsergroup_id().getName() + + "
    Access Group ID: " + appUserEntity.getUsergroup_id().getId()); + return userDetails; } } diff --git a/src/main/java/com/gcc/election/service/LoginUserInfo.java b/src/main/java/com/gcc/swm_services/service/LoginUserInfo.java similarity index 58% rename from src/main/java/com/gcc/election/service/LoginUserInfo.java rename to src/main/java/com/gcc/swm_services/service/LoginUserInfo.java index e6d3f83..2c2706c 100644 --- a/src/main/java/com/gcc/election/service/LoginUserInfo.java +++ b/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.temporal.ChronoUnit; @@ -22,15 +22,14 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Service public class LoginUserInfo { - private JdbcTemplate jdbcAppTemplate; - private JdbcTemplate jdbcKuralTemplate; - - @Autowired - public void setDataSource(@Qualifier("mysqlAppDataSource") DataSource sosDataSource - ) { - 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() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { @@ -41,12 +40,12 @@ public class LoginUserInfo { } return null; } - + public static String getLoginUserId() { - UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); - + UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); + if (userDetails instanceof CustomUserDetails) { - //System.out.println("User Details : "+userDetails.toString()); + // System.out.println("User Details : "+userDetails.toString()); CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; Map additionalAttributes = customUserDetails.getAdditionalAttributes(); if (additionalAttributes != null) { @@ -57,17 +56,18 @@ public class LoginUserInfo { } } /* - for (Map.Entry entry : additionalAttributes.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - System.out.println("Key: " + key + ", Value: " + value); - }*/ + * for (Map.Entry 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() { - UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); + UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); if (userDetails instanceof CustomUserDetails) { CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; Map additionalAttributes = customUserDetails.getAdditionalAttributes(); @@ -78,11 +78,11 @@ public class LoginUserInfo { } } } - return null; + return null; } - + public static String getUserRole() { - UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); + UserDetails userDetails = LoginUserInfo.getCurrentUserDetails(); if (userDetails instanceof CustomUserDetails) { CustomUserDetails customUserDetails = (CustomUserDetails) userDetails; Map 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) { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // Query to get the stored encoded password for the given user ID String fetchPasswordQuery = "SELECT `password` FROM `appusers` WHERE `id` = ?"; - List> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{userid}); + List> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[] { userid }); if (result.isEmpty()) { // If no matching user is found, return an error message @@ -121,7 +121,8 @@ public class LoginUserInfo { // Update the password in the database String updateQuery = "UPDATE `appusers` SET `password` = ?, `pwd_txt` = ? WHERE `id` = ?"; - int rowsAffected = jdbcAppTemplate.update(updateQuery, new Object[]{encodedNewPassword, newPassword, userid}); + int rowsAffected = jdbcAppTemplate.update(updateQuery, + new Object[] { encodedNewPassword, newPassword, userid }); if (rowsAffected > 0) { // 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."; } } - - + public List> userCheck(String username, String password) { - - Integer statusCode=404; - String statusTxt="error"; - String msgTxt="User not found."; - - Map response = new HashMap<>(); - + + Integer statusCode = 404; + String statusTxt = "error"; + String msgTxt = "User not found."; + + Map response = new HashMap<>(); + BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // Query to get the stored encoded password for the given user ID - String fetchPasswordQuery = "SELECT `id`, `roles`, `usergroup_id`, `isactive`, `dname`, `password` as saltref FROM `appusers` WHERE `username` = ? AND (`isactive`=1 AND `isdelete`=0)"; - List> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[]{username}); - + String fetchPasswordQuery = "SELECT `id`, `roles`, `usergroup_id`, `isactive`, `username`, `password` as saltref FROM `appusers` WHERE `username` = ? AND (`isactive`=1 AND `isdelete`=0)"; + List> result = jdbcAppTemplate.queryForList(fetchPasswordQuery, new Object[] { username }); + if (result.isEmpty()) { - System.out.println(fetchPasswordQuery); + System.out.println(fetchPasswordQuery); // If no matching user is found, return an error message - msgTxt = "User not found."; - response.put("Data", Collections.emptyList()); - } - else { - - String storedEncodedPassword = (String) result.get(0).get("saltref"); - - // Verify the password against the stored encoded password - if (!passwordEncoder.matches(password, storedEncodedPassword)) { - msgTxt = "User not found."; - response.put("Data", Collections.emptyList()); - } - else { - statusCode=200; - statusTxt="success"; - msgTxt = "Login Successfully"; - if (result.isEmpty()) { - } else { - response.put("Data", result); - } - } + msgTxt = "User not found."; + response.put("Data", Collections.emptyList()); + } else { + + String storedEncodedPassword = (String) result.get(0).get("saltref"); + + // Verify the password against the stored encoded password + if (!passwordEncoder.matches(password, storedEncodedPassword)) { + msgTxt = "User not found."; + response.put("Data", Collections.emptyList()); + } else { + statusCode = 200; + statusTxt = "success"; + msgTxt = "Login Successfully"; + if (result.isEmpty()) { + } else { + response.put("Data", result); + } + } } response.put("statusCode", statusCode); - response.put("statusText", statusTxt); - response.put("message", msgTxt); - - return Collections.singletonList(response); + response.put("statusText", statusTxt); + response.put("message", msgTxt); + + return Collections.singletonList(response); } - + // Dashboard : தினம் ஒரு திருக்குறள் // thirukkural - -// public List> getDailyContent() { -// // Query to get all content from the table -// String contentQuery = "SELECT * FROM kural"; // Replace content_table with your actual table name -// List> contentList = jdbcKuralTemplate.queryForList(contentQuery); -// -// // Total number of records -// int totalRecords = contentList.size(); -// -// if (totalRecords == 0) { -// // If there are no records, return an empty list -// return Collections.emptyList(); -// } -// -// // Calculate the number of days since a specific start date (e.g., October 21, 2024) -// LocalDate startDate = LocalDate.of(2024, 10, 21); -// LocalDate currentDate = LocalDate.now(); -// long daysSinceStart = ChronoUnit.DAYS.between(startDate, currentDate); -// -// // Get the content index for today (using modulo to cycle through the records) -// int contentIndex = (int) (daysSinceStart % totalRecords); -// -// // Return the content for today as a list -// return Collections.singletonList(contentList.get(contentIndex)); -// } + + // public List> getDailyContent() { + // // Query to get all content from the table + // String contentQuery = "SELECT * FROM kural"; // Replace content_table with + // your actual table name + // List> contentList = + // jdbcKuralTemplate.queryForList(contentQuery); + // + // // Total number of records + // int totalRecords = contentList.size(); + // + // if (totalRecords == 0) { + // // If there are no records, return an empty list + // return Collections.emptyList(); + // } + // + // // Calculate the number of days since a specific start date (e.g., October + // 21, 2024) + // LocalDate startDate = LocalDate.of(2024, 10, 21); + // LocalDate currentDate = LocalDate.now(); + // long daysSinceStart = ChronoUnit.DAYS.between(startDate, currentDate); + // + // // Get the content index for today (using modulo to cycle through the + // records) + // int contentIndex = (int) (daysSinceStart % totalRecords); + // + // // Return the content for today as a list + // return Collections.singletonList(contentList.get(contentIndex)); + // } } diff --git a/src/main/java/com/gcc/election/service/UserActivityService.java b/src/main/java/com/gcc/swm_services/service/UserActivityService.java similarity index 76% rename from src/main/java/com/gcc/election/service/UserActivityService.java rename to src/main/java/com/gcc/swm_services/service/UserActivityService.java index a76b1cc..add5f42 100644 --- a/src/main/java/com/gcc/election/service/UserActivityService.java +++ b/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.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; @Service public class UserActivityService { - private final UserActivityLogRepository userActivityLogRepository; + private final UserActivityLogRepository userActivityLogRepository; @Autowired public UserActivityService(UserActivityLogRepository userActivityLogRepository) { diff --git a/src/main/java/com/gcc/election/service/UserActivityTimelineService.java b/src/main/java/com/gcc/swm_services/service/UserActivityTimelineService.java similarity index 70% rename from src/main/java/com/gcc/election/service/UserActivityTimelineService.java rename to src/main/java/com/gcc/swm_services/service/UserActivityTimelineService.java index 05f51e8..fa90080 100644 --- a/src/main/java/com/gcc/election/service/UserActivityTimelineService.java +++ b/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.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; @Service public class UserActivityTimelineService { -private final UserActivityLogRepository userActivityLogRepository; - + private final UserActivityLogRepository userActivityLogRepository; + @Autowired public UserActivityTimelineService(UserActivityLogRepository userActivityLogRepository) { this.userActivityLogRepository = userActivityLogRepository; diff --git a/src/main/java/com/gcc/swm_services/swm/controller/AdminController.java b/src/main/java/com/gcc/swm_services/swm/controller/AdminController.java new file mode 100644 index 0000000..f83ddf7 --- /dev/null +++ b/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"; + } + +} diff --git a/src/main/java/com/gcc/swm_services/swm/controller/DropDownApiController.java b/src/main/java/com/gcc/swm_services/swm/controller/DropDownApiController.java new file mode 100644 index 0000000..dfc0af0 --- /dev/null +++ b/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> getFacilitiesTypeList() { + return dropDownService.getFacilitiesTypeList(); + } + + @GetMapping("/getzoneslist") + public List> getZonesList() { + return dropDownService.getZonesList(); + } + +} diff --git a/src/main/java/com/gcc/swm_services/swm/controller/MainController.java b/src/main/java/com/gcc/swm_services/swm/controller/MainController.java new file mode 100644 index 0000000..b689b74 --- /dev/null +++ b/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"; + } +} diff --git a/src/main/java/com/gcc/swm_services/swm/controller/SwmAdminApiController.java b/src/main/java/com/gcc/swm_services/swm/controller/SwmAdminApiController.java new file mode 100644 index 0000000..a4820f6 --- /dev/null +++ b/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))); + } +} diff --git a/src/main/java/com/gcc/swm_services/swm/controller/SwmApiController.java b/src/main/java/com/gcc/swm_services/swm/controller/SwmApiController.java new file mode 100644 index 0000000..6261fa6 --- /dev/null +++ b/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> data = addDetailsService.getZoneWiseFacilityByLogin( + username, fromDate, toDate); + + return ResponseEntity.ok(Map.of( + "status", "SUCCESS", + "data", data)); + } + +} diff --git a/src/main/java/com/gcc/swm_services/swm/service/AddDetailsService.java b/src/main/java/com/gcc/swm_services/swm/service/AddDetailsService.java new file mode 100644 index 0000000..fdddd55 --- /dev/null +++ b/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 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 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 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> 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> 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); + } + +} diff --git a/src/main/java/com/gcc/swm_services/swm/service/DropDownService.java b/src/main/java/com/gcc/swm_services/swm/service/DropDownService.java new file mode 100644 index 0000000..5e40e51 --- /dev/null +++ b/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> getFacilitiesTypeList() { + String sql = " SELECT * FROM facilities_type where is_active = '1' and is_delete ='0' "; + return jdbcTemplate.queryForList(sql); + } + + public List> getZonesList() { + String sql = " SELECT * FROM zones where is_active = '1' and is_delete ='0' "; + return jdbcTemplate.queryForList(sql); + } + +} diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index 995b381..65511b6 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -1,5 +1,5 @@ assets.base-url=/assets/ -fileBaseUrl=http://localhost:8080 +fileBaseUrl=http://localhost:8060 #fileBaseUrl = D:/Projects/Election_Project/election_v1/gcc_election_uploads \ No newline at end of file diff --git a/src/main/resources/application-prod.properties b/src/main/resources/application-prod.properties index bfe2aad..051b60c 100644 --- a/src/main/resources/application-prod.properties +++ b/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 \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 118cc4b..66d69e0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,7 +2,7 @@ spring.profiles.active=dev #spring.profiles.active=prod # Spring properties -spring.application.name=election +spring.application.name=swm_login spring.datasource.hikari.connection-timeout=30000 @@ -15,7 +15,7 @@ spring.servlet.multipart.max-file-size=20MB spring.servlet.multipart.max-request-size=20MB # HTTP Server -server.port = 8080 +server.port = 8060 #server.servlet.context-path=/gccoffice server.error.include-stacktrace= on_param # Hibernate logging diff --git a/src/main/resources/templates/fragments/modules/base/footer.html b/src/main/resources/templates/fragments/modules/base/footer.html index 822d68a..f963c43 100644 --- a/src/main/resources/templates/fragments/modules/base/footer.html +++ b/src/main/resources/templates/fragments/modules/base/footer.html @@ -1,7 +1,7 @@ -
    - -
    - Copyright © Greater Chennai Corporation | All rights reserved - -
    -
    \ No newline at end of file +
    + +
    + Copyright © Greater Chennai Corporation | All rights reserved + +
    +
    \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/base/head.html b/src/main/resources/templates/fragments/modules/base/head.html index eac4a1d..880ff42 100644 --- a/src/main/resources/templates/fragments/modules/base/head.html +++ b/src/main/resources/templates/fragments/modules/base/head.html @@ -1,351 +1,592 @@ + + + + GCC SWM_LOGIN APP + + + - - - - GCC Election APP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - \ No newline at end of file + .cursure_poiter { + cursor: pointer; + } + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/base/header.html b/src/main/resources/templates/fragments/modules/base/header.html index 0dcbc25..eaa10ef 100644 --- a/src/main/resources/templates/fragments/modules/base/header.html +++ b/src/main/resources/templates/fragments/modules/base/header.html @@ -1,26 +1,26 @@ -
    -
    -
    +
    +
    +
    -
    - - - -
    - -
    - Polling Personnel Data Management System -
    - -
    - + +
    + +
    + Solid Waste Management System +
    + +
    + - - - - - -
    + Logout + Password Reset
    -
    \ No newline at end of file + +
    +
    + +
    \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/base/login-head.html b/src/main/resources/templates/fragments/modules/base/login-head.html index fc12ce4..267edf2 100644 --- a/src/main/resources/templates/fragments/modules/base/login-head.html +++ b/src/main/resources/templates/fragments/modules/base/login-head.html @@ -1,352 +1,593 @@ + + + + GCC RDO_LOGIN APP + + + - - - - GCC Election APP - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - \ No newline at end of file + .cursure_poiter { + cursor: pointer; + } + + \ No newline at end of file diff --git a/src/main/resources/templates/fragments/modules/base/script.html b/src/main/resources/templates/fragments/modules/base/script.html index 942da54..fbf623e 100644 --- a/src/main/resources/templates/fragments/modules/base/script.html +++ b/src/main/resources/templates/fragments/modules/base/script.html @@ -37,339 +37,339 @@ -
    - -
    - - -
    - -
    - -
    -
    -