251202_01_ENH: User 관련 기능 구현
This commit is contained in:
328
src/main/java/com/kri/contact/server/service/UserService.java
Normal file
328
src/main/java/com/kri/contact/server/service/UserService.java
Normal file
@@ -0,0 +1,328 @@
|
||||
package com.kri.contact.server.service;
|
||||
|
||||
import com.kri.common.datetime.DateTimeUtil;
|
||||
import com.kri.common.excel.ExcelMapper;
|
||||
import com.kri.common.web.BusinessException;
|
||||
import com.kri.contact.server.common.consts.AppConstant;
|
||||
import com.kri.contact.server.common.external.intranet.IntranetExtensionApiClient;
|
||||
import com.kri.contact.server.common.util.ExcelUploadResultUtil;
|
||||
import com.kri.contact.server.dto.DataVerificationDto;
|
||||
import com.kri.contact.server.dto.ExcelUploadResponseDto;
|
||||
import com.kri.contact.server.dto.RoleInfoDto;
|
||||
import com.kri.contact.server.dto.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 lombok.RequiredArgsConstructor;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
private final IntranetExtensionApiClient intranetExtensionApiClient;
|
||||
private final RoleService roleService;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Transactional
|
||||
public void createUser(UserInfoDto userInfo, String regUser){
|
||||
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.isSuccess()).toList();
|
||||
if(!failList.isEmpty()){
|
||||
DataVerificationDto firstFail = failList.get(0);
|
||||
throw BusinessException.badRequest("WRONG_USER_DATA", firstFail.getErrMessage());
|
||||
}
|
||||
|
||||
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser);
|
||||
|
||||
userRepository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ExcelUploadResponseDto createUsersFromExcel(MultipartFile file, String regUser, String forceCmpn) {
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
|
||||
}
|
||||
|
||||
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", file.getOriginalFilename());
|
||||
}
|
||||
|
||||
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.getRoleNm()))
|
||||
.map(RoleInfoDto::getRoleCd)
|
||||
.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);
|
||||
successCount++;
|
||||
} catch (BusinessException ex) {
|
||||
// 시스템/비즈니스 예외도 에러 목록에 추가
|
||||
errorList.add(
|
||||
UserUploadErrorDto.of(
|
||||
rowNumber,
|
||||
"SYSTEM",
|
||||
ex.getMessage()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return ExcelUploadResultUtil.buildUploadResult(
|
||||
totalCount,
|
||||
successCount,
|
||||
errorList,
|
||||
UserUploadErrorDto.class,
|
||||
"user_upload_errors.xlsx"
|
||||
);
|
||||
}
|
||||
|
||||
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> getUserListWithCmpn(String searchCmpn){
|
||||
List<TUserEntity> userList;
|
||||
if(searchCmpn == null || searchCmpn.isBlank()){
|
||||
userList = userRepository.findAll();
|
||||
}
|
||||
else{
|
||||
userList = userRepository.findByUserCmpnAndUserRoleGreaterThanEqualAndDelFalse(searchCmpn, AppConstant.FIELDWORK_USER_ROLE);
|
||||
}
|
||||
|
||||
return userList.stream()
|
||||
.map(UserInfoDto::from)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<String> getUserCmpnList(){
|
||||
return userRepository.findDistinctUserCmpnAndDelFalse();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateUser(UserInfoDto dto, String modUser){
|
||||
TUserEntity entity = userRepository.findByUserIdAndDelFalse(dto.getUserId())
|
||||
.orElseThrow(() ->
|
||||
BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||
.with("userId", dto.getUserId())
|
||||
);
|
||||
|
||||
entity.updateFromDto(dto, modUser);// 기존 엔티티에 적용
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************private*******************************/
|
||||
private DataVerificationDto verifyUserId(String userId, List<String> intranetUserList){
|
||||
if(userId == null || userId.isBlank()){
|
||||
return new DataVerificationDto(false, "사용자 ID", "사용자 ID가 비었습니다.");
|
||||
}
|
||||
if (userId.length() < 3 || userId.length() > 16 ) {
|
||||
return new DataVerificationDto(false,"사용자 ID", "사용자 ID는 3~15 자리여야 합니다.");
|
||||
}
|
||||
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}$";
|
||||
if (!userPw.matches(pwPattern)) {
|
||||
result.add(new DataVerificationDto(
|
||||
false,
|
||||
"사용자 PW",
|
||||
"비밀번호는 영문과 숫자를 포함한 8~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.equals(r.getRoleCd()));
|
||||
|
||||
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.isSuccess()){
|
||||
errors.add(UserUploadErrorDto.of(
|
||||
rowNumber,
|
||||
validateResult.getFieldName(),
|
||||
validateResult.getErrMessage()
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
private void createUserInternal(UserInfoDto userInfo, String regUser) {
|
||||
userInfo.setUserId(userInfo.getUserId().toLowerCase());
|
||||
userInfo.setUserTeam("S101");
|
||||
|
||||
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser);
|
||||
userRepository.save(entity);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user