All GCC vendors and employee details for IT department management
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

632 lines
25 KiB

package com.gcc_manpower.controller;
import com.gcc_manpower.service.AppUserService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@Controller
@RequestMapping("/")
public class HomeController {
@Autowired
private AppUserService appUserService;
@Value("${upload.path:gcc_manpower_uploads}")
private String uploadPathConfig;
private void addSummaryStats(Model model, List<Map<String, Object>> vendorDetails) {
int totalVendors = vendorDetails.size();
int totalTenderCount = appUserService.getOverallTenderCount();
int totalExistingCount = appUserService.getOverallActiveEmployeeCount();
int totalVacantCount = 0;
for (Map<String, Object> vendor : vendorDetails) {
List<Map<String, Object>> designations = (List<Map<String, Object>>) vendor.get("designationDetails");
if (designations != null) {
for (Map<String, Object> des : designations) {
Object vacantObj = des.get("vacant_count");
if (vacantObj != null) {
try {
double val = Double.parseDouble(String.valueOf(vacantObj).trim());
if (val > 0) {
totalVacantCount += (int) val;
}
} catch (NumberFormatException ignored) {
}
}
}
}
}
model.addAttribute("totalVendors", totalVendors);
model.addAttribute("totalTenderCount", totalTenderCount);
model.addAttribute("totalExistingCount", totalExistingCount);
model.addAttribute("totalVacantCount", totalVacantCount);
}
@GetMapping("/")
public String home(Model model, HttpSession session) {
String usrName = (String) session.getAttribute("usrName");
if (usrName == null) {
return "redirect:/login";
}
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
List<Map<String, Object>> vendorDetails = appUserService.getVendorDetailsWithCounts();
addSummaryStats(model, vendorDetails);
model.addAttribute("curPage", "home");
model.addAttribute("isAdmin", isAdmin);
model.addAttribute("urls", new ArrayList<>()); // default empty services
model.addAttribute("vendorDetails", vendorDetails);
model.addAttribute("locations", appUserService.getActiveLocations());
model.addAttribute("designations", appUserService.getActiveDesignations());
model.addAttribute("userTypes", appUserService.getActiveUserTypes());
return "home/home";
}
@GetMapping("/login")
public String login(HttpSession session) {
// If already logged in, redirect to the home page
if (session.getAttribute("usrName") != null) {
return "redirect:/";
}
return "home/login";
}
@PostMapping("/api/val-app-usr-login")
@ResponseBody
public Map<String, Object> validateAppUserLogin(
@RequestParam("usrName") String usrName,
@RequestParam("usrPass") String usrPass,
HttpSession session) {
Map<String, Object> authResult = appUserService.authenticate(usrName, usrPass);
Map<String, Object> response = new HashMap<>();
if (Boolean.TRUE.equals(authResult.get("success"))) {
session.setAttribute("usrName", authResult.get("usrName"));
session.setAttribute("usrRole", authResult.get("usrRole"));
session.setMaxInactiveInterval(600); // 10 minutes session timeout
response.put("result", true);
response.put("usrName", authResult.get("usrName"));
} else {
response.put("result", false);
response.put("error", authResult.get("error"));
}
return response;
}
@PostMapping("/api/get-role")
@ResponseBody
public Map<String, Object> getRole(HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
if (usrName == null) {
response.put("authenticated", false);
response.put("isAdmin", false);
} else {
response.put("authenticated", true);
response.put("isAdmin", "ADMIN".equalsIgnoreCase(usrRole));
}
return response;
}
@GetMapping("/redirect")
public String redirect() {
return "redirect:/";
}
@GetMapping("/view-login-det")
public String viewLoginDetails(Model model, HttpSession session) {
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
if (usrName == null) {
return "redirect:/login";
}
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
// Fetch exact spreadsheet rows dynamically from MySQL using JdbcTemplate
List<Map<String, Object>> manpowerEntries = appUserService.getManpowerTenders();
List<Map<String, Object>> vendorDetails = appUserService.getVendorDetailsWithCounts();
model.addAttribute("curPage", "view-login-det");
model.addAttribute("isAdmin", isAdmin);
model.addAttribute("manpowerEntries", manpowerEntries);
model.addAttribute("vendorDetails", vendorDetails);
model.addAttribute("designations", appUserService.getActiveDesignations());
return "home/view-login-details";
}
@GetMapping("/api/vendor-employees")
@ResponseBody
public List<Map<String, Object>> getVendorEmployees(
@RequestParam("vendorName") String vendorName) {
return appUserService.getEmployeesByVendor(vendorName);
}
@GetMapping("/api/employee/history")
@ResponseBody
public List<Map<String, Object>> getEmployeeHistory(
@RequestParam("empCode") String empCode) {
return appUserService.getEmployeeHistory(empCode);
}
@GetMapping("/api/all-employees")
@ResponseBody
public List<Map<String, Object>> getAllEmployees() {
return appUserService.getAllEmployees();
}
@PostMapping("/api/save-manpower-stats")
@ResponseBody
public Map<String, Object> saveManpowerStats(
@RequestBody List<Map<String, Object>> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
if (usrName == null) {
response.put("success", false);
response.put("error", "Unauthorized access! Please log in.");
return response;
}
try {
boolean overallSuccess = true;
for (Map<String, Object> row : payload) {
int id = ((Number) row.get("id")).intValue();
int availableCount = ((Number) row.get("availableCount")).intValue();
String vacantRemarks = (String) row.get("vacantRemarks");
boolean rowSuccess = appUserService.updateManpowerTender(id, availableCount, vacantRemarks);
if (!rowSuccess) {
overallSuccess = false;
}
}
response.put("success", overallSuccess);
} catch (Exception e) {
response.put("success", false);
response.put("error", "Failed to save statistics: " + e.getMessage());
}
return response;
}
@GetMapping("/api/employee")
@ResponseBody
public Map<String, Object> getEmployeeByCode(
@RequestParam("empCode") String empCode,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
if (usrName == null) {
response.put("success", false);
response.put("error", "Unauthorized access! Please log in.");
return response;
}
Map<String, Object> emp = appUserService.getEmployeeByCode(empCode);
if (emp != null) {
response.put("success", true);
response.put("employee", emp);
} else {
response.put("success", false);
response.put("error", "Employee not found or inactive.");
}
return response;
}
@PostMapping("/api/employee/add")
@ResponseBody
public Map<String, Object> addEmployee(
@RequestBody Map<String, Object> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
boolean success = appUserService.addEmployee(payload, usrName);
if (success) {
response.put("success", true);
response.put("message", "Employee registered successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to register employee. The employee code might already exist.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@PostMapping("/api/employee/update")
@ResponseBody
public Map<String, Object> updateEmployee(
@RequestBody Map<String, Object> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
boolean success = appUserService.updateEmployee(payload, usrName);
if (success) {
response.put("success", true);
response.put("message", "Employee updated successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to update employee details. Record not found or inactive.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@PostMapping("/api/vendor/add-work-order")
@ResponseBody
public Map<String, Object> addVendorWorkOrder(
@RequestParam("vendorType") String vendorType,
@RequestParam(value = "vendorId", required = false) String vendorIdStr,
@RequestParam(value = "vendorName", required = false) String vendorName,
@RequestParam("description") String description,
@RequestParam("contractorName") String contractorName,
@RequestParam("fileNo") String fileNo,
@RequestParam("subject") String subject,
@RequestParam("issueDate") String issueDate,
@RequestParam("endDate") String endDate,
@RequestParam("totalEmployees") String totalEmployees,
@RequestParam(value = "orderby", required = false) Integer orderby,
@RequestParam(value = "file", required = false) MultipartFile file,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
// Convert to uppercase for Contractor Name and File No
if (contractorName != null) {
contractorName = contractorName.toUpperCase();
}
if (fileNo != null) {
fileNo = fileNo.toUpperCase();
}
long finalVendorId = 0;
if ("new".equalsIgnoreCase(vendorType)) {
// Check if vendor name already exists
List<Map<String, Object>> existingVendors = appUserService.getVendorDetailsWithCounts();
boolean vendorExists = false;
for (Map<String, Object> v : existingVendors) {
String vName = (String) v.get("vendor_name");
if (vName != null && vName.equalsIgnoreCase(vendorName)) {
vendorExists = true;
break;
}
}
if (vendorExists) {
response.put("success", false);
response.put("error", "A vendor with this name already exists.");
return response;
}
// Insert into vendor_details
finalVendorId = appUserService.addVendor(vendorName, description, totalEmployees, orderby);
if (finalVendorId == 0) {
response.put("success", false);
response.put("error", "Failed to create new vendor details.");
return response;
}
} else {
if (vendorIdStr == null || vendorIdStr.trim().isEmpty()) {
response.put("success", false);
response.put("error", "No existing vendor selected.");
return response;
}
try {
finalVendorId = Long.parseLong(vendorIdStr);
} catch (NumberFormatException e) {
response.put("success", false);
response.put("error", "Invalid vendor ID formatting.");
return response;
}
}
// Save upload file (mandatory validation)
if (file == null || file.isEmpty()) {
response.put("success", false);
response.put("error", "Work order PDF file is required.");
return response;
}
File uploadDir = new File(uploadPathConfig).getAbsoluteFile();
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
String originalFilename = file.getOriginalFilename();
String nameWithoutExt = "";
String ext = ".pdf";
if (originalFilename != null && originalFilename.contains(".")) {
int dotIdx = originalFilename.lastIndexOf(".");
nameWithoutExt = originalFilename.substring(0, dotIdx);
ext = originalFilename.substring(dotIdx);
} else {
nameWithoutExt = originalFilename != null ? originalFilename : "file";
}
nameWithoutExt = nameWithoutExt.replaceAll("[^a-zA-Z0-9-_]", "_");
String savedFilename = nameWithoutExt + "_" + System.currentTimeMillis() + ext;
File destFile = new File(uploadDir, savedFilename).getAbsoluteFile();
file.transferTo(destFile);
String fileWebUrl = "/gcc_manpower_uploads/" + savedFilename;
// Insert into vendor_details_work_order
boolean success = appUserService.addVendorWorkOrder(
String.valueOf(finalVendorId),
description,
contractorName,
fileNo,
subject,
issueDate,
endDate,
totalEmployees,
orderby,
fileWebUrl,
usrName);
if (success) {
// If it's an existing vendor, add total_employees to vendor_details
if (!"new".equalsIgnoreCase(vendorType)) {
int addedEmployees = 0;
if (totalEmployees != null) {
try {
addedEmployees = Integer.parseInt(totalEmployees.trim());
} catch (NumberFormatException ignored) {
}
}
if (addedEmployees > 0) {
appUserService.updateVendorTotalEmployees(String.valueOf(finalVendorId), addedEmployees);
}
}
response.put("success", true);
response.put("message", "Vendor work order saved successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to register vendor work order.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@PostMapping("/api/employee/delete")
@ResponseBody
public Map<String, Object> deleteEmployee(
@RequestBody Map<String, Object> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
String empCode = (String) payload.get("empCode");
if (empCode == null || empCode.trim().isEmpty()) {
response.put("success", false);
response.put("error", "Employee code is required.");
return response;
}
boolean success = appUserService.deleteEmployee(empCode, usrName);
if (success) {
response.put("success", true);
response.put("message", "Employee deleted successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to delete employee or record not found.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@PostMapping("/api/vendor/delete")
@ResponseBody
public Map<String, Object> deleteVendor(
@RequestBody Map<String, Object> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
Object idObj = payload.get("id");
if (idObj == null) {
response.put("success", false);
response.put("error", "Vendor ID is required.");
return response;
}
String idStr = String.valueOf(idObj);
boolean success = appUserService.deleteVendor(idStr);
if (success) {
response.put("success", true);
response.put("message", "Vendor and associated records deleted successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to delete vendor or record not found.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@PostMapping("/api/vendor/delete-work-order")
@ResponseBody
public Map<String, Object> deleteWorkOrder(
@RequestBody Map<String, Object> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
Object idObj = payload.get("workOrderId");
if (idObj == null) {
response.put("success", false);
response.put("error", "Work order ID is required.");
return response;
}
String workOrderId = String.valueOf(idObj);
boolean success = appUserService.deleteWorkOrder(workOrderId, usrName);
if (success) {
response.put("success", true);
response.put("message", "Work order deleted successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to delete work order or record not found.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@GetMapping("/api/vendor-employees-all")
@ResponseBody
public List<Map<String, Object>> getVendorEmployeesAll(
@RequestParam("vendorIdOrName") String vendorIdOrName) {
return appUserService.getEmployeesByVendorAll(vendorIdOrName);
}
@PostMapping("/api/employee/restore")
@ResponseBody
public Map<String, Object> restoreEmployee(
@RequestBody Map<String, Object> payload,
HttpSession session) {
Map<String, Object> response = new HashMap<>();
String usrName = (String) session.getAttribute("usrName");
String usrRole = (String) session.getAttribute("usrRole");
boolean isAdmin = "ADMIN".equalsIgnoreCase(usrRole);
if (usrName == null || !isAdmin) {
response.put("success", false);
response.put("error", "Unauthorized! Admin access required.");
return response;
}
try {
String empCode = (String) payload.get("empCode");
if (empCode == null || empCode.trim().isEmpty()) {
response.put("success", false);
response.put("error", "Employee code is required.");
return response;
}
boolean success = appUserService.restoreEmployee(empCode, usrName);
if (success) {
response.put("success", true);
response.put("message", "Employee restored successfully!");
} else {
response.put("success", false);
response.put("error", "Failed to restore employee or record not found.");
}
} catch (Exception e) {
response.put("success", false);
response.put("error", "Error: " + e.getMessage());
}
return response;
}
@GetMapping("/api/all-employees-with-deleted")
@ResponseBody
public List<Map<String, Object>> getAllEmployeesWithDeleted() {
return appUserService.getAllEmployeesWithDeleted();
}
@PostMapping("/usr-logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/login";
}
}