package com.rongyichuang.employee.service;
|
|
import com.rongyichuang.employee.dto.request.EmployeeInput;
|
import com.rongyichuang.employee.dto.response.EmployeeResponse;
|
import com.rongyichuang.employee.entity.Employee;
|
import com.rongyichuang.employee.repository.EmployeeRepository;
|
import com.rongyichuang.common.exception.BusinessException;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.Pageable;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.stereotype.Service;
|
import org.springframework.transaction.annotation.Transactional;
|
|
import java.util.List;
|
import java.util.Optional;
|
import java.util.regex.Pattern;
|
import java.util.stream.Collectors;
|
|
/**
|
* 员工服务类
|
*/
|
@Service
|
@Transactional
|
public class EmployeeService {
|
|
private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);
|
|
@Autowired
|
private EmployeeRepository employeeRepository;
|
|
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
|
// 密码验证正则:至少6个字符,必须包含字母和数字
|
private static final Pattern PASSWORD_PATTERN = Pattern.compile("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d@$!%*?&]{6,}$");
|
|
/**
|
* 获取所有员工列表
|
*/
|
public List<EmployeeResponse> findAllEmployees() {
|
List<Employee> employees = employeeRepository.findAll();
|
return employees.stream()
|
.map(EmployeeResponse::new)
|
.collect(Collectors.toList());
|
}
|
|
/**
|
* 分页查询员工列表,支持名称搜索
|
*/
|
public Page<EmployeeResponse> findEmployees(String name, int page, int size) {
|
Pageable pageable = PageRequest.of(page, size);
|
Page<Employee> employeePage = employeeRepository.findByNameContainingOrderByCreateTimeDesc(name, pageable);
|
return employeePage.map(EmployeeResponse::new);
|
}
|
|
/**
|
* 根据名称搜索员工
|
*/
|
public List<EmployeeResponse> searchByName(String name) {
|
if (name == null || name.trim().isEmpty()) {
|
return findAllEmployees();
|
}
|
List<Employee> employees = employeeRepository.findByNameContaining(name.trim());
|
return employees.stream()
|
.map(EmployeeResponse::new)
|
.collect(Collectors.toList());
|
}
|
|
/**
|
* 根据ID获取员工详情
|
*/
|
public EmployeeResponse findById(Long id) {
|
Optional<Employee> employee = employeeRepository.findById(id);
|
if (employee.isPresent()) {
|
return new EmployeeResponse(employee.get());
|
}
|
throw new BusinessException("EMPLOYEE_NOT_FOUND", "员工不存在");
|
}
|
|
/**
|
* 保存员工(新增或更新)
|
*/
|
public EmployeeResponse saveEmployee(EmployeeInput input) {
|
// 验证输入
|
validateEmployeeInput(input);
|
|
Employee employee;
|
if (input.getId() != null) {
|
// 更新员工
|
employee = employeeRepository.findById(input.getId())
|
.orElseThrow(() -> new BusinessException("EMPLOYEE_NOT_FOUND", "员工不存在"));
|
|
// 检查手机号是否被其他员工使用
|
if (employeeRepository.existsByPhoneAndIdNot(input.getPhone(), input.getId())) {
|
throw new BusinessException("PHONE_ALREADY_EXISTS", "手机号已被其他员工使用");
|
}
|
} else {
|
// 新增员工
|
if (employeeRepository.existsByPhone(input.getPhone())) {
|
throw new BusinessException("PHONE_ALREADY_EXISTS", "手机号已存在");
|
}
|
employee = new Employee();
|
employee.setUserId(1L); // 临时设置,实际应该从当前登录用户获取
|
}
|
|
// 设置基本信息
|
employee.setName(input.getName());
|
employee.setPhone(input.getPhone());
|
employee.setRoleId(input.getRoleId());
|
employee.setDescription(input.getDescription());
|
|
// 处理密码
|
if (input.getPassword() != null && !input.getPassword().trim().isEmpty()) {
|
employee.setPassword(passwordEncoder.encode(input.getPassword()));
|
}
|
|
Employee savedEmployee = employeeRepository.save(employee);
|
logger.info("员工保存成功: {}", savedEmployee.getName());
|
|
return new EmployeeResponse(savedEmployee);
|
}
|
|
/**
|
* 删除员工(软删除)
|
*/
|
public boolean deleteEmployee(Long id) {
|
Optional<Employee> employee = employeeRepository.findById(id);
|
if (employee.isPresent()) {
|
Employee emp = employee.get();
|
emp.setState(0); // 软删除
|
employeeRepository.save(emp);
|
logger.info("员工删除成功: {}", emp.getName());
|
return true;
|
}
|
return false;
|
}
|
|
/**
|
* 验证员工输入数据
|
*/
|
private void validateEmployeeInput(EmployeeInput input) {
|
if (input.getName() == null || input.getName().trim().isEmpty()) {
|
throw new BusinessException("NAME_REQUIRED", "员工姓名不能为空");
|
}
|
|
if (input.getPhone() == null || input.getPhone().trim().isEmpty()) {
|
throw new BusinessException("PHONE_REQUIRED", "手机号不能为空");
|
}
|
|
if (input.getRoleId() == null || input.getRoleId().trim().isEmpty()) {
|
throw new BusinessException("ROLE_REQUIRED", "角色不能为空");
|
}
|
|
// 新增员工时密码必填
|
if (input.getId() == null) {
|
if (input.getPassword() == null || input.getPassword().trim().isEmpty()) {
|
throw new BusinessException("PASSWORD_REQUIRED", "密码不能为空");
|
}
|
}
|
|
// 如果提供了密码,验证密码格式
|
if (input.getPassword() != null && !input.getPassword().trim().isEmpty()) {
|
if (!PASSWORD_PATTERN.matcher(input.getPassword()).matches()) {
|
throw new BusinessException("INVALID_PASSWORD_FORMAT", "密码至少6个字符,必须包含字母和数字");
|
}
|
}
|
|
// 验证手机号格式
|
if (!isValidPhone(input.getPhone())) {
|
throw new BusinessException("INVALID_PHONE_FORMAT", "手机号格式不正确");
|
}
|
}
|
|
/**
|
* 验证手机号格式
|
*/
|
private boolean isValidPhone(String phone) {
|
if (phone == null) return false;
|
// 简单的手机号验证:11位数字
|
return phone.matches("^1[3-9]\\d{9}$");
|
}
|
}
|