409 lines
15 KiB
Java
409 lines
15 KiB
Java
package com.kri.contact.server.service;
|
|
|
|
import static com.kri.contact.server.common.consts.ContactConstant.SYSTEM_USER_NAME;
|
|
|
|
import com.kri.common.feature.datetime.DateTimeUtil;
|
|
import com.kri.common.feature.excel.ExcelMapper;
|
|
import com.kri.common.feature.web.BusinessException;
|
|
import com.kri.contact.server.common.consts.ContactConstant;
|
|
import com.kri.contact.server.common.external.intranet.IntranetExtensionApiClient;
|
|
import com.kri.contact.server.common.util.ExcelUploadResultUtil;
|
|
import com.kri.contact.server.dto.common.DataVerificationDto;
|
|
import com.kri.contact.server.dto.excel.ExcelUploadResultDto;
|
|
import com.kri.contact.server.dto.user.RoleInfoDto;
|
|
import com.kri.contact.server.dto.user.UserInfoDto;
|
|
import com.kri.contact.server.dto.excel.UserUploadDto;
|
|
import com.kri.contact.server.dto.excel.UserUploadErrorDto;
|
|
import com.kri.contact.server.persistence.entity.TUserEntity;
|
|
import com.kri.contact.server.persistence.repository.UserRepository;
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.time.LocalDateTime;
|
|
import java.util.ArrayList;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
import java.util.Objects;
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.apache.poi.ss.usermodel.Workbook;
|
|
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class UserService {
|
|
|
|
private final IntranetExtensionApiClient intranetExtensionApiClient;
|
|
private final AssignService assignService;
|
|
private final RoleService roleService;
|
|
private final UserRepository userRepository;
|
|
|
|
private static final int OUTSOURCE_USER_ROLE_END = ContactConstant.OUTSOURCE_USER_ROLE + 1000;
|
|
|
|
@Transactional
|
|
public void createUser(UserInfoDto userInfo, String regUser, LocalDateTime regDt) {
|
|
List<RoleInfoDto> roleList = roleService.getRoleList();
|
|
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
|
|
|
|
userInfo.setUserId(userInfo.getUserId().toLowerCase());
|
|
|
|
List<DataVerificationDto> failList = validateUserDto(userInfo, roleList,
|
|
intranetUserList).stream().filter(dto -> !dto.success()).toList();
|
|
if (!failList.isEmpty()) {
|
|
DataVerificationDto firstFail = failList.get(0);
|
|
throw BusinessException.badRequest("WRONG_USER_DATA", firstFail.errMessage());
|
|
}
|
|
|
|
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser, regDt);
|
|
|
|
userRepository.save(entity);
|
|
}
|
|
|
|
@Transactional
|
|
public ExcelUploadResultDto createUsersFromExcel(MultipartFile file, String regUser,
|
|
LocalDateTime regDt, String forceCmpn) {
|
|
if (file == null || file.isEmpty()) {
|
|
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
|
|
}
|
|
|
|
String fileName = file.getOriginalFilename();
|
|
String errorFileName = fileName != null && fileName.endsWith(".xlsx")
|
|
? fileName.substring(0, fileName.length() - 5) + "_error.xlsx"
|
|
: fileName + "_error.xlsx";
|
|
|
|
List<UserUploadDto> rows;
|
|
try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
|
|
// DTO 매핑 (스트리밍 X, 일반 방식)
|
|
rows = ExcelMapper.readFromWorkbook(workbook, UserUploadDto.class);
|
|
} catch (Exception e) {
|
|
throw BusinessException.badRequest("INVALID_EXCEL", "엑셀 파일을 읽는 중 오류가 발생했습니다.")
|
|
.with("fileName", fileName);
|
|
}
|
|
|
|
int totalCount = rows.size();
|
|
int successCount = 0;
|
|
List<RoleInfoDto> roleList = roleService.getRoleList();
|
|
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
|
|
List<UserUploadErrorDto> errorList = new ArrayList<>();
|
|
|
|
// 엑셀 1행 = 헤더, DTO 리스트는 2행부터라고 가정
|
|
for (int i = 0; i < rows.size(); i++) {
|
|
UserUploadDto uploadDto = rows.get(i);
|
|
Integer roleCd = roleList.stream()
|
|
.filter(r -> java.util.Objects.equals(uploadDto.getUserRoleStr(), r.roleNm()))
|
|
.map(RoleInfoDto::roleCd)
|
|
.findFirst()
|
|
.orElse(null);
|
|
|
|
UserInfoDto dto = UserInfoDto.from(uploadDto, roleCd, regUser);
|
|
if (!forceCmpn.isBlank()) {
|
|
dto.setUserCmpn(forceCmpn);
|
|
}
|
|
|
|
int rowNumber = i + 2; // 엑셀 실제 행 번호 (헤더가 1행일 때)
|
|
// 1) 값 검증
|
|
List<UserUploadErrorDto> rowErrors = validateUserDtoForExcel(dto, rowNumber, roleList,
|
|
intranetUserList);
|
|
if (!rowErrors.isEmpty()) {
|
|
errorList.addAll(rowErrors);
|
|
continue; // 이 행은 DB 저장 스킵
|
|
}
|
|
|
|
// 2) 실제 DB 저장
|
|
try {
|
|
this.createUserInternal(dto, regUser, regDt);
|
|
successCount++;
|
|
} catch (BusinessException ex) {
|
|
// 시스템/비즈니스 예외도 에러 목록에 추가
|
|
errorList.add(
|
|
UserUploadErrorDto.of(
|
|
rowNumber,
|
|
dto.getUserId(),
|
|
SYSTEM_USER_NAME,
|
|
ex.getMessage()
|
|
)
|
|
);
|
|
}
|
|
}
|
|
|
|
int failCount = errorList.stream()
|
|
.map(UserUploadErrorDto::getRowNumber)
|
|
.distinct()
|
|
.toList()
|
|
.size();
|
|
|
|
return ExcelUploadResultUtil.buildUploadResult(
|
|
totalCount,
|
|
successCount,
|
|
failCount,
|
|
errorList,
|
|
UserUploadErrorDto.class,
|
|
errorFileName
|
|
);
|
|
}
|
|
|
|
public byte[] exportUserTemplate() {
|
|
try (Workbook workbook =
|
|
ExcelMapper.writeToWorkbook(Collections.emptyList(), UserUploadDto.class);
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
|
|
|
workbook.write(out);
|
|
return out.toByteArray();
|
|
} catch (Exception e) {
|
|
throw BusinessException.internalError("사용자 업로드 템플릿 엑셀 생성 중 오류");
|
|
}
|
|
}
|
|
|
|
public DataVerificationDto checkUserId(String userId) {
|
|
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
|
|
return this.verifyUserId(userId, intranetUserList);
|
|
}
|
|
|
|
public UserInfoDto getUser(String userId) {
|
|
TUserEntity user = userRepository.findByUserIdAndDelFalse(userId)
|
|
.orElseThrow(() ->
|
|
BusinessException.notFound("USER_NOT_FOUND", "사용자가 없습니다.")
|
|
.with("userId", userId)
|
|
);
|
|
|
|
UserInfoDto userInfoDto = UserInfoDto.from(user);
|
|
userInfoDto.setUserPw(user.getUserPw());
|
|
return userInfoDto;
|
|
}
|
|
|
|
public TUserEntity getUser(String userId, String userPw) {
|
|
return userRepository.findByUserIdAndUserPwAndDelFalse(userId, userPw)
|
|
.orElseThrow(() ->
|
|
BusinessException.notFound("USER_NOT_FOUND", "사용자가 없습니다.")
|
|
.with("userId", userId)
|
|
);
|
|
}
|
|
|
|
public List<UserInfoDto> getUserList() {
|
|
return userRepository.findByUserRoleGreaterThanEqualAndDelFalse(ContactConstant.OUTSOURCE_USER_ROLE).stream()
|
|
.map(UserInfoDto::from)
|
|
.toList();
|
|
}
|
|
|
|
public List<UserInfoDto> getFieldworkUserListWithCmpn(String searchCmpn) {
|
|
List<TUserEntity> userList;
|
|
if (searchCmpn == null || searchCmpn.isBlank()) {
|
|
userList = userRepository.findByUserRoleGreaterThanEqualAndDelFalse(
|
|
ContactConstant.FIELDWORK_USER_ROLE);
|
|
} else {
|
|
userList = userRepository.findByUserCmpnAndUserRoleGreaterThanEqualAndDelFalse(searchCmpn,
|
|
ContactConstant.FIELDWORK_USER_ROLE);
|
|
}
|
|
|
|
return userList.stream()
|
|
.map(UserInfoDto::from)
|
|
.toList();
|
|
}
|
|
|
|
public List<UserInfoDto> getOutsourceList() {
|
|
List<TUserEntity> userList = userRepository.findByRoleRangeAndDelFalse(
|
|
ContactConstant.OUTSOURCE_USER_ROLE,
|
|
ContactConstant.OUTSOURCE_USER_ROLE + 1000
|
|
);
|
|
|
|
return userList.stream()
|
|
.map(UserInfoDto::from)
|
|
.toList();
|
|
}
|
|
|
|
public List<String> getUserCmpnList() {
|
|
return userRepository.findDistinctUserCmpnAndDelFalse();
|
|
}
|
|
|
|
@Transactional
|
|
public void updateUser(UserInfoDto dto, String modUser, LocalDateTime modDt) {
|
|
// dirty checking 업데이트
|
|
TUserEntity entity = userRepository.findByUserIdAndDelFalse(dto.getUserId())
|
|
.orElseThrow(() ->
|
|
BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
|
.with("userId", dto.getUserId())
|
|
);
|
|
|
|
validateUserRoleChange(entity.getUserRole(), dto.getUserRole());
|
|
|
|
if(!Objects.equals(entity.getUserRole(), dto.getUserRole())) {
|
|
assignService.deleteListAssignWithUser(dto.getUserId());
|
|
}
|
|
|
|
entity.updateFromDto(dto, modUser, modDt);// 기존 엔티티에 적용
|
|
}
|
|
|
|
@Transactional
|
|
public void deleteUser(String userId, String delUser) {
|
|
int deleteCount = userRepository.softDeleteByUserId(userId, delUser,
|
|
DateTimeUtil.nowKstLocalDateTime());
|
|
|
|
if (deleteCount == 0) {
|
|
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
|
.with("userId", userId);
|
|
}
|
|
|
|
assignService.deleteListAssignWithUser(userId);
|
|
}
|
|
|
|
/*******************************private*******************************/
|
|
private void validateUserRoleChange(Integer currentRole, Integer newRole) {
|
|
if (Objects.equals(currentRole, newRole)) {
|
|
return;
|
|
}
|
|
if ((isOutsourceRole(currentRole) && isFieldworkRole(newRole))
|
|
|| (isFieldworkRole(currentRole) && isOutsourceRole(newRole))) {
|
|
throw BusinessException.badRequest(
|
|
"USER_ROLE_CHANGE_NOT_ALLOWED",
|
|
"외주사와 콜센터/컨택원/면접원 간 권한 변경은 할 수 없습니다."
|
|
);
|
|
}
|
|
}
|
|
|
|
private boolean isOutsourceRole(Integer role) {
|
|
return role != null
|
|
&& role >= ContactConstant.OUTSOURCE_USER_ROLE
|
|
&& role < OUTSOURCE_USER_ROLE_END;
|
|
}
|
|
|
|
private boolean isFieldworkRole(Integer role) {
|
|
return role != null && role >= ContactConstant.FIELDWORK_USER_ROLE;
|
|
}
|
|
|
|
private DataVerificationDto verifyUserId(String userId, List<String> intranetUserList) {
|
|
if (userId == null || userId.isBlank()) {
|
|
return new DataVerificationDto(false, "사용자 ID", "사용자 ID가 비었습니다.");
|
|
}
|
|
if (userId.length() < 2 || userId.length() > 16) {
|
|
return new DataVerificationDto(false, "사용자 ID", "사용자 ID는 2~16 자리여야 합니다.");
|
|
}
|
|
if (!userId.matches("^[a-z가-힣][a-z0-9가-힣]+$")) {
|
|
return new DataVerificationDto(false, "사용자 ID", "사용자 ID는 한글, 영소문자, 숫자만 허용합니다.");
|
|
}
|
|
if (userRepository.existsByUserIdAndDelFalse(userId)) {
|
|
return new DataVerificationDto(false, "사용자 ID", "이미 사용중인 ID입니다.");
|
|
}
|
|
if (intranetUserList.contains(userId) || intranetUserList.contains(
|
|
String.format("%s@kric.com", userId))) {
|
|
return new DataVerificationDto(false, "사용자 ID", "이미 사용중인 직원 ID입니다.");
|
|
}
|
|
|
|
return new DataVerificationDto();
|
|
}
|
|
|
|
private List<DataVerificationDto> validateUserDto(
|
|
UserInfoDto dto,
|
|
List<RoleInfoDto> roleList,
|
|
List<String> intranetUserList
|
|
) {
|
|
List<DataVerificationDto> result = new ArrayList<>();
|
|
|
|
// 0. userId 기본 검증 (기존 로직)
|
|
result.add(this.verifyUserId(dto.getUserId(), intranetUserList));
|
|
|
|
// 1. userPw 비어있는지 / PW 정규식 검사
|
|
String userPw = dto.getUserPw();
|
|
if (userPw == null || userPw.isBlank()) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 PW",
|
|
"비밀번호가 비어 있습니다."
|
|
));
|
|
} else {
|
|
// 예시: 8~20자, 영문 + 숫자 반드시 포함, 특수문자 허용
|
|
//String pwPattern = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d!@#$%^&*()_+\\-={}\\[\\]:;\"'<>,.?/]{8,20}$";
|
|
// 1~20자, 영문·숫자·특수문자 허용
|
|
String pwPattern = "^[A-Za-z\\d!@#$%^&*()_+\\-={}\\[\\]:;\"'<>,.?/]{1,20}$";
|
|
if (!userPw.matches(pwPattern)) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 PW",
|
|
"비밀번호는 영문, 숫자, 허용된 특수문자를 사용하여 1~20자로 입력해야 합니다."
|
|
));
|
|
}
|
|
}
|
|
|
|
// 2. userName 비어있는지 / 한글·영문 대소문자만 허용
|
|
String userName = dto.getUserName();
|
|
if (userName == null || userName.isBlank()) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 이름",
|
|
"사용자 이름이 비어 있습니다."
|
|
));
|
|
} else if (!userName.matches("^[가-힣A-Za-z][가-힣A-Za-z0-9_ ()]*$")) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 이름",
|
|
"사용자 이름은 한글/영문으로 시작해야 하며, 한글/영문/숫자와 공백, '(', ')', '_'만 입력 가능합니다."
|
|
));
|
|
}
|
|
|
|
// 3. userCmpn 비어있는지 / 한글, 영문, 숫자, 공백, (, ) 만 허용
|
|
String userCmpn = dto.getUserCmpn();
|
|
if (userCmpn == null || userCmpn.isBlank()) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 소속 회사",
|
|
"사용자 소속 회사가 비어 있습니다."
|
|
));
|
|
} else if (!userCmpn.matches("^[가-힣A-Za-z0-9() ]+$")) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 소속 회사",
|
|
"사용자 소속 회사는 한글, 영문, 숫자, 공백, '(', ')'만 사용할 수 있습니다."
|
|
));
|
|
}
|
|
|
|
// 4. userRole 이 roleList의 roleNm에 존재하는지 체크
|
|
Integer userRole = dto.getUserRole();
|
|
if (roleList != null && !roleList.isEmpty()) {
|
|
boolean exists = roleList.stream()
|
|
.anyMatch(r -> userRole != null && userRole.equals(r.roleCd()));
|
|
|
|
if (!exists) {
|
|
result.add(new DataVerificationDto(
|
|
false,
|
|
"사용자 권한",
|
|
"사용자 권한이 잘 못 됐습니다."
|
|
));
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private List<UserUploadErrorDto> validateUserDtoForExcel(
|
|
UserInfoDto dto,
|
|
int rowNumber,
|
|
List<RoleInfoDto> roleList,
|
|
List<String> intranetUserList
|
|
) {
|
|
List<UserUploadErrorDto> errors = new ArrayList<>();
|
|
|
|
List<DataVerificationDto> validateUserList = this.validateUserDto(dto, roleList,
|
|
intranetUserList);
|
|
|
|
validateUserList.forEach(validateResult -> {
|
|
if (!validateResult.success()) {
|
|
errors.add(UserUploadErrorDto.of(
|
|
rowNumber,
|
|
dto.getUserId(),
|
|
validateResult.fieldName(),
|
|
validateResult.errMessage()
|
|
));
|
|
}
|
|
});
|
|
|
|
return errors;
|
|
}
|
|
|
|
private void createUserInternal(UserInfoDto userInfo, String regUser, LocalDateTime regDt) {
|
|
userInfo.setUserId(userInfo.getUserId().toLowerCase());
|
|
userInfo.setUserTeam("S101");
|
|
|
|
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser, regDt);
|
|
userRepository.save(entity);
|
|
}
|
|
}
|