251202_01_ENH: User 관련 기능 구현

This commit is contained in:
2025-12-02 13:46:44 +09:00
parent bff9747d52
commit d13595f315
52 changed files with 1279 additions and 159 deletions

View File

@@ -1,24 +0,0 @@
package com.kri.contact.server.api.auth;
import com.kri.contact.server.api.auth.request.LoginRequestDto;
import com.kri.contact.server.api.auth.response.LoginResponseDto;
import com.kri.contact.server.application.AuthService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@Tag(name = "Auth", description = "인증 API")
public class AuthController {
private final AuthService authService;
@PostMapping("/login")
public LoginResponseDto tryLogin(@RequestBody LoginRequestDto request){
return authService.tryLogin(request);
}
}

View File

@@ -1,11 +0,0 @@
package com.kri.contact.server.api.auth.request;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LoginRequestDto {
private String userId;
private String userPw;
}

View File

@@ -0,0 +1,8 @@
package com.kri.contact.server.common.consts;
public final class AppConstant {
private AppConstant(){}
public static final Integer EXTERNAL_USER_ROLE = 4000;
public static final Integer FIELDWORK_USER_ROLE = 9000;
}

View File

@@ -0,0 +1,32 @@
package com.kri.contact.server.common.enums;
import com.kri.common.enums.CodeEnum;
public enum SystemEventType implements CodeEnum<Short> {
LOGIN((short) 11), // 로그인
LOGOUT((short) 11), // 로그인
CREAT_PROJECT((short) 21), // 프로젝트 생성
UPDATE_PROJECT((short) 22), // 프로젝트 수정
DELETE_PROJECT((short) 23), // 프로젝트 삭제
CREAT_USER((short) 31), // 사용자 생성
UPDATE_USER((short) 32), // 사용자 수정
DELETE_USER((short) 33), // 사용자 삭제
UPLOAD_USER((short) 34), // 사용자 삭제
CREAT_ROLE((short) 41), // 권한 생성
UPDATE_ROLE((short) 42), // 권한 수정
DELETE_ROLE((short) 43); // 권한 삭제
private final short code;
SystemEventType(short code) {
this.code = code;
}
@Override
public Short getCode() {
return code;
}
}

View File

@@ -1,15 +1,15 @@
package com.kri.contact.server.common.external.intranet;
import com.kri.common.http.ExternalApiClient;
import com.kri.contact.server.api.auth.request.LoginRequestDto;
import com.kri.contact.server.api.auth.response.LoginResponseDto;
import com.kri.contact.server.common.external.intranet.response.SearchLoginInfoResponseDto;
import com.kri.contact.server.dto.LoginRequestDto;
import java.util.Collections;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.kri.common.http.ExternalApiResponse;
@@ -36,7 +36,7 @@ public class IntranetExtensionApiClient {
private final ObjectMapper objectMapper = new ObjectMapper();
public SearchLoginInfoResponseDto searchLoginInfo(LoginRequestDto request) {
String url = String.format("%s/api/v1/user/search/login-info", intranetExtensionBaseUrl);
String url = String.format("%s/api/v1/user/login-info", intranetExtensionBaseUrl);
// 요구사항: ExternalApiClient.post() 사용 (시그니처: post(url, headers, body))
Map<String, String> headers = new HashMap<>();
headers.put(apiKeyHeaderName, apiKey);
@@ -44,10 +44,25 @@ public class IntranetExtensionApiClient {
String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body);
String test = response.getBody();
return objectMapper.readValue(response.getBody(), SearchLoginInfoResponseDto.class);
} catch (JsonProcessingException e) {
return null;
}
}
public List<String> getUserIdArray(){
String url = String.format("%s/api/v1/user/user-id-list", intranetExtensionBaseUrl);
Map<String, String> headers = new HashMap<>();
headers.put(apiKeyHeaderName, apiKey);
try {
ExternalApiResponse response = externalApiClient.get(url, headers);
return objectMapper.readValue(
response.getBody(),
new com.fasterxml.jackson.core.type.TypeReference<List<String>>() {}
);
} catch (JsonProcessingException e) {
return Collections.emptyList();
}
}
}

View File

@@ -1,4 +1,4 @@
package com.kri.contact.server.common.external.intranet.response;
package com.kri.contact.server.common.external.intranet;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
@@ -12,15 +12,18 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor // Builder 패턴 사용 시 필요
@Schema(description = "인트라넷 사용자 검색 응답 DTO")
public class SearchLoginInfoResponseDto {
@Schema(description = "사용자 ID (p_user_mail)")
private String userId; // final 제거
@Schema(description = "사용자 ID")
private String userId;
@Schema(description = "사용자 이름 (p_name)")
private String userNm; // final 제거
@Schema(description = "사용자 소속 회사")
private String userCmpn;
@Schema(description = "사용자 팀 (p_depart_now + p_team_now)")
private String userTeam; // final 제거
@Schema(description = "사용자 이름")
private String userNm;
@Schema(description = "사용자 팀")
private String userTeam;
@Schema(description = "사용자 역할")
private int userRole; // final 제거
private int userRole;
}

View File

@@ -0,0 +1,68 @@
package com.kri.contact.server.common.util;
import com.kri.common.excel.ExcelMapper;
import com.kri.contact.server.dto.ExcelUploadResponseDto;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.List;
public final class ExcelUploadResultUtil {
private ExcelUploadResultUtil() {}
/**
* 엑셀 업로드 결과 + 에러 엑셀 생성까지 공통 처리.
*
* @param totalCount 전체 행 수
* @param successCount 성공 개수
* @param errorList 에러 DTO 리스트
* @param errorClass 에러 DTO 타입 (ExcelMapper용)
* @param errorFileName 에러 엑셀 파일명
*/
public static <E> ExcelUploadResponseDto buildUploadResult(
int totalCount,
int successCount,
List<E> errorList,
Class<E> errorClass,
String errorFileName
) {
int failCount = (errorList != null) ? errorList.size() : 0;
// 1) 에러가 없으면 파일 없이 반환
if (failCount == 0) {
return ExcelUploadResponseDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(0)
.hasErrorFile(false)
.build();
}
// 2) 에러가 있으면 에러 리스트를 엑셀로 생성
try (Workbook errorWb = ExcelMapper.writeToWorkbook(errorList, errorClass);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
errorWb.write(bos);
byte[] bytes = bos.toByteArray();
String base64 = Base64.getEncoder().encodeToString(bytes);
return ExcelUploadResponseDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(failCount)
.hasErrorFile(true)
.errorFileName(errorFileName)
.errorFileBase64(base64)
.build();
} catch (Exception e) {
// 에러 파일 생성 실패해도 업로드 결과는 그대로 리턴
return ExcelUploadResponseDto.builder()
.totalCount(totalCount)
.successCount(successCount)
.failCount(failCount)
.hasErrorFile(false)
.build();
}
}
}

View File

@@ -0,0 +1,34 @@
package com.kri.contact.server.controller;
import com.kri.common.webmvc.RequestUserContext;
import com.kri.contact.server.dto.LoginRequestDto;
import com.kri.contact.server.dto.LoginResponseDto;
import com.kri.contact.server.service.AuthService;
import com.kri.contact.server.service.SystemEventLogService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@Tag(name = "Auth", description = "인증 API")
public class AuthController {
private final AuthService authService;
private final SystemEventLogService systemEventLogService;
@PostMapping("/login")
public LoginResponseDto tryLogin(@RequestBody LoginRequestDto request, RequestUserContext ctx){
LoginResponseDto response = authService.tryLogin(request);
systemEventLogService.writeLoginLog(response.getUser().getUserId(), ctx.getClientIp());
return response;
}
@PostMapping("/logout/{userId}")
public boolean logout(@PathVariable String userId, RequestUserContext ctx){
systemEventLogService.writeLogoutLog(userId, ctx.getClientIp());
return true;
}
}

View File

@@ -0,0 +1,25 @@
package com.kri.contact.server.controller;
import com.kri.common.webmvc.RequestUserContext;
import com.kri.contact.server.dto.RoleInfoDto;
import com.kri.contact.server.service.RoleService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/v1/role")
@RequiredArgsConstructor
@Tag(name = "Role", description = "권한 관리 API")
public class RoleController {
private final RoleService roleService;
@GetMapping()
public List<RoleInfoDto> getRoleList(RequestUserContext ctx){
return roleService.getRoleList(ctx.getUserRole());
}
}

View File

@@ -0,0 +1,119 @@
package com.kri.contact.server.controller;
import com.kri.common.webmvc.RequestUserContext;
import com.kri.contact.server.common.consts.AppConstant;
import com.kri.contact.server.dto.DataVerificationDto;
import com.kri.contact.server.dto.ExcelUploadResponseDto;
import com.kri.contact.server.dto.UserInfoDto;
import com.kri.contact.server.dto.systemlog.UploadUserContentDto;
import com.kri.contact.server.service.SystemEventLogService;
import com.kri.contact.server.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Collections;
import java.util.List;
@RestController
@RequestMapping("/api/v1/user")
@RequiredArgsConstructor
@Tag(name = "User", description = "사용자 관리 API")
public class UserController {
private final UserService userService;
private final SystemEventLogService systemEventLogService;
@GetMapping("/check-user-id")
public DataVerificationDto checkUserId(@RequestParam String userId){
return userService.checkUserId(userId);
}
@GetMapping("/{userId}")
public UserInfoDto getUser(@PathVariable String userId){
return userService.getUser(userId);
}
@GetMapping()
public List<UserInfoDto> getUserList(RequestUserContext ctx){
//내부 직원
if(ctx.getUserRole() < AppConstant.EXTERNAL_USER_ROLE){
return userService.getUserListWithCmpn("");
}
//외주사 이상
return userService.getUserListWithCmpn(ctx.getUserCmpn());
}
@GetMapping("cmpn")
public List<String> getUserCmpnList(RequestUserContext ctx){
if(ctx.getUserRole() < AppConstant.EXTERNAL_USER_ROLE){
return userService.getUserCmpnList();
}
return Collections.emptyList();
}
@PutMapping
public void createUser(@RequestBody UserInfoDto userInfo, RequestUserContext ctx){
String regId = ctx.getUserId();
String clientIp = ctx.getClientIp();
userService.createUser(userInfo, regId);
systemEventLogService.writeCreatUserLog(regId, clientIp, userInfo);
}
@PostMapping("/excel")
public ExcelUploadResponseDto createUserFromExcel(
@RequestPart("file") MultipartFile file,
RequestUserContext ctx
) {
String regId = ctx.getUserId();
String clientIp = ctx.getClientIp();
//외주사급이 업로드로 계정을 생성하는 경우 자신의 회사명으로 고정
String forceCmpn = ctx.getUserRole() < AppConstant.EXTERNAL_USER_ROLE? "" : ctx.getUserCmpn();
ExcelUploadResponseDto result = userService.createUsersFromExcel(file, regId, forceCmpn);
UploadUserContentDto content = new UploadUserContentDto(
file.getOriginalFilename(),
file.getContentType(),
file.getSize()
);
systemEventLogService.writeUploadUserLog(regId, clientIp, content);
return result;
}
@PostMapping("/excel/template")
public ResponseEntity<byte[]> exportUserTemplate(){
byte[] bytes = userService.exportUserTemplate();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"user_upload_template.xlsx\"")
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
@PatchMapping()
public void updateUser(@RequestBody UserInfoDto dto, RequestUserContext ctx){
String modId = ctx.getUserId();
String clientIp = ctx.getClientIp();
userService.updateUser(dto, modId);
systemEventLogService.writeUpdateUserLog(modId, clientIp, dto);
}
@DeleteMapping("/{userId}")
public void deleteUser(@PathVariable String userId, RequestUserContext ctx){
String regId = ctx.getUserId();
String clientIp = ctx.getClientIp();
userService.deleteUser(userId, regId);
systemEventLogService.writeDeleteUserLog(regId, clientIp, userId);
}
}

View File

@@ -0,0 +1,29 @@
package com.kri.contact.server.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
@AllArgsConstructor
@Schema(description = "데이터 검증에 대한 공용 Dto")
public class DataVerificationDto {
@Schema(description = "데이터 검증 통과 여부")
private boolean success;
@Schema(description = "검증 필드명")
private String fieldName;
@Schema(description = "검증 메시지(error)")
private String errMessage;
public DataVerificationDto() {
this.success = true;
this.fieldName = "";
this.errMessage = "";
}
}

View File

@@ -0,0 +1,30 @@
package com.kri.contact.server.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class ExcelUploadResponseDto {
@Schema(description = "전체 읽은 행 수 (헤더 제외)")
private int totalCount;
@Schema(description = "DB에 실제로 insert/update 성공한 개수")
private int successCount;
@Schema(description = "실패(에러) 개수")
private int failCount;
@Schema(description = "에러 엑셀 파일이 있는지 여부")
private boolean hasErrorFile;
@Schema(description = "프론트가 저장용으로 쓸 파일명")
private String errorFileName;
@Schema(description = "에러 엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
private String errorFileBase64;
}

View File

@@ -0,0 +1,16 @@
package com.kri.contact.server.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "사용자 로그인 요청")
public class LoginRequestDto {
@Schema(description = "사용자 ID")
private String userId;
@Schema(description = "사용자 PW")
private String userPw;
}

View File

@@ -1,14 +1,18 @@
package com.kri.contact.server.api.auth.response;
package com.kri.contact.server.dto;
import com.kri.common.auth.jwt.JwtUserClaimsDto;
import com.kri.contact.server.persistence.entity.TUserEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Schema(description = "로그인 응답")
public class LoginResponseDto {
@Schema(description = "jwt access 토큰")
private String accessToken;
@Schema(description = "사용자 정보")
private JwtUserClaimsDto user;
public static LoginResponseDto from(String accessToken, JwtUserClaimsDto jwtUserClaims){

View File

@@ -0,0 +1,54 @@
package com.kri.contact.server.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.contact.server.persistence.entity.TRoleEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@Builder
@Schema(description = "권한 정보")
public class RoleInfoDto {
@Schema(description = "권한 코드")
private Integer roleCd;
@Schema(description = "권한 명")
private String roleNm;
@Schema(description = "메모")
private String memo;
@Schema(description = "등록자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String regUser;
@Schema(description = "등록일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
@Schema(description = "수정자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String modUser;
@Schema(description = "수정일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime modDt;
public static RoleInfoDto from(TRoleEntity roleEntity){
return RoleInfoDto.builder()
.roleCd(roleEntity.getRoleCd())
.roleNm(roleEntity.getRoleNm())
.memo(roleEntity.getMemo())
.regUser(roleEntity.getRegUser())
.regDt(roleEntity.getRegDt())
.modUser(roleEntity.getModUser())
.modDt(roleEntity.getModDt())
.build();
}
}

View File

@@ -0,0 +1,84 @@
package com.kri.contact.server.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.common.datetime.DateTimeUtil;
import com.kri.contact.server.dto.excel.UserUploadDto;
import com.kri.contact.server.persistence.entity.TUserEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.time.LocalDateTime;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "사용자 정보")
public class UserInfoDto {
@Schema(description = "사용자 ID")
private String userId;
@Schema(description = "사용자 PW")
private String userPw;
@Schema(description = "사용자 이름")
private String userName;
@Schema(description = "사용자 소속 회사")
private String userCmpn;
@Schema(description = "사용자 소속 팀")
private String userTeam = "S101";
@Schema(description = "사용자 권한")
private Integer userRole;
@Schema(description = "메모")
private String memo;
@Schema(description = "등록자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String regUser;
@Schema(description = "등록일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
@Schema(description = "수정자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String modUser;
@Schema(description = "수정일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime modDt;
public static UserInfoDto from(TUserEntity entity){
return UserInfoDto.builder()
.userId(entity.getUserId())
.userName(entity.getUserNm())
.userCmpn(entity.getUserCmpn())
.userTeam(entity.getUserTeam())
.userRole(entity.getUserRole())
.memo(entity.getMemo())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.modUser(entity.getModUser())
.modDt(entity.getModDt())
.build();
}
public static UserInfoDto from(UserUploadDto dto, Integer userRole, String regUser){
return UserInfoDto.builder()
.userId(dto.getUserId())
.userPw(dto.getUserPw())
.userName(dto.getUserName())
.userCmpn(dto.getUserCmpn())
.userTeam("S101")
.userRole(userRole)
.memo(dto.getMemo())
.regUser(regUser)
.regDt(DateTimeUtil.nowKstLocalDateTime())
.build();
}
}

View File

@@ -0,0 +1,27 @@
package com.kri.contact.server.dto.excel;
import com.kri.common.excel.ExcelColumn;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ExcelErrorDto {
@ExcelColumn(header = "행 번호", order = 0)
private int rowNumber;
@ExcelColumn(header = "필드명", order = 1)
private String fieldName;
@ExcelColumn(header = "에러 메시지", order = 2)
private String errorMessage;
public static ExcelErrorDto of(int rowNumber, String fieldName, String errorMessage) {
ExcelErrorDto dto = new ExcelErrorDto();
dto.setRowNumber(rowNumber);
dto.setFieldName(fieldName);
dto.setErrorMessage(errorMessage);
return dto;
}
}

View File

@@ -0,0 +1,36 @@
package com.kri.contact.server.dto.excel;
import com.kri.common.excel.ExcelColumn;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserUploadDto {
@ExcelColumn(header = "사용자 ID", order = 0, width = 11)
@Schema(description = "사용자 ID")
private String userId;
@ExcelColumn(header = "사용자 PW", order = 1, width = 11)
@Schema(description = "사용자 PW")
private String userPw;
@ExcelColumn(header = "사용자 이름", order = 2, width = 11)
@Schema(description = "사용자 이름")
private String userName;
@ExcelColumn(header = "사용자 소속 회사", order = 3, width = 16)
@Schema(description = "사용자 소속 회사")
private String userCmpn;
@ExcelColumn(header = "사용자 권한", order = 4, width = 11)
@Schema(description = "사용자 권한")
private String userRoleStr;
@ExcelColumn(header = "메모", order = 5, width = 20)
@Schema(description = "메모")
private String memo;
}

View File

@@ -0,0 +1,19 @@
package com.kri.contact.server.dto.excel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class UserUploadErrorDto extends ExcelErrorDto {
public static UserUploadErrorDto of(int rowNumber, String fieldName, String errorMessage) {
UserUploadErrorDto dto = new UserUploadErrorDto();
dto.setRowNumber(rowNumber);
dto.setFieldName(fieldName);
dto.setErrorMessage(errorMessage);
return dto;
}
}

View File

@@ -0,0 +1,15 @@
package com.kri.contact.server.dto.systemlog;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@AllArgsConstructor
public class UploadUserContentDto {
String fileName;
String fileType;
Long fileSize;
}

View File

@@ -0,0 +1,12 @@
package com.kri.contact.server.dto.systemlog;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@AllArgsConstructor
public class UserIdContentDto {
private String userId;
}

View File

@@ -1,26 +0,0 @@
package com.kri.contact.server.persistence.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "t_event_ty_dic")
public class TEventTyDicEntity {
@Id
@Column(name = "event_ty", nullable = false)
private Short eventTy;
@Size(max = 64)
@NotNull
@Column(name = "event_ty_nm", nullable = false, length = 64)
private String eventTyNm;
}

View File

@@ -25,7 +25,7 @@ public class TFuncEntity {
@NotNull
@ColumnDefault("1")
@Column(name = "is_menu", nullable = false)
private Boolean isMenu = false;
private Boolean menu = false;
@NotNull
@Column(name = "depth", nullable = false)

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -40,13 +40,13 @@ public class TListAssignEntity {
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt")
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@Column(name = "exc_user", length = 32)
private String excUser;
@Column(name = "exc_dt")
private Instant excDt;
private LocalDateTime excDt;
}

View File

@@ -10,7 +10,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -22,7 +22,7 @@ public class TListEntity {
@NotNull
@Column(name = "is_use", nullable = false)
private Short isUse;
private Short use;
@Size(max = 2048)
@Column(name = "memo", length = 2048)
@@ -36,7 +36,7 @@ public class TListEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@@ -45,7 +45,7 @@ public class TListEntity {
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
private LocalDateTime modDt;
public Long getPrjctIdx(){
return id.getPrjctIdx();

View File

@@ -7,7 +7,8 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -43,6 +44,6 @@ public class TListEventHistEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
}

View File

@@ -10,7 +10,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -57,7 +57,7 @@ public class TListHeaderEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@@ -66,7 +66,7 @@ public class TListHeaderEntity {
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
private LocalDateTime modDt;
public Long getPrjctIdx(){
return id.getPrjctIdx();

View File

@@ -15,7 +15,7 @@ import java.util.Objects;
@Embeddable
public class TListHeaderEntityId implements Serializable {
private static final long serialVersionUID = -1296812261527497087L;
@Column(name = "prjct_idx", columnDefinition = "int UNSIGNED not null")
@Column(name = "prjct_idx", insertable = false, updatable = false, columnDefinition = "int UNSIGNED not null")
private Long prjctIdx;
@NotNull

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -30,7 +30,7 @@ public class TListItemEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@@ -39,7 +39,7 @@ public class TListItemEntity {
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
private LocalDateTime modDt;
public Long getPrjctIdx(){
return id.getPrjctIdx();

View File

@@ -10,7 +10,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -39,7 +39,7 @@ public class TListItemUploadEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@@ -48,7 +48,7 @@ public class TListItemUploadEntity {
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
private LocalDateTime modDt;
public Long getPrjctIdx(){
return id.getPrjctIdx();

View File

@@ -9,7 +9,7 @@ import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Map;
@Getter
@@ -56,6 +56,6 @@ public class TListResetLogEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
}

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -38,7 +38,7 @@ public class TListResveEntity {
@NotNull
@Column(name = "resve_dt", nullable = false)
private Instant resveDt;
private LocalDateTime resveDt;
@Size(max = 32)
@NotNull
@@ -53,6 +53,6 @@ public class TListResveEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
}

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -48,6 +48,6 @@ public class TListUpdateHistEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
}

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -46,7 +46,7 @@ public class TListUploadLogEntity {
@NotNull
@Column(name = "is_success", nullable = false)
private Boolean isSuccess = false;
private Boolean success = false;
@Size(max = 32)
@NotNull
@@ -56,6 +56,6 @@ public class TListUploadLogEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
}

View File

@@ -10,7 +10,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -28,7 +28,7 @@ public class TPrjctAssignEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
public Long getPrjctIdx(){
return id.getPrjctIdx();

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -79,7 +79,7 @@ public class TPrjctEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@@ -88,18 +88,17 @@ public class TPrjctEntity {
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
private LocalDateTime modDt;
@NotNull
@ColumnDefault("0")
@Column(name = "is_del", nullable = false)
private Boolean isDel = false;
private Boolean del = false;
@Size(max = 32)
@Column(name = "del_user", length = 32)
private String delUser;
@Column(name = "del_dt")
private Instant delDt;
private LocalDateTime delDt;
}

View File

@@ -10,7 +10,7 @@ import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -32,7 +32,7 @@ public class TResultCodeEntity {
@NotNull
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@@ -41,7 +41,7 @@ public class TResultCodeEntity {
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
private LocalDateTime modDt;
public Long getPrjctIdx(){
return id.getPrjctIdx();

View File

@@ -7,7 +7,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -36,15 +36,15 @@ public class TRoleEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@Column(name = "mod_user", nullable = false, length = 32)
@Column(name = "mod_user", length = 32)
private String modUser;
@NotNull
@Column(name = "mod_dt", nullable = false)
private Instant modDt;
@Column(name = "mod_dt")
private LocalDateTime modDt;
}

View File

@@ -10,7 +10,7 @@ import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -28,7 +28,7 @@ public class TRoleFuncMapEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
public Integer getRoleCd(){
return id.getRoleCd();

View File

@@ -1,20 +1,21 @@
package com.kri.contact.server.persistence.entity;
import com.kri.common.datetime.DateTimeUtil;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Map;
@Getter
@Setter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(name = "t_sys_event_log")
public class TSysEventLogEntity {
@Id
@@ -52,6 +53,23 @@ public class TSysEventLogEntity {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
private LocalDateTime regDt;
@Builder
private TSysEventLogEntity(
Short eventTy,
String logTitle,
Map<String, Object> logContent,
Long prjctIdx,
String ip,
String regUser
) {
this.eventTy = eventTy;
this.logTitle = logTitle;
this.logContent = logContent;
this.prjctIdx = prjctIdx;
this.ip = ip;
this.regUser = regUser;
this.regDt = DateTimeUtil.nowKstLocalDateTime();
}
}

View File

@@ -1,13 +1,14 @@
package com.kri.contact.server.persistence.entity;
import com.kri.common.datetime.DateTimeUtil;
import com.kri.contact.server.dto.UserInfoDto;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Setter
@@ -21,7 +22,7 @@ public class TUserEntity {
@Size(max = 32)
@NotNull
@Column(name = "user_id", nullable = false, length = 32)
@Column(name = "user_id", nullable = false, length = 32, updatable = false)
private String userId;
@Size(max = 128)
@@ -29,6 +30,12 @@ public class TUserEntity {
@Column(name = "user_pw", nullable = false, length = 128)
private String userPw;
@Size(max = 32)
@NotNull
@ColumnDefault("'KRI'")
@Column(name = "user_cmpn", nullable = false, length = 32, updatable = false)
private String userCmpn;
@Size(max = 32)
@NotNull
@Column(name = "user_nm", nullable = false, length = 32)
@@ -37,7 +44,7 @@ public class TUserEntity {
@Size(max = 32)
@NotNull
@ColumnDefault("'S101'")
@Column(name = "user_team", nullable = false, length = 32)
@Column(name = "user_team", nullable = false, length = 32, updatable = false)
private String userTeam;
@NotNull
@@ -51,21 +58,64 @@ public class TUserEntity {
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
@Column(name = "reg_user", nullable = false, length = 32, updatable = false)
private String regUser;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private Instant regDt;
@Column(name = "reg_dt", nullable = false, updatable = false)
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@Column(name = "mod_user", length = 32)
@Column(name = "mod_user", length = 32, insertable = false)
private String modUser;
@NotNull
@Column(name = "mod_dt")
private Instant modDt;
private LocalDateTime modDt;
@NotNull
@ColumnDefault("0")
@Column(name = "is_del", nullable = false)
private Boolean del = false;
@Size(max = 32)
@Column(name = "del_user", length = 32)
private String delUser;
@Column(name = "del_dt")
private LocalDateTime delDt;
public static TUserEntity fromDto(UserInfoDto dto, String regUser) {
TUserEntity entity = new TUserEntity();
entity.setUserId(dto.getUserId());
entity.setUserPw(dto.getUserPw());
entity.setUserNm(dto.getUserName());
entity.setUserCmpn(dto.getUserCmpn());
entity.setUserTeam(
dto.getUserTeam() != null && !dto.getUserTeam().isBlank()
? dto.getUserTeam()
: "S101"// DB 기본값과 맞춰서 디폴트 세팅
);
entity.setUserRole(dto.getUserRole());
entity.setMemo(dto.getMemo() != null ? dto.getMemo() : "");
entity.setRegUser(regUser);
entity.setRegDt(DateTimeUtil.nowKstLocalDateTime());
return entity;
}
public void updateFromDto(UserInfoDto dto, String modUser) {
// 비번은 값이 있을 때만 변경
if (dto.getUserPw() != null && !dto.getUserPw().isBlank()) {
this.userPw = dto.getUserPw();
}
this.userNm = dto.getUserName();
this.userRole = dto.getUserRole();
this.memo = (dto.getMemo() != null) ? dto.getMemo() : "";
this.modUser = modUser;
this.modDt = DateTimeUtil.nowKstLocalDateTime();
}
}

View File

@@ -0,0 +1,11 @@
package com.kri.contact.server.persistence.repository;
import com.kri.contact.server.persistence.entity.TRoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
public interface RoleRepository extends JpaRepository<TRoleEntity, Long>, JpaSpecificationExecutor<TRoleEntity> {
List<TRoleEntity> findByRoleCdGreaterThanEqual(Integer roleCd);
}

View File

@@ -0,0 +1,8 @@
package com.kri.contact.server.persistence.repository;
import com.kri.contact.server.persistence.entity.TSysEventLogEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface SystemEventLogRepository extends JpaRepository<TSysEventLogEntity, Long>, JpaSpecificationExecutor<TSysEventLogEntity> {
}

View File

@@ -3,7 +3,39 @@ package com.kri.contact.server.persistence.repository;
import com.kri.contact.server.persistence.entity.TUserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface UserRepository extends JpaRepository<TUserEntity, Long>, JpaSpecificationExecutor<TUserEntity> {
TUserEntity findByUserIdAndUserPw(String userId, String userPw);
}
Optional<TUserEntity> findByUserIdAndUserPwAndDelFalse(String userId, String userPw);
Optional<TUserEntity> findByUserIdAndDelFalse(String userId);
List<TUserEntity> findByUserCmpnAndUserRoleGreaterThanEqualAndDelFalse(String userCmpn, Integer userRoleCd);
@Query("""
select distinct u.userCmpn
from TUserEntity u
where u.userCmpn is not null and u.userCmpn <> ''
and u.del = false
order by u.userCmpn
""")
List<String> findDistinctUserCmpnAndDelFalse();
boolean existsByUserIdAndDelFalse(String userId);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TUserEntity u
set u.del = true,
u.delUser = :delUser,
u.delDt = :delDt
where u.userId = :userId
and u.del = false
""")
int softDeleteByUserId(String userId, String delUser, LocalDateTime delDt);
}

View File

@@ -1,14 +1,12 @@
package com.kri.contact.server.application;
package com.kri.contact.server.service;
import com.kri.common.auth.jwt.JwtService;
import com.kri.common.auth.jwt.JwtUserClaimsDto;
import com.kri.common.web.BusinessException;
import com.kri.contact.server.api.auth.request.LoginRequestDto;
import com.kri.contact.server.api.auth.response.LoginResponseDto;
import com.kri.contact.server.dto.LoginRequestDto;
import com.kri.contact.server.dto.LoginResponseDto;
import com.kri.contact.server.common.external.intranet.IntranetExtensionApiClient;
import com.kri.contact.server.common.external.intranet.response.SearchLoginInfoResponseDto;
import com.kri.contact.server.common.external.intranet.SearchLoginInfoResponseDto;
import com.kri.contact.server.persistence.entity.TUserEntity;
import com.kri.contact.server.persistence.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -16,8 +14,9 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor
public class AuthService {
private final JwtService jwtService;
private final UserService userService;
private final IntranetExtensionApiClient intranetExtensionApiClient;
private final UserRepository userRepository;
public LoginResponseDto tryLogin(LoginRequestDto request){
SearchLoginInfoResponseDto loginInfoResponse = intranetExtensionApiClient.searchLoginInfo(request);
@@ -26,20 +25,17 @@ public class AuthService {
if(loginInfoResponse != null){
claims = JwtUserClaimsDto.builder()
.userId(loginInfoResponse.getUserId())
.userCmpn(loginInfoResponse.getUserCmpn())
.userName(loginInfoResponse.getUserNm())
.userTeam(loginInfoResponse.getUserTeam())
.userRole(loginInfoResponse.getUserRole())
.build();
}
else{
TUserEntity user = userRepository.findByUserIdAndUserPw(request.getUserId(), request.getUserPw());
if(user == null){
throw BusinessException.forbidden("USER_NOT_FOUND", "사용자가 없습니다.")
.with("userId", request.getUserId());
}
TUserEntity user = userService.getUser(request.getUserId(), request.getUserPw());
claims = JwtUserClaimsDto.builder()
.userId(user.getUserId())
.userCmpn(user.getUserCmpn())
.userName(user.getUserNm())
.userTeam(user.getUserTeam())
.userRole(user.getUserRole())

View File

@@ -0,0 +1,32 @@
package com.kri.contact.server.service;
import com.kri.contact.server.common.consts.AppConstant;
import com.kri.contact.server.dto.RoleInfoDto;
import com.kri.contact.server.persistence.repository.RoleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class RoleService {
private final RoleRepository roleRepository;
public List<RoleInfoDto> getRoleList(){
return roleRepository.findAll().stream()
.map(RoleInfoDto::from)
.toList();
}
public List<RoleInfoDto> getRoleList(Integer roleCd){
Integer searchRoleCd = roleCd < AppConstant.EXTERNAL_USER_ROLE ?
AppConstant.EXTERNAL_USER_ROLE :
AppConstant.FIELDWORK_USER_ROLE;
return roleRepository.findByRoleCdGreaterThanEqual(searchRoleCd).stream()
.map(RoleInfoDto::from)
.toList();
}
}

View File

@@ -0,0 +1,71 @@
package com.kri.contact.server.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.contact.server.dto.UserInfoDto;
import com.kri.contact.server.dto.systemlog.UploadUserContentDto;
import com.kri.contact.server.dto.systemlog.UserIdContentDto;
import com.kri.contact.server.common.enums.SystemEventType;
import com.kri.contact.server.persistence.entity.TSysEventLogEntity;
import com.kri.contact.server.persistence.repository.SystemEventLogRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Map;
import static com.kri.common.json.JsonUtil.toMap;
@Service
@RequiredArgsConstructor
public class SystemEventLogService {
private final ObjectMapper objectMapper;
private final SystemEventLogRepository systemEventLogRepository;
public void writeLoginLog(String userId, String clientIp) {
UserIdContentDto content = new UserIdContentDto(userId);
writeSystemLog(SystemEventType.LOGIN, "Login", null, userId, clientIp, content);
}
public void writeLogoutLog(String userId, String clientIp) {
UserIdContentDto content = new UserIdContentDto(userId);
writeSystemLog(SystemEventType.LOGOUT, "Logout", null, userId, clientIp, content);
}
public void writeCreatUserLog(String regId, String clientIp, UserInfoDto userInfo){
writeSystemLog(SystemEventType.CREAT_USER, "Create User", null, regId, clientIp, userInfo);
}
public void writeUploadUserLog(String regId, String clientIp, UploadUserContentDto content){
writeSystemLog(SystemEventType.UPLOAD_USER, "Upload User", null, regId, clientIp, content);
}
public void writeUpdateUserLog(String regId, String clientIp, UserInfoDto userInfo){
writeSystemLog(SystemEventType.UPDATE_USER, "Update User", null, regId, clientIp, userInfo);
}
public void writeDeleteUserLog(String regId, String clientIp, String userId){
UserIdContentDto content = new UserIdContentDto(userId);
writeSystemLog(SystemEventType.DELETE_USER, "Delete User", null, regId, clientIp, content);
}
private <T> void writeSystemLog(
SystemEventType eventType,
String title,
Long prjctIdx,
String regId,
String clientIp,
T content
) {
Map<String, Object> contentMap = toMap(objectMapper, content);
TSysEventLogEntity log = TSysEventLogEntity.builder()
.eventTy(eventType.getCode())
.logTitle(title)
.logContent(contentMap)
.prjctIdx(prjctIdx)
.ip(clientIp)
.regUser(regId)
.build();
systemEventLogRepository.save(log);
}
}

View 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);
}
}