修改用户角色,添加管理员相关逻辑
This commit is contained in:
@@ -0,0 +1,138 @@
|
|||||||
|
package com.light.delivery.controller;
|
||||||
|
|
||||||
|
import com.light.delivery.model.Employee;
|
||||||
|
import com.light.delivery.model.User;
|
||||||
|
import com.light.delivery.model.UserRole;
|
||||||
|
import com.light.delivery.service.EmployeeService;
|
||||||
|
import com.light.delivery.service.UserService;
|
||||||
|
import com.light.delivery.service.impl.UserServiceImpl;
|
||||||
|
import com.light.delivery.util.JwtUtil;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 员工管理控制器,提供员工信息的增删改查功能。
|
||||||
|
* 仅限管理员角色访问。
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/employees")
|
||||||
|
public class EmployeeController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeService employeeService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserService userService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JwtUtil jwtUtil;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserServiceImpl userServiceImpl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有员工列表
|
||||||
|
* @return 员工信息列表
|
||||||
|
*/
|
||||||
|
@GetMapping
|
||||||
|
public ResponseEntity<?> getAllEmployees(HttpServletRequest request) {
|
||||||
|
try {
|
||||||
|
User user = getUserFromToken(request);
|
||||||
|
UserRole userRole = userServiceImpl.getUserRole(user);
|
||||||
|
if (!UserRole.ADMIN.equals(userRole)) {
|
||||||
|
return ResponseEntity.status(403).body("权限不足,仅管理员可访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Employee> employees = employeeService.getAllEmployees();
|
||||||
|
return ResponseEntity.ok(employees);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(401).body("认证失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加新员工
|
||||||
|
* @param employee 员工信息
|
||||||
|
* @return 添加结果
|
||||||
|
*/
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<?> addEmployee(@RequestBody Employee employee, HttpServletRequest request) {
|
||||||
|
try {
|
||||||
|
User user = getUserFromToken(request);
|
||||||
|
UserRole userRole = userServiceImpl.getUserRole(user);
|
||||||
|
if (!UserRole.ADMIN.equals(userRole)) {
|
||||||
|
return ResponseEntity.status(403).body("权限不足,仅管理员可访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
Employee savedEmployee = employeeService.saveEmployee(employee);
|
||||||
|
return ResponseEntity.ok(savedEmployee);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(401).body("认证失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新员工信息
|
||||||
|
* @param id 员工ID
|
||||||
|
* @param employee 员工信息
|
||||||
|
* @return 更新结果
|
||||||
|
*/
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ResponseEntity<?> updateEmployee(@PathVariable Long id, @RequestBody Employee employee, HttpServletRequest request) {
|
||||||
|
try {
|
||||||
|
User user = getUserFromToken(request);
|
||||||
|
UserRole userRole = userServiceImpl.getUserRole(user);
|
||||||
|
if (!UserRole.ADMIN.equals(userRole)) {
|
||||||
|
return ResponseEntity.status(403).body("权限不足,仅管理员可访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
Employee updatedEmployee = employeeService.updateEmployee(id, employee);
|
||||||
|
if (updatedEmployee == null) {
|
||||||
|
return ResponseEntity.status(404).body("员工不存在");
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok(updatedEmployee);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(401).body("认证失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除员工
|
||||||
|
* @param id 员工ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ResponseEntity<?> deleteEmployee(@PathVariable Long id, HttpServletRequest request) {
|
||||||
|
try {
|
||||||
|
User user = getUserFromToken(request);
|
||||||
|
UserRole userRole = userServiceImpl.getUserRole(user);
|
||||||
|
if (!UserRole.ADMIN.equals(userRole)) {
|
||||||
|
return ResponseEntity.status(403).body("权限不足,仅管理员可访问");
|
||||||
|
}
|
||||||
|
|
||||||
|
employeeService.deleteEmployee(id);
|
||||||
|
return ResponseEntity.ok("员工删除成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(401).body("认证失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从请求中提取用户信息
|
||||||
|
* @param request HTTP请求
|
||||||
|
* @return 用户对象
|
||||||
|
*/
|
||||||
|
private User getUserFromToken(HttpServletRequest request) {
|
||||||
|
String bearerToken = request.getHeader("Authorization");
|
||||||
|
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
|
||||||
|
String token = bearerToken.substring(7);
|
||||||
|
String openid = jwtUtil.extractUsername(token);
|
||||||
|
return userService.getUserInfo(token);
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Authorization token is missing");
|
||||||
|
}
|
||||||
|
}
|
15
src/main/java/com/light/delivery/dto/EmployeeDto.java
Normal file
15
src/main/java/com/light/delivery/dto/EmployeeDto.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package com.light.delivery.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 员工信息DTO,用于员工信息的传输
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class EmployeeDto {
|
||||||
|
private Long id;
|
||||||
|
private String name;
|
||||||
|
private String phone;
|
||||||
|
private String role;
|
||||||
|
private String openid;
|
||||||
|
}
|
@@ -0,0 +1,49 @@
|
|||||||
|
package com.light.delivery.exception;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局异常处理器,用于统一处理系统中的异常
|
||||||
|
*/
|
||||||
|
@ControllerAdvice
|
||||||
|
public class GlobalExceptionHandler {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理权限不足异常
|
||||||
|
*/
|
||||||
|
@ExceptionHandler(SecurityException.class)
|
||||||
|
public ResponseEntity<Map<String, String>> handleSecurityException(SecurityException e) {
|
||||||
|
Map<String, String> errorResponse = new HashMap<>();
|
||||||
|
errorResponse.put("error", "权限不足");
|
||||||
|
errorResponse.put("message", e.getMessage());
|
||||||
|
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理非法参数异常
|
||||||
|
*/
|
||||||
|
@ExceptionHandler(IllegalArgumentException.class)
|
||||||
|
public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException e) {
|
||||||
|
Map<String, String> errorResponse = new HashMap<>();
|
||||||
|
errorResponse.put("error", "参数错误");
|
||||||
|
errorResponse.put("message", e.getMessage());
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理通用异常
|
||||||
|
*/
|
||||||
|
@ExceptionHandler(Exception.class)
|
||||||
|
public ResponseEntity<Map<String, String>> handleGenericException(Exception e) {
|
||||||
|
Map<String, String> errorResponse = new HashMap<>();
|
||||||
|
errorResponse.put("error", "系统错误");
|
||||||
|
errorResponse.put("message", e.getMessage());
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,52 @@
|
|||||||
|
package com.light.delivery.service;
|
||||||
|
|
||||||
|
import com.light.delivery.dto.EmployeeDto;
|
||||||
|
import com.light.delivery.model.Employee;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 员工服务接口,定义员工相关的业务操作。
|
||||||
|
*/
|
||||||
|
public interface EmployeeService {
|
||||||
|
/**
|
||||||
|
* 获取所有员工信息
|
||||||
|
* @return 员工列表
|
||||||
|
*/
|
||||||
|
List<Employee> getAllEmployees();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存员工信息
|
||||||
|
* @param employee 员工信息
|
||||||
|
* @return 保存后的员工信息
|
||||||
|
*/
|
||||||
|
Employee saveEmployee(Employee employee);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新员工信息
|
||||||
|
* @param id 员工ID
|
||||||
|
* @param employee 员工信息
|
||||||
|
* @return 更新后的员工信息
|
||||||
|
*/
|
||||||
|
Employee updateEmployee(Long id, Employee employee);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除员工
|
||||||
|
* @param id 员工ID
|
||||||
|
*/
|
||||||
|
void deleteEmployee(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将Employee实体转换为EmployeeDto
|
||||||
|
* @param employee 员工实体
|
||||||
|
* @return 员工DTO
|
||||||
|
*/
|
||||||
|
EmployeeDto toDto(Employee employee);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将EmployeeDto转换为Employee实体
|
||||||
|
* @param dto 员工DTO
|
||||||
|
* @return 员工实体
|
||||||
|
*/
|
||||||
|
Employee toEntity(EmployeeDto dto);
|
||||||
|
}
|
@@ -0,0 +1,80 @@
|
|||||||
|
package com.light.delivery.service.impl;
|
||||||
|
|
||||||
|
import com.light.delivery.dto.EmployeeDto;
|
||||||
|
import com.light.delivery.model.Employee;
|
||||||
|
import com.light.delivery.repository.EmployeeRepository;
|
||||||
|
import com.light.delivery.service.EmployeeService;
|
||||||
|
import org.springframework.beans.BeanUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 员工服务实现类,处理员工相关的业务逻辑。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class EmployeeServiceImpl implements EmployeeService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Employee> getAllEmployees() {
|
||||||
|
return employeeRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Employee saveEmployee(Employee employee) {
|
||||||
|
return employeeRepository.save(employee);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Employee updateEmployee(Long id, Employee employee) {
|
||||||
|
Optional<Employee> existingEmployee = employeeRepository.findById(id);
|
||||||
|
if (existingEmployee.isPresent()) {
|
||||||
|
Employee emp = existingEmployee.get();
|
||||||
|
emp.setName(employee.getName());
|
||||||
|
emp.setPhone(employee.getPhone());
|
||||||
|
emp.setRole(employee.getRole());
|
||||||
|
// 注意:不更新openid字段,该字段由用户注册时自动填充
|
||||||
|
return employeeRepository.save(emp);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteEmployee(Long id) {
|
||||||
|
employeeRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将Employee实体转换为EmployeeDto
|
||||||
|
* @param employee 员工实体
|
||||||
|
* @return 员工DTO
|
||||||
|
*/
|
||||||
|
public EmployeeDto toDto(Employee employee) {
|
||||||
|
if (employee == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
EmployeeDto dto = new EmployeeDto();
|
||||||
|
BeanUtils.copyProperties(employee, dto);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将EmployeeDto转换为Employee实体
|
||||||
|
* @param dto 员工DTO
|
||||||
|
* @return 员工实体
|
||||||
|
*/
|
||||||
|
public Employee toEntity(EmployeeDto dto) {
|
||||||
|
if (dto == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Employee employee = new Employee();
|
||||||
|
BeanUtils.copyProperties(dto, employee);
|
||||||
|
return employee;
|
||||||
|
}
|
||||||
|
}
|
293
src/main/resources/static/employee-management.html
Normal file
293
src/main/resources/static/employee-management.html
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>员工管理</title>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
|
||||||
|
<style>
|
||||||
|
.action-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
.modal-form .form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container mt-4">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||||
|
<h2>员工管理</h2>
|
||||||
|
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEmployeeModal">
|
||||||
|
添加员工
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 员工列表表格 -->
|
||||||
|
<table class="table table-striped table-hover">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ID</th>
|
||||||
|
<th>姓名</th>
|
||||||
|
<th>电话</th>
|
||||||
|
<th>角色</th>
|
||||||
|
<th>OpenID</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="employeeTableBody">
|
||||||
|
<!-- 员工数据将通过JavaScript动态加载 -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 添加员工模态框 -->
|
||||||
|
<div class="modal fade" id="addEmployeeModal" tabindex="-1" aria-hidden="true">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title">添加员工</h5>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="addEmployeeForm" class="modal-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="addName" class="form-label">姓名</label>
|
||||||
|
<input type="text" class="form-control" id="addName" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="addPhone" class="form-label">电话</label>
|
||||||
|
<input type="text" class="form-control" id="addPhone" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="addRole" class="form-label">角色</label>
|
||||||
|
<select class="form-control" id="addRole" required>
|
||||||
|
<option value="DELIVERY_PERSON">配送员</option>
|
||||||
|
<option value="ADMIN">管理员</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
|
||||||
|
<button type="button" class="btn btn-primary" id="saveEmployeeBtn">保存</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 编辑员工模态框 -->
|
||||||
|
<div class="modal fade" id="editEmployeeModal" tabindex="-1" aria-hidden="true">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title">编辑员工</h5>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="editEmployeeForm" class="modal-form">
|
||||||
|
<input type="hidden" id="editId">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="editName" class="form-label">姓名</label>
|
||||||
|
<input type="text" class="form-control" id="editName" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="editPhone" class="form-label">电话</label>
|
||||||
|
<input type="text" class="form-control" id="editPhone" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="editRole" class="form-label">角色</label>
|
||||||
|
<select class="form-control" id="editRole" required>
|
||||||
|
<option value="DELIVERY_PERSON">配送员</option>
|
||||||
|
<option value="ADMIN">管理员</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
|
||||||
|
<button type="button" class="btn btn-primary" id="updateEmployeeBtn">更新</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
|
<script>
|
||||||
|
// API基础URL
|
||||||
|
const API_BASE_URL = '/api';
|
||||||
|
|
||||||
|
// 页面加载时获取员工列表
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
loadEmployees();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取所有员工
|
||||||
|
function loadEmployees() {
|
||||||
|
fetch(`${API_BASE_URL}/employees`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(employees => {
|
||||||
|
const tableBody = document.getElementById('employeeTableBody');
|
||||||
|
tableBody.innerHTML = '';
|
||||||
|
|
||||||
|
employees.forEach(employee => {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
row.innerHTML = `
|
||||||
|
<td>${employee.id || ''}</td>
|
||||||
|
<td>${employee.name || ''}</td>
|
||||||
|
<td>${employee.phone || ''}</td>
|
||||||
|
<td>${getRoleDisplayName(employee.role) || ''}</td>
|
||||||
|
<td>${employee.openid || ''}</td>
|
||||||
|
<td class="action-buttons">
|
||||||
|
<button class="btn btn-sm btn-outline-primary" onclick="editEmployee(${employee.id})">编辑</button>
|
||||||
|
<button class="btn btn-sm btn-outline-danger" onclick="deleteEmployee(${employee.id})">删除</button>
|
||||||
|
</td>
|
||||||
|
`;
|
||||||
|
tableBody.appendChild(row);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('获取员工列表失败:', error);
|
||||||
|
alert('获取员工列表失败');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 角色显示名称转换
|
||||||
|
function getRoleDisplayName(role) {
|
||||||
|
switch (role) {
|
||||||
|
case 'DELIVERY_PERSON':
|
||||||
|
return '配送员';
|
||||||
|
case 'ADMIN':
|
||||||
|
return '管理员';
|
||||||
|
default:
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存新员工
|
||||||
|
document.getElementById('saveEmployeeBtn').addEventListener('click', function() {
|
||||||
|
const name = document.getElementById('addName').value;
|
||||||
|
const phone = document.getElementById('addPhone').value;
|
||||||
|
const role = document.getElementById('addRole').value;
|
||||||
|
|
||||||
|
if (!name || !phone || !role) {
|
||||||
|
alert('请填写所有必填字段');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const employee = {
|
||||||
|
name: name,
|
||||||
|
phone: phone,
|
||||||
|
role: role
|
||||||
|
};
|
||||||
|
|
||||||
|
fetch(`${API_BASE_URL}/employees`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(employee)
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
alert('员工添加成功');
|
||||||
|
// 关闭模态框
|
||||||
|
const modal = bootstrap.Modal.getInstance(document.getElementById('addEmployeeModal'));
|
||||||
|
modal.hide();
|
||||||
|
// 重置表单
|
||||||
|
document.getElementById('addEmployeeForm').reset();
|
||||||
|
// 重新加载员工列表
|
||||||
|
loadEmployees();
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('添加员工失败:', error);
|
||||||
|
alert('添加员工失败');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 编辑员工
|
||||||
|
function editEmployee(id) {
|
||||||
|
fetch(`${API_BASE_URL}/employees`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(employees => {
|
||||||
|
const employee = employees.find(emp => emp.id === id);
|
||||||
|
if (employee) {
|
||||||
|
document.getElementById('editId').value = employee.id;
|
||||||
|
document.getElementById('editName').value = employee.name;
|
||||||
|
document.getElementById('editPhone').value = employee.phone;
|
||||||
|
document.getElementById('editRole').value = employee.role;
|
||||||
|
|
||||||
|
// 显示编辑模态框
|
||||||
|
const modal = new bootstrap.Modal(document.getElementById('editEmployeeModal'));
|
||||||
|
modal.show();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('获取员工信息失败:', error);
|
||||||
|
alert('获取员工信息失败');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新员工信息
|
||||||
|
document.getElementById('updateEmployeeBtn').addEventListener('click', function() {
|
||||||
|
const id = document.getElementById('editId').value;
|
||||||
|
const name = document.getElementById('editName').value;
|
||||||
|
const phone = document.getElementById('editPhone').value;
|
||||||
|
const role = document.getElementById('editRole').value;
|
||||||
|
|
||||||
|
if (!id || !name || !phone || !role) {
|
||||||
|
alert('员工信息不完整');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const employee = {
|
||||||
|
id: parseInt(id),
|
||||||
|
name: name,
|
||||||
|
phone: phone,
|
||||||
|
role: role
|
||||||
|
};
|
||||||
|
|
||||||
|
fetch(`${API_BASE_URL}/employees/${id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(employee)
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
alert('员工信息更新成功');
|
||||||
|
// 关闭模态框
|
||||||
|
const modal = bootstrap.Modal.getInstance(document.getElementById('editEmployeeModal'));
|
||||||
|
modal.hide();
|
||||||
|
// 重新加载员工列表
|
||||||
|
loadEmployees();
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('更新员工信息失败:', error);
|
||||||
|
alert('更新员工信息失败');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除员工
|
||||||
|
function deleteEmployee(id) {
|
||||||
|
if (confirm('确定要删除这个员工吗?')) {
|
||||||
|
fetch(`${API_BASE_URL}/employees/${id}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
})
|
||||||
|
.then(response => response.text())
|
||||||
|
.then(data => {
|
||||||
|
alert('员工删除成功');
|
||||||
|
// 重新加载员工列表
|
||||||
|
loadEmployees();
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('删除员工失败:', error);
|
||||||
|
alert('删除员工失败');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
125
src/main/resources/static/js/employee-api.js
Normal file
125
src/main/resources/static/js/employee-api.js
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
/**
|
||||||
|
* 员工管理API服务
|
||||||
|
*/
|
||||||
|
class EmployeeApiService {
|
||||||
|
constructor(baseURL) {
|
||||||
|
this.baseURL = baseURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有员工列表
|
||||||
|
* @returns 员工信息数组
|
||||||
|
*/
|
||||||
|
async getEmployees() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${this.baseURL}/employees`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${this.getToken()}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取员工列表失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加新员工
|
||||||
|
* @param employeeInfo 员工信息
|
||||||
|
* @returns 添加结果
|
||||||
|
*/
|
||||||
|
async addEmployee(employeeInfo) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${this.baseURL}/employees`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${this.getToken()}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(employeeInfo)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('添加员工失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除员工
|
||||||
|
* @param employeeId 员工ID
|
||||||
|
* @returns 删除结果
|
||||||
|
*/
|
||||||
|
async deleteEmployee(employeeId) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${this.baseURL}/employees/${employeeId}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${this.getToken()}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.text();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('删除员工失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新员工信息
|
||||||
|
* @param employeeId 员工ID
|
||||||
|
* @param employeeInfo 员工信息
|
||||||
|
* @returns 更新结果
|
||||||
|
*/
|
||||||
|
async updateEmployee(employeeId, employeeInfo) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${this.baseURL}/employees/${employeeId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${this.getToken()}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(employeeInfo)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('更新员工信息失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从localStorage获取token
|
||||||
|
* @returns JWT token
|
||||||
|
*/
|
||||||
|
getToken() {
|
||||||
|
return localStorage.getItem('token');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出员工API服务实例
|
||||||
|
const employeeApiService = new EmployeeApiService('/api');
|
Reference in New Issue
Block a user