260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용

This commit is contained in:
2026-02-12 11:23:15 +09:00
parent 4948faa28a
commit b07a4389d1
84 changed files with 3176 additions and 2891 deletions

View File

@@ -14,334 +14,342 @@ 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.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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 RoleService roleService;
private final UserRepository userRepository;
@Transactional
public void createUser(UserInfoDto userInfo, String regUser, LocalDateTime regDt) {
List<RoleInfoDto> roleList = roleService.getRoleList();
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
private final IntranetExtensionApiClient intranetExtensionApiClient;
private final RoleService roleService;
private final UserRepository userRepository;
userInfo.setUserId(userInfo.getUserId().toLowerCase());
@Transactional
public void createUser(UserInfoDto userInfo, String regUser, LocalDateTime regDt) {
List<RoleInfoDto> roleList = roleService.getRoleList();
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
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());
}
userInfo.setUserId(userInfo.getUserId().toLowerCase());
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser, regDt);
userRepository.save(entity);
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());
}
@Transactional
public ExcelUploadResponseDto createUsersFromExcel(MultipartFile file, String regUser, LocalDateTime regDt, String forceCmpn) {
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
}
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser, regDt);
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());
}
userRepository.save(entity);
}
int totalCount = rows.size();
int successCount = 0;
List<RoleInfoDto> roleList = roleService.getRoleList();
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
List<UserUploadErrorDto> errorList = new ArrayList<>();
@Transactional
public ExcelUploadResponseDto createUsersFromExcel(MultipartFile file, String regUser,
LocalDateTime regDt, String forceCmpn) {
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_FILE", "업로드된 파일이 없습니다.");
}
// 엑셀 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);
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());
}
UserInfoDto dto = UserInfoDto.from(uploadDto, roleCd, regUser);
if(!forceCmpn.isBlank()) {
dto.setUserCmpn(forceCmpn);
}
int totalCount = rows.size();
int successCount = 0;
List<RoleInfoDto> roleList = roleService.getRoleList();
List<String> intranetUserList = intranetExtensionApiClient.getUserIdArray();
List<UserUploadErrorDto> errorList = new ArrayList<>();
int rowNumber = i + 2; // 엑셀 실제 행 번호 (헤더가 1행일 때)
// 1) 값 검증
List<UserUploadErrorDto> rowErrors = validateUserDtoForExcel(dto, rowNumber, roleList, intranetUserList);
if (!rowErrors.isEmpty()) {
errorList.addAll(rowErrors);
continue; // 이 행은 DB 저장 스킵
}
// 엑셀 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);
// 2) 실제 DB 저장
try {
this.createUserInternal(dto, regUser, regDt);
successCount++;
} catch (BusinessException ex) {
// 시스템/비즈니스 예외도 에러 목록에 추가
errorList.add(
UserUploadErrorDto.of(
rowNumber,
"SYSTEM",
ex.getMessage()
)
);
}
}
UserInfoDto dto = UserInfoDto.from(uploadDto, roleCd, regUser);
if (!forceCmpn.isBlank()) {
dto.setUserCmpn(forceCmpn);
}
return ExcelUploadResultUtil.buildUploadResult(
totalCount,
successCount,
errorList,
UserUploadErrorDto.class,
"user_upload_errors.xlsx"
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,
"SYSTEM",
ex.getMessage()
)
);
}
}
public byte[] exportUserTemplate() {
try (Workbook workbook =
ExcelMapper.writeToWorkbook(Collections.emptyList(), UserUploadDto.class);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
return ExcelUploadResultUtil.buildUploadResult(
totalCount,
successCount,
errorList,
UserUploadErrorDto.class,
"user_upload_errors.xlsx"
);
}
workbook.write(out);
return out.toByteArray();
} catch (Exception e) {
throw BusinessException.internalError("사용자 업로드 템플릿 엑셀 생성 중 오류");
}
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 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.findByDelFalse().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
public UserInfoDto getUser(String userId) {
TUserEntity user = userRepository.findByUserIdAndDelFalse(userId)
.orElseThrow(() ->
BusinessException.notFound("USER_NOT_FOUND", "사용자가 없습니다.")
.with("userId", userId)
);
return userList.stream()
.map(UserInfoDto::from)
.toList();
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.findByDelFalse().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);
}
public List<String> getUserCmpnList() {
return userRepository.findDistinctUserCmpnAndDelFalse();
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())
);
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);
}
}
/*******************************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입니다.");
}
@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())
);
return new DataVerificationDto();
}
entity.updateFromDto(dto, modUser, modDt);// 기존 엔티티에 적용
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자로 입력해야 합니다."
));
}
}
@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);
}
// 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,
"사용자 이름",
"사용자 이름은 한글/영문으로 시작해야 하며, 한글/영문/숫자와 공백, '(', ')', '_'만 입력 가능합니다."
));
}
/*******************************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();
// 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,
"사용자 소속 회사",
"사용자 소속 회사는 한글, 영문, 숫자, 공백, '(', ')'만 사용할 수 있습니다."
));
}
private List<DataVerificationDto> validateUserDto(
UserInfoDto dto,
List<RoleInfoDto> roleList,
List<String> intranetUserList
) {
List<DataVerificationDto> result = new ArrayList<>();
// 4. userRole 이 roleList의 roleNm에 존재하는지 체크
Integer userRole = dto.getUserRole();
if (roleList != null && !roleList.isEmpty()) {
boolean exists = roleList.stream()
.anyMatch(r -> userRole.equals(r.getRoleCd()));
// 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;
if (!exists) {
result.add(new DataVerificationDto(
false,
"사용자 권한",
"사용자 권한이 잘 못 됐습니다."
));
}
}
private List<UserUploadErrorDto> validateUserDtoForExcel(
UserInfoDto dto,
int rowNumber,
List<RoleInfoDto> roleList,
List<String> intranetUserList
) {
List<UserUploadErrorDto> errors = new ArrayList<>();
return result;
}
List<DataVerificationDto> validateUserList = this.validateUserDto(dto, roleList, intranetUserList);
private List<UserUploadErrorDto> validateUserDtoForExcel(
UserInfoDto dto,
int rowNumber,
List<RoleInfoDto> roleList,
List<String> intranetUserList
) {
List<UserUploadErrorDto> errors = new ArrayList<>();
validateUserList.forEach(validateResult -> {
if(!validateResult.isSuccess()) {
errors.add(UserUploadErrorDto.of(
rowNumber,
validateResult.getFieldName(),
validateResult.getErrMessage()
));
}
});
List<DataVerificationDto> validateUserList = this.validateUserDto(dto, roleList,
intranetUserList);
return errors;
}
validateUserList.forEach(validateResult -> {
if (!validateResult.isSuccess()) {
errors.add(UserUploadErrorDto.of(
rowNumber,
validateResult.getFieldName(),
validateResult.getErrMessage()
));
}
});
private void createUserInternal(UserInfoDto userInfo, String regUser, LocalDateTime regDt) {
userInfo.setUserId(userInfo.getUserId().toLowerCase());
userInfo.setUserTeam("S101");
return errors;
}
TUserEntity entity = TUserEntity.fromDto(userInfo, regUser, regDt);
userRepository.save(entity);
}
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);
}
}