diff --git a/src/main/java/com/kamco/cd/kamcoback/code/CommonCodeApiController.java b/src/main/java/com/kamco/cd/kamcoback/code/CommonCodeApiController.java index a5dbe6e6..8a3749b9 100644 --- a/src/main/java/com/kamco/cd/kamcoback/code/CommonCodeApiController.java +++ b/src/main/java/com/kamco/cd/kamcoback/code/CommonCodeApiController.java @@ -30,19 +30,19 @@ public class CommonCodeApiController { private final CommonCodeService commonCodeService; - @Operation(summary = "목록 조회", description = "모든 공통코드 조회") + @Operation(summary = "목록 조회", description = "모든 공통코드 조회") @ApiResponses( - value = { - @ApiResponse( - responseCode = "200", - description = "조회 성공", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = CommonCodeDto.Basic.class))), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "200", + description = "조회 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = CommonCodeDto.Basic.class))), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @GetMapping public ApiResponseDto> getFindAll() { return ApiResponseDto.createOK(commonCodeService.getFindAll()); @@ -50,139 +50,160 @@ public class CommonCodeApiController { @Operation(summary = "단건 조회", description = "단건 조회") @ApiResponses( - value = { - @ApiResponse( - responseCode = "200", - description = "조회 성공", - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = CommonCodeDto.Basic.class))), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "200", + description = "조회 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = CommonCodeDto.Basic.class))), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @GetMapping("/{id}") public ApiResponseDto getOneById( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "단건 조회", - required = true) - @PathVariable Long id) { + @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "단건 조회", required = true) + @PathVariable + Long id) { return ApiResponseDto.ok(commonCodeService.getOneById(id)); } @Operation(summary = "저장", description = "공통코드를 저장 합니다.") @ApiResponses( - value = { - @ApiResponse(responseCode = "201", description = "공통코드 저장 성공", content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = Long.class))), - @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "201", + description = "공통코드 저장 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = Long.class))), + @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @PostMapping public ApiResponseDto save( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "공통코드 생성 요청 정보", - required = true, - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = CommonCodeDto.AddReq.class))) - @RequestBody - @Valid CommonCodeDto.AddReq req) { + @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "공통코드 생성 요청 정보", + required = true, + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = CommonCodeDto.AddReq.class))) + @RequestBody + @Valid + CommonCodeDto.AddReq req) { return ApiResponseDto.createOK(commonCodeService.save(req)); } @Operation(summary = "수정", description = "공통코드를 수정 합니다.") @ApiResponses( - value = { - @ApiResponse(responseCode = "204", description = "공통코드 수정 성공", content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = Long.class))), - @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "204", + description = "공통코드 수정 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = Long.class))), + @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @PutMapping("/{id}") public ApiResponseDto update( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "공통코드 수정 요청 정보", - required = true, - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = CommonCodeDto.ModifyReq.class))) - @PathVariable Long id, @RequestBody @Valid CommonCodeDto.ModifyReq req) { + @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "공통코드 수정 요청 정보", + required = true, + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = CommonCodeDto.ModifyReq.class))) + @PathVariable + Long id, + @RequestBody @Valid CommonCodeDto.ModifyReq req) { commonCodeService.update(id, req); return ApiResponseDto.deleteOk(null); } @Operation(summary = "삭제", description = "공통코드를 삭제 합니다.") @ApiResponses( - value = { - @ApiResponse(responseCode = "204", description = "공통코드 삭제 성공", content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = Long.class))), - @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "204", + description = "공통코드 삭제 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = Long.class))), + @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @DeleteMapping("/{id}") public ApiResponseDto remove( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "공통코드 삭제 요청 정보", - required = true) - @PathVariable Long id) { - commonCodeService.remove(id); + @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "공통코드 삭제 요청 정보", + required = true) + @PathVariable + Long id) { + commonCodeService.remove(id); return ApiResponseDto.deleteOk(id); } @Operation(summary = "순서 변경", description = "공통코드 순서를 변경 합니다.") @ApiResponses( - value = { - @ApiResponse(responseCode = "204", description = "공통코드 순서 변경 성공", content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = Long.class))), - @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "204", + description = "공통코드 순서 변경 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = Long.class))), + @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @PutMapping("/order") public ApiResponseDto updateOrder( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "공통코드 순서변경 요청 정보", - required = true, - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = CommonCodeDto.OrderReq.class))) - @RequestBody @Valid CommonCodeDto.OrderReq req) { - commonCodeService.updateOrder(req); + @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "공통코드 순서변경 요청 정보", + required = true, + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = CommonCodeDto.OrderReq.class))) + @RequestBody + @Valid + CommonCodeDto.OrderReq req) { + commonCodeService.updateOrder(req); return ApiResponseDto.deleteOk(null); } @Operation(summary = "code 기반 조회", description = "code 기반 조회") @ApiResponses( - value = { - @ApiResponse(responseCode = "200", description = "공통코드 순서 변경 성공", content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = Long.class))), - @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), - @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) - }) + value = { + @ApiResponse( + responseCode = "200", + description = "공통코드 순서 변경 성공", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = Long.class))), + @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content), + @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content) + }) @GetMapping("/used") public ApiResponseDto> getByCode( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "공통코드 순서변경 요청 정보", - required = true) - @RequestParam String code) { + @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "공통코드 순서변경 요청 정보", + required = true) + @RequestParam + String code) { return ApiResponseDto.ok(commonCodeService.findByCode(code)); } } diff --git a/src/main/java/com/kamco/cd/kamcoback/code/dto/CommonCodeDto.java b/src/main/java/com/kamco/cd/kamcoback/code/dto/CommonCodeDto.java index b30cf2db..0c8c5c48 100644 --- a/src/main/java/com/kamco/cd/kamcoback/code/dto/CommonCodeDto.java +++ b/src/main/java/com/kamco/cd/kamcoback/code/dto/CommonCodeDto.java @@ -1,13 +1,10 @@ package com.kamco.cd.kamcoback.code.dto; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.kamco.cd.kamcoback.common.utils.interfaces.JsonFormatDttm; -import com.kamco.cd.kamcoback.postgres.entity.CommonCodeEntity; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.PositiveOrZero; import java.time.ZonedDateTime; import java.util.List; import lombok.AllArgsConstructor; @@ -15,7 +12,6 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; - public class CommonCodeDto { @Schema(name = "CodeAddReq", description = "공통코드 저장 정보") @@ -25,10 +21,8 @@ public class CommonCodeDto { @AllArgsConstructor public static class AddReq { - @NotEmpty - private String code; - @NotEmpty - private String name; + @NotEmpty private String code; + @NotEmpty private String name; private String description; private int order; private boolean used; @@ -41,8 +35,7 @@ public class CommonCodeDto { @NoArgsConstructor @AllArgsConstructor public static class ModifyReq { - @NotEmpty - private String name; + @NotEmpty private String name; private String description; private int order; private boolean used; @@ -54,8 +47,7 @@ public class CommonCodeDto { @NoArgsConstructor @AllArgsConstructor public static class OrderReq { - @Valid - List orders; + @Valid List orders; } @Getter @@ -63,11 +55,9 @@ public class CommonCodeDto { @NoArgsConstructor @AllArgsConstructor public static class OrderReqDetail { - @NotNull - private Long id; + @NotNull private Long id; - @NotNull - private Integer order; + @NotNull private Integer order; } @Schema(name = "CommonCode Basic", description = "공통코드 기본 정보") @@ -83,23 +73,21 @@ public class CommonCodeDto { private Boolean deleted; private List children; - @JsonFormatDttm - private ZonedDateTime createdDttm; + @JsonFormatDttm private ZonedDateTime createdDttm; - @JsonFormatDttm - private ZonedDateTime updatedDttm; + @JsonFormatDttm private ZonedDateTime updatedDttm; public Basic( - Long id, - String code, - String description, - String name, - Integer order, - Boolean used, - Boolean deleted, - List children, - ZonedDateTime createdDttm, - ZonedDateTime updatedDttm) { + Long id, + String code, + String description, + String name, + Integer order, + Boolean used, + Boolean deleted, + List children, + ZonedDateTime createdDttm, + ZonedDateTime updatedDttm) { this.id = id; this.code = code; this.description = description; diff --git a/src/main/java/com/kamco/cd/kamcoback/code/service/CommonCodeService.java b/src/main/java/com/kamco/cd/kamcoback/code/service/CommonCodeService.java index 54261d81..7ae65f90 100644 --- a/src/main/java/com/kamco/cd/kamcoback/code/service/CommonCodeService.java +++ b/src/main/java/com/kamco/cd/kamcoback/code/service/CommonCodeService.java @@ -17,9 +17,9 @@ public class CommonCodeService { private final CommonCodeCoreService commonCodeCoreService; - /** * 공통코드 목록 조회 + * * @return 모튼 코드 정보 */ public List getFindAll() { @@ -28,6 +28,7 @@ public class CommonCodeService { /** * 공통코드 단건 조회 + * * @param id * @return 코드 아이디로 조회한 코드 정보 */ @@ -37,6 +38,7 @@ public class CommonCodeService { /** * 공통코드 생성 요청 + * * @param req 생성요청 정보 * @return 생성된 코드 id */ @@ -47,6 +49,7 @@ public class CommonCodeService { /** * 공통코드 수정 요청 + * * @param id 코드 아이디 * @param req 수정요청 정보 */ @@ -57,6 +60,7 @@ public class CommonCodeService { /** * 공통코드 삭제 처리 + * * @param id 코드 아이디 */ @Transactional @@ -66,6 +70,7 @@ public class CommonCodeService { /** * 공통코드 순서 변경 + * * @param req id, order 정보를 가진 List */ @Transactional @@ -75,6 +80,7 @@ public class CommonCodeService { /** * 코드기반 조회 + * * @param code 코드 * @return 코드로 조회한 공통코드 정보 */ diff --git a/src/main/java/com/kamco/cd/kamcoback/common/utils/interfaces/JsonFormatDttm.java b/src/main/java/com/kamco/cd/kamcoback/common/utils/interfaces/JsonFormatDttm.java index 44341876..61459803 100644 --- a/src/main/java/com/kamco/cd/kamcoback/common/utils/interfaces/JsonFormatDttm.java +++ b/src/main/java/com/kamco/cd/kamcoback/common/utils/interfaces/JsonFormatDttm.java @@ -4,15 +4,12 @@ import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; import com.fasterxml.jackson.annotation.JsonFormat; import java.lang.annotation.*; -@Target({ ElementType.FIELD, ElementType.METHOD }) +@Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @JacksonAnnotationsInside @JsonFormat( - shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd'T'HH:mm:ssXXX", - timezone = "Asia/Seoul" -) -public @interface JsonFormatDttm { - -} + shape = JsonFormat.Shape.STRING, + pattern = "yyyy-MM-dd'T'HH:mm:ssXXX", + timezone = "Asia/Seoul") +public @interface JsonFormatDttm {} diff --git a/src/main/java/com/kamco/cd/kamcoback/config/GlobalExceptionHandler.java b/src/main/java/com/kamco/cd/kamcoback/config/GlobalExceptionHandler.java index b3809687..995f6561 100644 --- a/src/main/java/com/kamco/cd/kamcoback/config/GlobalExceptionHandler.java +++ b/src/main/java/com/kamco/cd/kamcoback/config/GlobalExceptionHandler.java @@ -8,6 +8,12 @@ import com.kamco.cd.kamcoback.postgres.entity.ErrorLogEntity; import com.kamco.cd.kamcoback.postgres.repository.log.ErrorLogRepository; import jakarta.persistence.EntityNotFoundException; import jakarta.servlet.http.HttpServletRequest; +import java.nio.file.AccessDeniedException; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.core.annotation.Order; import org.springframework.dao.DataIntegrityViolationException; @@ -19,13 +25,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.client.HttpServerErrorException; -import java.nio.file.AccessDeniedException; -import java.time.ZonedDateTime; -import java.util.Arrays; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.stream.Collectors; - @Slf4j @Order(value = 1) @RestControllerAdvice @@ -39,102 +38,192 @@ public class GlobalExceptionHandler { @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(EntityNotFoundException.class) - public ApiResponseDto handlerEntityNotFoundException(EntityNotFoundException e, HttpServletRequest request) { + public ApiResponseDto handlerEntityNotFoundException( + EntityNotFoundException e, HttpServletRequest request) { log.warn("[EntityNotFoundException] resource :{} ", e.getMessage()); String codeName = "NOT_FOUND"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.ERROR, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.ERROR, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(HttpMessageNotReadableException.class) - public ApiResponseDto handleUnreadable(HttpMessageNotReadableException e, HttpServletRequest request) { + public ApiResponseDto handleUnreadable( + HttpMessageNotReadableException e, HttpServletRequest request) { log.warn("[HttpMessageNotReadableException] resource :{} ", e.getMessage()); String codeName = "BAD_REQUEST"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.WARNING, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.WARNING, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(NoSuchElementException.class) - public ApiResponseDto handlerNoSuchElementException(NoSuchElementException e, HttpServletRequest request) { + public ApiResponseDto handlerNoSuchElementException( + NoSuchElementException e, HttpServletRequest request) { log.warn("[NoSuchElementException] resource :{} ", e.getMessage()); String codeName = "NOT_FOUND_DATA"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.WARNING, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.WARNING, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf("NOT_FOUND"), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf("NOT_FOUND"), + errorLog.getId()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(IllegalArgumentException.class) - public ApiResponseDto handlerIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) { + public ApiResponseDto handlerIllegalArgumentException( + IllegalArgumentException e, HttpServletRequest request) { log.warn("[handlerIllegalArgumentException] resource :{} ", e.getMessage()); String codeName = "BAD_REQUEST"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.WARNING, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.WARNING, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) @ExceptionHandler(DataIntegrityViolationException.class) - public ApiResponseDto handlerDataIntegrityViolationException(DataIntegrityViolationException e, HttpServletRequest request) { + public ApiResponseDto handlerDataIntegrityViolationException( + DataIntegrityViolationException e, HttpServletRequest request) { log.warn("[DataIntegrityViolationException] resource :{} ", e.getMessage()); String codeName = "DATA_INTEGRITY_ERROR"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.CRITICAL, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.CRITICAL, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf("UNPROCESSABLE_ENTITY"), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf("UNPROCESSABLE_ENTITY"), + errorLog.getId()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) - public ApiResponseDto handlerMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) { + public ApiResponseDto handlerMethodArgumentNotValidException( + MethodArgumentNotValidException e, HttpServletRequest request) { log.warn("[MethodArgumentNotValidException] resource :{} ", e.getMessage()); String codeName = "BAD_REQUEST"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.WARNING, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.WARNING, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(AccessDeniedException.class) - public ApiResponseDto handlerAccessDeniedException(AccessDeniedException e, HttpServletRequest request) { + public ApiResponseDto handlerAccessDeniedException( + AccessDeniedException e, HttpServletRequest request) { log.warn("[AccessDeniedException] resource :{} ", e.getMessage()); String codeName = "UNAUTHORIZED"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.ERROR, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.ERROR, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.BAD_GATEWAY) @ExceptionHandler(HttpServerErrorException.BadGateway.class) - public ApiResponseDto handlerHttpServerErrorException(HttpServerErrorException e, HttpServletRequest request) { + public ApiResponseDto handlerHttpServerErrorException( + HttpServerErrorException e, HttpServletRequest request) { log.warn("[HttpServerErrorException] resource :{} ", e.getMessage()); String codeName = "BAD_GATEWAY"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.CRITICAL, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.CRITICAL, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(RuntimeException.class) - public ApiResponseDto handlerRuntimeException(RuntimeException e, HttpServletRequest request) { + public ApiResponseDto handlerRuntimeException( + RuntimeException e, HttpServletRequest request) { log.warn("[RuntimeException] resource :{} ", e.getMessage()); String codeName = "INTERNAL_SERVER_ERROR"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.CRITICAL, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.CRITICAL, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @@ -143,14 +232,24 @@ public class GlobalExceptionHandler { log.warn("[Exception] resource :{} ", e.getMessage()); String codeName = "INTERNAL_SERVER_ERROR"; - ErrorLogEntity errorLog = saveErrerLogData(request, ApiResponseCode.getCode(codeName), - HttpStatus.valueOf(codeName), ErrorLogDto.LogErrorLevel.CRITICAL, e.getStackTrace()); + ErrorLogEntity errorLog = + saveErrerLogData( + request, + ApiResponseCode.getCode(codeName), + HttpStatus.valueOf(codeName), + ErrorLogDto.LogErrorLevel.CRITICAL, + e.getStackTrace()); - return ApiResponseDto.createException(ApiResponseCode.getCode(codeName), ApiResponseCode.getMessage(codeName), HttpStatus.valueOf(codeName), errorLog.getId()); + return ApiResponseDto.createException( + ApiResponseCode.getCode(codeName), + ApiResponseCode.getMessage(codeName), + HttpStatus.valueOf(codeName), + errorLog.getId()); } /** * 에러 로그 테이블 저장 로직 + * * @param request : request * @param errorCode : 정의된 enum errorCode * @param httpStatus : HttpStatus 값 @@ -158,19 +257,32 @@ public class GlobalExceptionHandler { * @param stackTrace : 에러 내용 * @return : insert하고 결과로 받은 Entity */ - private ErrorLogEntity saveErrerLogData(HttpServletRequest request, ApiResponseCode errorCode, - HttpStatus httpStatus, ErrorLogDto.LogErrorLevel logErrorLevel, StackTraceElement[] stackTrace) { - //TODO : 로그인 개발되면 이것도 연결해야 함 + private ErrorLogEntity saveErrerLogData( + HttpServletRequest request, + ApiResponseCode errorCode, + HttpStatus httpStatus, + ErrorLogDto.LogErrorLevel logErrorLevel, + StackTraceElement[] stackTrace) { + // TODO : 로그인 개발되면 이것도 연결해야 함 Long userid = Long.valueOf(Optional.ofNullable(ApiLogFunction.getUserId(request)).orElse("1")); - //TODO : stackTrace limit 10줄? 확인 필요 - String stackTraceStr = Arrays.stream(stackTrace) - .limit(10) - .map(StackTraceElement::toString) - .collect(Collectors.joining("\n")); + // TODO : stackTrace limit 10줄? 확인 필요 + String stackTraceStr = + Arrays.stream(stackTrace) + .limit(10) + .map(StackTraceElement::toString) + .collect(Collectors.joining("\n")); - ErrorLogEntity errorLogEntity = new ErrorLogEntity(request.getRequestURI(), ApiLogFunction.getEventType(request), logErrorLevel, - String.valueOf(httpStatus.value()), errorCode.getText(), stackTraceStr, userid, ZonedDateTime.now()); + ErrorLogEntity errorLogEntity = + new ErrorLogEntity( + request.getRequestURI(), + ApiLogFunction.getEventType(request), + logErrorLevel, + String.valueOf(httpStatus.value()), + errorCode.getText(), + stackTraceStr, + userid, + ZonedDateTime.now()); return errorLogRepository.save(errorLogEntity); } diff --git a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFilter.java b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFilter.java index f678cfb4..944dc43f 100644 --- a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFilter.java +++ b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFilter.java @@ -4,22 +4,21 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.ContentCachingResponseWrapper; -import java.io.IOException; - @Component public class ApiLogFilter extends OncePerRequestFilter { @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - ContentCachingRequestWrapper wrappedRequest = - new ContentCachingRequestWrapper(request); + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request); - ContentCachingResponseWrapper wrappedResponse = - new ContentCachingResponseWrapper(response); + ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response); filterChain.doFilter(wrappedRequest, wrappedResponse); diff --git a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFunction.java b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFunction.java index 4e9581e2..2c4e8cba 100644 --- a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFunction.java +++ b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiLogFunction.java @@ -3,11 +3,10 @@ package com.kamco.cd.kamcoback.config.api; import com.kamco.cd.kamcoback.log.dto.EventStatus; import com.kamco.cd.kamcoback.log.dto.EventType; import jakarta.servlet.http.HttpServletRequest; -import org.springframework.web.util.ContentCachingRequestWrapper; - import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.stream.Collectors; +import org.springframework.web.util.ContentCachingRequestWrapper; public class ApiLogFunction { // 클라이언트 IP 추출 @@ -26,7 +25,7 @@ public class ApiLogFunction { } } String ip = request.getRemoteAddr(); - if ("0:0:0:0:0:0:0:1".equals(ip)) { //local 일 때 + if ("0:0:0:0:0:0:0:1".equals(ip)) { // local 일 때 ip = "127.0.0.1"; } return ip; @@ -45,9 +44,9 @@ public class ApiLogFunction { String method = request.getMethod().toUpperCase(); String uri = request.getRequestURI().toLowerCase(); - //URL 기반 DOWNLOAD/PRINT 분류 - if(uri.contains("/download") || uri.contains("/export")) return EventType.DOWNLOAD; - if(uri.contains("/print")) return EventType.PRINT; + // URL 기반 DOWNLOAD/PRINT 분류 + if (uri.contains("/download") || uri.contains("/export")) return EventType.DOWNLOAD; + if (uri.contains("/print")) return EventType.PRINT; // 일반 CRUD return switch (method) { @@ -59,23 +58,25 @@ public class ApiLogFunction { }; } - public static String getRequestBody(HttpServletRequest servletRequest, ContentCachingRequestWrapper contentWrapper) { + public static String getRequestBody( + HttpServletRequest servletRequest, ContentCachingRequestWrapper contentWrapper) { StringBuilder resultBody = new StringBuilder(); // GET, form-urlencoded POST 파라미터 Map paramMap = servletRequest.getParameterMap(); - String queryParams = paramMap.entrySet().stream() - .map(e -> e.getKey() + "=" + String.join(",", e.getValue())) - .collect(Collectors.joining("&")); + String queryParams = + paramMap.entrySet().stream() + .map(e -> e.getKey() + "=" + String.join(",", e.getValue())) + .collect(Collectors.joining("&")); resultBody.append(queryParams.isEmpty() ? "" : queryParams); // JSON Body if ("POST".equalsIgnoreCase(servletRequest.getMethod()) - && servletRequest.getContentType() != null - && servletRequest.getContentType().contains("application/json")) { + && servletRequest.getContentType() != null + && servletRequest.getContentType().contains("application/json")) { try { - //json인 경우는 Wrapper를 통해 가져오기 + // json인 경우는 Wrapper를 통해 가져오기 resultBody.append(getBodyData(contentWrapper)); } catch (Exception e) { @@ -85,8 +86,8 @@ public class ApiLogFunction { // Multipart form-data if ("POST".equalsIgnoreCase(servletRequest.getMethod()) - && servletRequest.getContentType() != null - && servletRequest.getContentType().startsWith("multipart/form-data")) { + && servletRequest.getContentType() != null + && servletRequest.getContentType().startsWith("multipart/form-data")) { resultBody.append("multipart/form-data request"); } @@ -104,8 +105,8 @@ public class ApiLogFunction { } } - //ApiResponse 의 Status가 2xx 범위이면 SUCCESS, 아니면 FAILED - public static EventStatus isSuccessFail(ApiResponseDto apiResponse){ + // ApiResponse 의 Status가 2xx 범위이면 SUCCESS, 아니면 FAILED + public static EventStatus isSuccessFail(ApiResponseDto apiResponse) { return apiResponse.getHttpStatus().is2xxSuccessful() ? EventStatus.SUCCESS : EventStatus.FAILED; } } diff --git a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseAdvice.java b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseAdvice.java index 3cc2fdef..61fd661e 100644 --- a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseAdvice.java +++ b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseAdvice.java @@ -3,6 +3,7 @@ package com.kamco.cd.kamcoback.config.api; import com.kamco.cd.kamcoback.postgres.entity.AuditLogEntity; import com.kamco.cd.kamcoback.postgres.repository.log.AuditLogRepository; import jakarta.servlet.http.HttpServletRequest; +import java.util.Optional; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; @@ -13,8 +14,6 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import org.springframework.web.util.ContentCachingRequestWrapper; -import java.util.Optional; - /** * ApiResponseDto의 내장된 HTTP 상태 코드를 실제 HTTP 응답에 적용하는 Advice * @@ -53,16 +52,23 @@ public class ApiResponseAdvice implements ResponseBodyAdvice { response.setStatusCode(apiResponse.getHttpStatus()); String ip = ApiLogFunction.getClientIp(servletRequest); - //TODO : userid 가 계정명인지, uid 인지 확인 후 로직 수정 필요함 - Long userid = Long.valueOf(Optional.ofNullable(ApiLogFunction.getUserId(servletRequest)).orElse("1")); + // TODO : userid 가 계정명인지, uid 인지 확인 후 로직 수정 필요함 + Long userid = + Long.valueOf(Optional.ofNullable(ApiLogFunction.getUserId(servletRequest)).orElse("1")); - //TODO: menuUid 를 동적으로 가져오게끔 해야함 - AuditLogEntity log = new AuditLogEntity(userid, ApiLogFunction.getEventType(servletRequest), - ApiLogFunction.isSuccessFail(apiResponse), "MU_01_01", ip, servletRequest.getRequestURI(), ApiLogFunction.getRequestBody(servletRequest, contentWrapper), - apiResponse.getErrorLogUid() - ); + // TODO: menuUid 를 동적으로 가져오게끔 해야함 + AuditLogEntity log = + new AuditLogEntity( + userid, + ApiLogFunction.getEventType(servletRequest), + ApiLogFunction.isSuccessFail(apiResponse), + "MU_01_01", + ip, + servletRequest.getRequestURI(), + ApiLogFunction.getRequestBody(servletRequest, contentWrapper), + apiResponse.getErrorLogUid()); - //tb_audit_log 테이블 저장 + // tb_audit_log 테이블 저장 auditLogRepository.save(log); } diff --git a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseDto.java b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseDto.java index 287b9114..a8ca69cd 100644 --- a/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseDto.java +++ b/src/main/java/com/kamco/cd/kamcoback/config/api/ApiResponseDto.java @@ -40,11 +40,14 @@ public class ApiResponseDto { public ApiResponseDto(ApiResponseCode code, String message) { this.error = new Error(code.getId(), message); } + public ApiResponseDto(ApiResponseCode code, String message, HttpStatus httpStatus) { this.error = new Error(code.getId(), message); this.httpStatus = httpStatus; } - public ApiResponseDto(ApiResponseCode code, String message, HttpStatus httpStatus, Long errorLogUid) { + + public ApiResponseDto( + ApiResponseCode code, String message, HttpStatus httpStatus, Long errorLogUid) { this.error = new Error(code.getId(), message); this.httpStatus = httpStatus; this.errorLogUid = errorLogUid; @@ -75,10 +78,14 @@ public class ApiResponseDto { public static ApiResponseDto createException(ApiResponseCode code, String message) { return new ApiResponseDto<>(code, message); } - public static ApiResponseDto createException(ApiResponseCode code, String message, HttpStatus httpStatus) { + + public static ApiResponseDto createException( + ApiResponseCode code, String message, HttpStatus httpStatus) { return new ApiResponseDto<>(code, message, httpStatus); } - public static ApiResponseDto createException(ApiResponseCode code, String message, HttpStatus httpStatus, Long errorLogUid) { + + public static ApiResponseDto createException( + ApiResponseCode code, String message, HttpStatus httpStatus, Long errorLogUid) { return new ApiResponseDto<>(code, message, httpStatus, errorLogUid); } diff --git a/src/main/java/com/kamco/cd/kamcoback/log/AuditLogApiController.java b/src/main/java/com/kamco/cd/kamcoback/log/AuditLogApiController.java index cbf8c3fe..3577e8eb 100644 --- a/src/main/java/com/kamco/cd/kamcoback/log/AuditLogApiController.java +++ b/src/main/java/com/kamco/cd/kamcoback/log/AuditLogApiController.java @@ -4,8 +4,8 @@ import com.kamco.cd.kamcoback.config.api.ApiResponseDto; import com.kamco.cd.kamcoback.log.dto.AuditLogDto; import com.kamco.cd.kamcoback.postgres.core.AuditLogCoreService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; +import java.time.LocalDate; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; @@ -13,8 +13,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.time.LocalDate; - @Tag(name = "감사 로그", description = "감사 로그 관리 API") @RequiredArgsConstructor @RestController @@ -26,18 +24,15 @@ public class AuditLogApiController { @Operation(summary = "일자별 로그 조회") @GetMapping("/daily") public ApiResponseDto> getDailyLogs( - @RequestParam(required = false) LocalDate startDate, - @RequestParam(required = false) LocalDate endDate, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - AuditLogDto.DailySearchReq searchReq = new AuditLogDto.DailySearchReq(startDate, endDate, null, page, size, "created_dttm,desc"); + @RequestParam(required = false) LocalDate startDate, + @RequestParam(required = false) LocalDate endDate, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + AuditLogDto.DailySearchReq searchReq = + new AuditLogDto.DailySearchReq(startDate, endDate, null, page, size, "created_dttm,desc"); - Page result = auditLogCoreService.getLogByDaily( - searchReq, - startDate, - endDate - ); + Page result = + auditLogCoreService.getLogByDaily(searchReq, startDate, endDate); return ApiResponseDto.ok(result); } @@ -45,83 +40,69 @@ public class AuditLogApiController { @Operation(summary = "일자별 로그 상세") @GetMapping("/daily/result") public ApiResponseDto> getDailyResultLogs( - @RequestParam LocalDate logDate, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - AuditLogDto.DailySearchReq searchReq = new AuditLogDto.DailySearchReq(null, null, logDate, page, size, "created_dttm,desc"); - Page result = auditLogCoreService.getLogByDailyResult( - searchReq, - logDate - ); + @RequestParam LocalDate logDate, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + AuditLogDto.DailySearchReq searchReq = + new AuditLogDto.DailySearchReq(null, null, logDate, page, size, "created_dttm,desc"); + Page result = + auditLogCoreService.getLogByDailyResult(searchReq, logDate); return ApiResponseDto.ok(result); } @Operation(summary = "메뉴별 로그 조회") - @GetMapping("/menu") public ApiResponseDto> getMenuLogs( - @RequestParam(required = false) String searchValue, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - AuditLogDto.MenuUserSearchReq searchReq = new AuditLogDto.MenuUserSearchReq(searchValue, null, null, page, size, "created_dttm,desc"); - Page result = auditLogCoreService.getLogByMenu( - searchReq, searchValue - ); + @RequestParam(required = false) String searchValue, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + AuditLogDto.MenuUserSearchReq searchReq = + new AuditLogDto.MenuUserSearchReq(searchValue, null, null, page, size, "created_dttm,desc"); + Page result = auditLogCoreService.getLogByMenu(searchReq, searchValue); return ApiResponseDto.ok(result); } @Operation(summary = "메뉴별 로그 상세") - @GetMapping("/menu/result") public ApiResponseDto> getMenuResultLogs( - @RequestParam String menuId, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - AuditLogDto.MenuUserSearchReq searchReq = new AuditLogDto.MenuUserSearchReq(null, menuId, null, page, size, "created_dttm,desc"); - Page result = auditLogCoreService.getLogByMenuResult( - searchReq, - menuId - ); + @RequestParam String menuId, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + AuditLogDto.MenuUserSearchReq searchReq = + new AuditLogDto.MenuUserSearchReq(null, menuId, null, page, size, "created_dttm,desc"); + Page result = + auditLogCoreService.getLogByMenuResult(searchReq, menuId); return ApiResponseDto.ok(result); } @Operation(summary = "사용자별 로그 조회") - @GetMapping("/account") public ApiResponseDto> getAccountLogs( - @RequestParam(required = false) String searchValue, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - AuditLogDto.MenuUserSearchReq searchReq = new AuditLogDto.MenuUserSearchReq(searchValue, null, null, page, size, "created_dttm,desc"); - Page result = auditLogCoreService.getLogByAccount( - searchReq, searchValue - ); + @RequestParam(required = false) String searchValue, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + AuditLogDto.MenuUserSearchReq searchReq = + new AuditLogDto.MenuUserSearchReq(searchValue, null, null, page, size, "created_dttm,desc"); + Page result = + auditLogCoreService.getLogByAccount(searchReq, searchValue); return ApiResponseDto.ok(result); } @Operation(summary = "사용자별 로그 상세") - @GetMapping("/account/result") public ApiResponseDto> getAccountResultLogs( - @RequestParam Long userUid, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - AuditLogDto.MenuUserSearchReq searchReq = new AuditLogDto.MenuUserSearchReq(null, null, userUid, page, size, "created_dttm,desc"); - Page result = auditLogCoreService.getLogByAccountResult( - searchReq, - userUid - ); + @RequestParam Long userUid, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + AuditLogDto.MenuUserSearchReq searchReq = + new AuditLogDto.MenuUserSearchReq(null, null, userUid, page, size, "created_dttm,desc"); + Page result = + auditLogCoreService.getLogByAccountResult(searchReq, userUid); return ApiResponseDto.ok(result); } - } diff --git a/src/main/java/com/kamco/cd/kamcoback/log/ErrorLogApiController.java b/src/main/java/com/kamco/cd/kamcoback/log/ErrorLogApiController.java index 1a7d2973..4c84d0b0 100644 --- a/src/main/java/com/kamco/cd/kamcoback/log/ErrorLogApiController.java +++ b/src/main/java/com/kamco/cd/kamcoback/log/ErrorLogApiController.java @@ -1,25 +1,19 @@ package com.kamco.cd.kamcoback.log; import com.kamco.cd.kamcoback.config.api.ApiResponseDto; -import com.kamco.cd.kamcoback.log.dto.AuditLogDto; import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; import com.kamco.cd.kamcoback.log.dto.EventType; -import com.kamco.cd.kamcoback.postgres.core.AuditLogCoreService; import com.kamco.cd.kamcoback.postgres.core.ErrorLogCoreService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import java.time.LocalDate; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.time.LocalDate; -import java.util.List; - @Tag(name = "에러 로그", description = "에러 로그 관리 API") @RequiredArgsConstructor @RestController @@ -29,17 +23,17 @@ public class ErrorLogApiController { private final ErrorLogCoreService errorLogCoreService; @Operation(summary = "에러로그 조회") - @GetMapping("/error") public ApiResponseDto> getErrorLogs( - @RequestParam(required = false) ErrorLogDto.LogErrorLevel logErrorLevel, - @RequestParam(required = false) EventType eventType, - @RequestParam(required = false) LocalDate startDate, - @RequestParam(required = false) LocalDate endDate, - @RequestParam int page, - @RequestParam(defaultValue = "20") int size - ) { - ErrorLogDto.ErrorSearchReq searchReq = new ErrorLogDto.ErrorSearchReq(logErrorLevel, eventType, startDate, endDate, page, size, "created_dttm,desc"); + @RequestParam(required = false) ErrorLogDto.LogErrorLevel logErrorLevel, + @RequestParam(required = false) EventType eventType, + @RequestParam(required = false) LocalDate startDate, + @RequestParam(required = false) LocalDate endDate, + @RequestParam int page, + @RequestParam(defaultValue = "20") int size) { + ErrorLogDto.ErrorSearchReq searchReq = + new ErrorLogDto.ErrorSearchReq( + logErrorLevel, eventType, startDate, endDate, page, size, "created_dttm,desc"); Page result = errorLogCoreService.findLogByError(searchReq); return ApiResponseDto.ok(result); diff --git a/src/main/java/com/kamco/cd/kamcoback/log/dto/AuditLogDto.java b/src/main/java/com/kamco/cd/kamcoback/log/dto/AuditLogDto.java index d4dc30ac..c9b1da72 100644 --- a/src/main/java/com/kamco/cd/kamcoback/log/dto/AuditLogDto.java +++ b/src/main/java/com/kamco/cd/kamcoback/log/dto/AuditLogDto.java @@ -3,6 +3,9 @@ package com.kamco.cd.kamcoback.log.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.kamco.cd.kamcoback.common.utils.interfaces.JsonFormatDttm; import io.swagger.v3.oas.annotations.media.Schema; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -11,18 +14,13 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; - public class AuditLogDto { @Schema(name = "AuditLogBasic", description = "감사로그 기본 정보") @Getter public static class Basic { - @JsonIgnore - private final Long id; + @JsonIgnore private final Long id; private final Long userUid; private final EventType eventType; private final EventStatus eventStatus; @@ -32,30 +30,29 @@ public class AuditLogDto { private final String requestBody; private final Long errorLogUid; - @JsonFormatDttm - private final ZonedDateTime createdDttm; + @JsonFormatDttm private final ZonedDateTime createdDttm; public Basic( - Long id, - Long userUid, - EventType eventType, - EventStatus eventStatus, - String menuUid, - String ipAddress, - String requestUri, - String requestBody, - Long errorLogUid, - ZonedDateTime createdDttm) { - this.id = id; - this.userUid = userUid; - this.eventType = eventType; - this.eventStatus = eventStatus; - this.menuUid = menuUid; - this.ipAddress = ipAddress; - this.requestUri = requestUri; - this.requestBody = requestBody; - this.errorLogUid = errorLogUid; - this.createdDttm = createdDttm; + Long id, + Long userUid, + EventType eventType, + EventStatus eventStatus, + String menuUid, + String ipAddress, + String requestUri, + String requestBody, + Long errorLogUid, + ZonedDateTime createdDttm) { + this.id = id; + this.userUid = userUid; + this.eventType = eventType; + this.eventStatus = eventStatus; + this.menuUid = menuUid; + this.ipAddress = ipAddress; + this.requestUri = requestUri; + this.requestBody = requestBody; + this.errorLogUid = errorLogUid; + this.createdDttm = createdDttm; } } @@ -76,7 +73,13 @@ public class AuditLogDto { private Long menuId; private String menuName; - public AuditList(LocalDateTime baseDate, int readCount, int cudCount, int printCount, int downloadCount, Long totalCount){ + public AuditList( + LocalDateTime baseDate, + int readCount, + int cudCount, + int printCount, + int downloadCount, + Long totalCount) { this.baseDate = baseDate; this.readCount = readCount; this.cudCount = cudCount; @@ -103,7 +106,7 @@ public class AuditLogDto { @Getter @Setter @AllArgsConstructor - public static class LogDetail{ + public static class LogDetail { String serviceName; String parentMenuName; String menuName; @@ -152,14 +155,15 @@ public class AuditLogDto { // 메뉴별, 사용자별 로그 검색 조건 private String searchValue; private String menuUid; - private Long userUid; //menuId, userUid 조회 + private Long userUid; // menuId, userUid 조회 // 페이징 파라미터 private int page = 0; private int size = 20; private String sort; - public MenuUserSearchReq(String searchValue, String menuUid, Long userUid, int page, int size, String sort) { + public MenuUserSearchReq( + String searchValue, String menuUid, Long userUid, int page, int size, String sort) { this.searchValue = searchValue; this.menuUid = menuUid; this.page = page; diff --git a/src/main/java/com/kamco/cd/kamcoback/log/dto/ErrorLogDto.java b/src/main/java/com/kamco/cd/kamcoback/log/dto/ErrorLogDto.java index 8b50504e..f4e85c17 100644 --- a/src/main/java/com/kamco/cd/kamcoback/log/dto/ErrorLogDto.java +++ b/src/main/java/com/kamco/cd/kamcoback/log/dto/ErrorLogDto.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.kamco.cd.kamcoback.common.utils.interfaces.JsonFormatDttm; import com.kamco.cd.kamcoback.config.enums.EnumType; import io.swagger.v3.oas.annotations.media.Schema; +import java.time.LocalDate; +import java.time.ZonedDateTime; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -12,18 +14,13 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; - public class ErrorLogDto { @Schema(name = "ErrorLogBasic", description = "에러로그 기본 정보") @Getter public static class Basic { - @JsonIgnore - private final Long id; + @JsonIgnore private final Long id; private final String requestId; private final EventType errorType; private final LogErrorLevel errorLevel; @@ -32,23 +29,21 @@ public class ErrorLogDto { private final String stackTrace; private final Long handlerUid; - @JsonFormatDttm - private final ZonedDateTime handledDttm; + @JsonFormatDttm private final ZonedDateTime handledDttm; - @JsonFormatDttm - private final ZonedDateTime createdDttm; + @JsonFormatDttm private final ZonedDateTime createdDttm; public Basic( - Long id, - String requestId, - EventType errorType, - LogErrorLevel errorLevel, - String errorCode, - String errorMessage, - String stackTrace, - Long handlerUid, - ZonedDateTime handledDttm, - ZonedDateTime createdDttm) { + Long id, + String requestId, + EventType errorType, + LogErrorLevel errorLevel, + String errorCode, + String errorMessage, + String stackTrace, + Long handlerUid, + ZonedDateTime handledDttm, + ZonedDateTime createdDttm) { this.id = id; this.requestId = requestId; this.errorType = errorType; @@ -79,7 +74,13 @@ public class ErrorLogDto { private int size = 20; private String sort; - public ErrorSearchReq(LogErrorLevel errorLevel, EventType eventType, LocalDate startDate, LocalDate endDate, int page, int size) { + public ErrorSearchReq( + LogErrorLevel errorLevel, + EventType eventType, + LocalDate startDate, + LocalDate endDate, + int page, + int size) { this.errorLevel = errorLevel; this.eventType = eventType; this.startDate = startDate; @@ -93,7 +94,7 @@ public class ErrorLogDto { String[] sortParams = sort.split(","); String property = sortParams[0]; Sort.Direction direction = - sortParams.length > 1 ? Sort.Direction.fromString(sortParams[1]) : Sort.Direction.ASC; + sortParams.length > 1 ? Sort.Direction.fromString(sortParams[1]) : Sort.Direction.ASC; return PageRequest.of(page, size, Sort.by(direction, property)); } return PageRequest.of(page, size); @@ -112,10 +113,13 @@ public class ErrorLogDto { } @Override - public String getId() { return name(); } + public String getId() { + return name(); + } @Override - public String getText() { return desc; } + public String getText() { + return desc; + } } - } diff --git a/src/main/java/com/kamco/cd/kamcoback/log/dto/EventStatus.java b/src/main/java/com/kamco/cd/kamcoback/log/dto/EventStatus.java index ed50fd47..bef06921 100644 --- a/src/main/java/com/kamco/cd/kamcoback/log/dto/EventStatus.java +++ b/src/main/java/com/kamco/cd/kamcoback/log/dto/EventStatus.java @@ -13,8 +13,12 @@ public enum EventStatus implements EnumType { private final String desc; @Override - public String getId() { return name(); } + public String getId() { + return name(); + } @Override - public String getText() { return desc; } + public String getText() { + return desc; + } } diff --git a/src/main/java/com/kamco/cd/kamcoback/log/dto/EventType.java b/src/main/java/com/kamco/cd/kamcoback/log/dto/EventType.java index 414a3386..318b5f17 100644 --- a/src/main/java/com/kamco/cd/kamcoback/log/dto/EventType.java +++ b/src/main/java/com/kamco/cd/kamcoback/log/dto/EventType.java @@ -18,8 +18,12 @@ public enum EventType implements EnumType { private final String desc; @Override - public String getId() { return name(); } + public String getId() { + return name(); + } @Override - public String getText() { return desc; } + public String getText() { + return desc; + } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/CommonCreateEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/CommonCreateEntity.java index e0950848..701df391 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/CommonCreateEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/CommonCreateEntity.java @@ -3,11 +3,10 @@ package com.kamco.cd.kamcoback.postgres; import jakarta.persistence.Column; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.PrePersist; +import java.time.ZonedDateTime; import lombok.Getter; import org.springframework.data.annotation.CreatedDate; -import java.time.ZonedDateTime; - @Getter @MappedSuperclass public class CommonCreateEntity { diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/core/AuditLogCoreService.java b/src/main/java/com/kamco/cd/kamcoback/postgres/core/AuditLogCoreService.java index fdcc902f..13e25583 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/core/AuditLogCoreService.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/core/AuditLogCoreService.java @@ -3,24 +3,22 @@ package com.kamco.cd.kamcoback.postgres.core; import com.kamco.cd.kamcoback.common.service.BaseCoreService; import com.kamco.cd.kamcoback.log.dto.AuditLogDto; import com.kamco.cd.kamcoback.postgres.repository.log.AuditLogRepository; +import java.time.LocalDate; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.LocalDate; - @Service @RequiredArgsConstructor @Transactional(readOnly = true) -public class AuditLogCoreService implements BaseCoreService { +public class AuditLogCoreService + implements BaseCoreService { private final AuditLogRepository auditLogRepository; @Override - public void remove(Long aLong) { - - } + public void remove(Long aLong) {} @Override public AuditLogDto.AuditList getOneById(Long aLong) { @@ -32,27 +30,33 @@ public class AuditLogCoreService implements BaseCoreService getLogByDaily(AuditLogDto.DailySearchReq searchRange, LocalDate startDate, LocalDate endDate) { + public Page getLogByDaily( + AuditLogDto.DailySearchReq searchRange, LocalDate startDate, LocalDate endDate) { return auditLogRepository.findLogByDaily(searchRange, startDate, endDate); } - public Page getLogByMenu(AuditLogDto.MenuUserSearchReq searchRange, String searchValue) { + public Page getLogByMenu( + AuditLogDto.MenuUserSearchReq searchRange, String searchValue) { return auditLogRepository.findLogByMenu(searchRange, searchValue); } - public Page getLogByAccount(AuditLogDto.MenuUserSearchReq searchRange, String searchValue) { + public Page getLogByAccount( + AuditLogDto.MenuUserSearchReq searchRange, String searchValue) { return auditLogRepository.findLogByAccount(searchRange, searchValue); } - public Page getLogByDailyResult(AuditLogDto.DailySearchReq searchRange, LocalDate logDate) { + public Page getLogByDailyResult( + AuditLogDto.DailySearchReq searchRange, LocalDate logDate) { return auditLogRepository.findLogByDailyResult(searchRange, logDate); } - public Page getLogByMenuResult(AuditLogDto.MenuUserSearchReq searchRange, String menuId) { + public Page getLogByMenuResult( + AuditLogDto.MenuUserSearchReq searchRange, String menuId) { return auditLogRepository.findLogByMenuResult(searchRange, menuId); } - public Page getLogByAccountResult(AuditLogDto.MenuUserSearchReq searchRange, Long accountId) { + public Page getLogByAccountResult( + AuditLogDto.MenuUserSearchReq searchRange, Long accountId) { return auditLogRepository.findLogByAccountResult(searchRange, accountId); } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/core/CommonCodeCoreService.java b/src/main/java/com/kamco/cd/kamcoback/postgres/core/CommonCodeCoreService.java index 743ce101..4aac8774 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/core/CommonCodeCoreService.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/core/CommonCodeCoreService.java @@ -14,34 +14,52 @@ import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor -public class CommonCodeCoreService implements BaseCoreService { +public class CommonCodeCoreService + implements BaseCoreService { private final CommonCodeRepository commonCodeRepository; - public List findAll() { return commonCodeRepository.findByAll().stream().map(CommonCodeEntity::toDto).toList(); } public CommonCodeDto.Basic save(CommonCodeDto.AddReq req) { - if(req.getParentId() != null){ - CommonCodeEntity parentCommonCodeEntity = commonCodeRepository.findById(req.getParentId()) - .orElseThrow(() -> new EntityNotFoundException("parent id 를 찾을 수 없습니다. id : " + req.getParentId())); + if (req.getParentId() != null) { + CommonCodeEntity parentCommonCodeEntity = + commonCodeRepository + .findById(req.getParentId()) + .orElseThrow( + () -> + new EntityNotFoundException( + "parent id 를 찾을 수 없습니다. id : " + req.getParentId())); - CommonCodeEntity entity = new CommonCodeEntity(req.getCode(), req.getName(), req.getDescription(), req.getOrder(), req.isUsed()); + CommonCodeEntity entity = + new CommonCodeEntity( + req.getCode(), req.getName(), req.getDescription(), req.getOrder(), req.isUsed()); entity.addParent(parentCommonCodeEntity); return commonCodeRepository.save(entity).toDto(); } - CommonCodeEntity entity = new CommonCodeEntity(req.getCode(), req.getName(), req.getDescription(), req.getOrder(), req.isUsed()); + CommonCodeEntity entity = + new CommonCodeEntity( + req.getCode(), req.getName(), req.getDescription(), req.getOrder(), req.isUsed()); return commonCodeRepository.save(entity).toDto(); } public CommonCodeDto.Basic update(Long id, CommonCodeDto.ModifyReq req) { - CommonCodeEntity found = commonCodeRepository.findByCodeId(id) - .orElseThrow(()->new EntityNotFoundException("common code 를 찾을 수 없습니다. id : " + id)); + CommonCodeEntity found = + commonCodeRepository + .findByCodeId(id) + .orElseThrow(() -> new EntityNotFoundException("common code 를 찾을 수 없습니다. id : " + id)); - CommonCodeEntity entity = new CommonCodeEntity( id, req.getName(), req.getDescription(), req.getOrder(), req.isUsed(), found.getDeleted()); + CommonCodeEntity entity = + new CommonCodeEntity( + id, + req.getName(), + req.getDescription(), + req.getOrder(), + req.isUsed(), + found.getDeleted()); return commonCodeRepository.save(entity).toDto(); } @@ -56,8 +74,10 @@ public class CommonCodeCoreService implements BaseCoreServicenew EntityNotFoundException("code를 찾을 수 없습니다. id " + id)); + CommonCodeEntity entity = + commonCodeRepository + .findByCodeId(id) + .orElseThrow(() -> new EntityNotFoundException("code를 찾을 수 없습니다. id " + id)); // 하위 코드 deleted = false 업데이트 entity.getChildren().forEach(CommonCodeEntity::deleted); @@ -67,8 +87,10 @@ public class CommonCodeCoreService implements BaseCoreServicenew EntityNotFoundException("code를 찾을 수 없습니다. id " + id)); + CommonCodeEntity entity = + commonCodeRepository + .findByCodeId(id) + .orElseThrow(() -> new EntityNotFoundException("code를 찾을 수 없습니다. id " + id)); return entity.toDto(); } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/core/ErrorLogCoreService.java b/src/main/java/com/kamco/cd/kamcoback/postgres/core/ErrorLogCoreService.java index b833f3d0..853a3dd3 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/core/ErrorLogCoreService.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/core/ErrorLogCoreService.java @@ -1,21 +1,18 @@ package com.kamco.cd.kamcoback.postgres.core; import com.kamco.cd.kamcoback.common.service.BaseCoreService; -import com.kamco.cd.kamcoback.log.dto.AuditLogDto; import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; -import com.kamco.cd.kamcoback.postgres.repository.log.AuditLogRepository; import com.kamco.cd.kamcoback.postgres.repository.log.ErrorLogRepository; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.LocalDate; - @Service @RequiredArgsConstructor @Transactional(readOnly = true) -public class ErrorLogCoreService implements BaseCoreService { +public class ErrorLogCoreService + implements BaseCoreService { private final ErrorLogRepository errorLogRepository; diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/AuditLogEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/AuditLogEntity.java index 7570f66d..5ac909e5 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/AuditLogEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/AuditLogEntity.java @@ -43,7 +43,15 @@ public class AuditLogEntity extends CommonCreateEntity { @Column(name = "error_log_uid") private Long errorLogUid; - public AuditLogEntity(Long userUid, EventType eventType, EventStatus eventStatus, String menuUid, String ipAddress, String requestUri, String requestBody, Long errorLogUid) { + public AuditLogEntity( + Long userUid, + EventType eventType, + EventStatus eventStatus, + String menuUid, + String ipAddress, + String requestUri, + String requestBody, + Long errorLogUid) { this.userUid = userUid; this.eventType = eventType; this.eventStatus = eventStatus; @@ -56,29 +64,37 @@ public class AuditLogEntity extends CommonCreateEntity { public AuditLogDto.Basic toDto() { return new AuditLogDto.Basic( - this.id, - this.userUid, - this.eventType, - this.eventStatus, - this.menuUid, - this.ipAddress, - this.requestUri, - this.requestBody, - this.errorLogUid, - super.getCreatedDate()); + this.id, + this.userUid, + this.eventType, + this.eventStatus, + this.menuUid, + this.ipAddress, + this.requestUri, + this.requestBody, + this.errorLogUid, + super.getCreatedDate()); } @Override - public String toString(){ + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(this.id).append("\n") - .append(this.userUid).append("\n") - .append(this.eventType).append("\n") - .append(this.eventStatus).append("\n") - .append(this.menuUid).append("\n") - .append(this.ipAddress).append("\n") - .append(this.requestUri).append("\n") - .append(this.requestBody).append("\n") + sb.append(this.id) + .append("\n") + .append(this.userUid) + .append("\n") + .append(this.eventType) + .append("\n") + .append(this.eventStatus) + .append("\n") + .append(this.menuUid) + .append("\n") + .append(this.ipAddress) + .append("\n") + .append(this.requestUri) + .append("\n") + .append(this.requestBody) + .append("\n") .append(this.errorLogUid); return sb.toString(); } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/CommonCodeEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/CommonCodeEntity.java index 9ecbd892..1922ad64 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/CommonCodeEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/CommonCodeEntity.java @@ -61,7 +61,8 @@ public class CommonCodeEntity extends CommonDateEntity { @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List children = new ArrayList<>(); - public CommonCodeEntity(String code, String name, String description, Integer order, Boolean used) { + public CommonCodeEntity( + String code, String name, String description, Integer order, Boolean used) { this.code = code; this.name = name; this.description = description; @@ -69,7 +70,8 @@ public class CommonCodeEntity extends CommonDateEntity { this.used = used; } - public CommonCodeEntity(Long id, String name, String description, Integer order, Boolean used, Boolean deleted) { + public CommonCodeEntity( + Long id, String name, String description, Integer order, Boolean used, Boolean deleted) { this.id = id; this.name = name; this.description = description; @@ -80,19 +82,18 @@ public class CommonCodeEntity extends CommonDateEntity { public CommonCodeDto.Basic toDto() { return new CommonCodeDto.Basic( - this.id, - this.code, - this.description, - this.name, - this.order, - this.used, - this.deleted, - this.children.stream().map(CommonCodeEntity::toDto).toList(), - super.getCreatedDate(), - super.getModifiedDate()); + this.id, + this.code, + this.description, + this.name, + this.order, + this.used, + this.deleted, + this.children.stream().map(CommonCodeEntity::toDto).toList(), + super.getCreatedDate(), + super.getModifiedDate()); } - public void addParent(CommonCodeEntity parent) { this.parent = parent; } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/ErrorLogEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/ErrorLogEntity.java index 281b3d0c..604727a1 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/ErrorLogEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/ErrorLogEntity.java @@ -4,13 +4,11 @@ import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; import com.kamco.cd.kamcoback.log.dto.EventType; import com.kamco.cd.kamcoback.postgres.CommonCreateEntity; import jakarta.persistence.*; +import java.time.ZonedDateTime; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; - @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -30,14 +28,22 @@ public class ErrorLogEntity extends CommonCreateEntity { @Enumerated(EnumType.STRING) private ErrorLogDto.LogErrorLevel errorLevel; + private String errorCode; private String errorMessage; private String stackTrace; private Long handlerUid; private ZonedDateTime handledDttm; - public ErrorLogEntity(String requestId, EventType errorType, ErrorLogDto.LogErrorLevel errorLevel, String errorCode, String errorMessage, String stackTrace - , Long handlerUid, ZonedDateTime handledDttm) { + public ErrorLogEntity( + String requestId, + EventType errorType, + ErrorLogDto.LogErrorLevel errorLevel, + String errorCode, + String errorMessage, + String stackTrace, + Long handlerUid, + ZonedDateTime handledDttm) { this.requestId = requestId; this.errorType = errorType; this.errorLevel = errorLevel; diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/MenuEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/MenuEntity.java index bfb65394..be9e68c5 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/MenuEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/MenuEntity.java @@ -1,17 +1,14 @@ package com.kamco.cd.kamcoback.postgres.entity; -import com.kamco.cd.kamcoback.log.dto.EventStatus; -import com.kamco.cd.kamcoback.log.dto.EventType; import com.kamco.cd.kamcoback.postgres.CommonDateEntity; import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; +import java.util.ArrayList; +import java.util.List; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; -import java.util.ArrayList; -import java.util.List; - @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/UserEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/UserEntity.java index df7631b0..747f0d27 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/UserEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/UserEntity.java @@ -1,15 +1,12 @@ package com.kamco.cd.kamcoback.postgres.entity; -import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; -import com.kamco.cd.kamcoback.log.dto.EventType; import com.kamco.cd.kamcoback.postgres.CommonDateEntity; import jakarta.persistence.*; +import java.time.ZonedDateTime; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; -import java.time.ZonedDateTime; - @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @@ -27,15 +24,14 @@ public class UserEntity extends CommonDateEntity { private String userId; @Column(name = "pswd") - private String pswd; //TODO: 암호화 + private String pswd; // TODO: 암호화 - //@Enumerated(EnumType.STRING) - private String state; //TODO: 추후 enum -> ACTIVE : 정상, LOCKED : 잠김, EXPIRED : 만료, WITHDRAWAL : 탈퇴 + // @Enumerated(EnumType.STRING) + private String state; // TODO: 추후 enum -> ACTIVE : 정상, LOCKED : 잠김, EXPIRED : 만료, WITHDRAWAL : 탈퇴 private ZonedDateTime dateWithdrawal; private String userEmail; private Long createdUid; private Long updatedUid; - } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepository.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepository.java index 31894bbd..70921aa8 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepository.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepository.java @@ -3,6 +3,5 @@ package com.kamco.cd.kamcoback.postgres.repository; import com.kamco.cd.kamcoback.postgres.entity.CommonCodeEntity; import org.springframework.data.jpa.repository.JpaRepository; -public interface CommonCodeRepository extends JpaRepository, CommonCodeRepositoryCustom { - -} +public interface CommonCodeRepository + extends JpaRepository, CommonCodeRepositoryCustom {} diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryCustom.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryCustom.java index 2a635907..2d0bf7ba 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryCustom.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryCustom.java @@ -7,7 +7,10 @@ import java.util.Optional; public interface CommonCodeRepositoryCustom { Optional findByCodeId(Long id); + Optional findByCode(String code); + List findByAll(); + void updateOrder(CommonCodeDto.OrderReq req); } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryImpl.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryImpl.java index 98bc7720..2bacb370 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryImpl.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/CommonCodeRepositoryImpl.java @@ -6,10 +6,7 @@ import com.kamco.cd.kamcoback.code.dto.CommonCodeDto; import com.kamco.cd.kamcoback.code.dto.CommonCodeDto.OrderReqDetail; import com.kamco.cd.kamcoback.postgres.entity.CommonCodeEntity; import com.kamco.cd.kamcoback.postgres.entity.QCommonCodeEntity; -import com.querydsl.core.types.dsl.Expressions; import com.querydsl.jpa.impl.JPAQueryFactory; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -17,7 +14,8 @@ import java.util.Set; import java.util.stream.Collectors; import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; -public class CommonCodeRepositoryImpl extends QuerydslRepositorySupport implements CommonCodeRepositoryCustom { +public class CommonCodeRepositoryImpl extends QuerydslRepositorySupport + implements CommonCodeRepositoryCustom { private final JPAQueryFactory queryFactory; @@ -30,75 +28,65 @@ public class CommonCodeRepositoryImpl extends QuerydslRepositorySupport implemen public Optional findByCodeId(Long id) { QCommonCodeEntity child = new QCommonCodeEntity("child"); return Optional.ofNullable( - queryFactory - .selectFrom(commonCodeEntity) - .leftJoin(commonCodeEntity.children, child) - .fetchJoin() - .where( - commonCodeEntity.id.eq(id), - commonCodeEntity.deleted.isFalse() - ) - .orderBy(commonCodeEntity.order.asc(), child.order.asc()) - .fetchOne() - ); + queryFactory + .selectFrom(commonCodeEntity) + .leftJoin(commonCodeEntity.children, child) + .fetchJoin() + .where(commonCodeEntity.id.eq(id), commonCodeEntity.deleted.isFalse()) + .orderBy(commonCodeEntity.order.asc(), child.order.asc()) + .fetchOne()); } @Override public Optional findByCode(String code) { QCommonCodeEntity child = new QCommonCodeEntity("child"); return Optional.ofNullable( - queryFactory - .selectFrom(commonCodeEntity) - .leftJoin(commonCodeEntity.children, child) - .fetchJoin() - .where( - commonCodeEntity.parent.isNull(), - commonCodeEntity.code.eq(code), - commonCodeEntity.used.isTrue(), - commonCodeEntity.deleted.isFalse() - ) - .orderBy(child.order.asc()) - .fetchOne() - ); + queryFactory + .selectFrom(commonCodeEntity) + .leftJoin(commonCodeEntity.children, child) + .fetchJoin() + .where( + commonCodeEntity.parent.isNull(), + commonCodeEntity.code.eq(code), + commonCodeEntity.used.isTrue(), + commonCodeEntity.deleted.isFalse()) + .orderBy(child.order.asc()) + .fetchOne()); } @Override public List findByAll() { QCommonCodeEntity child = new QCommonCodeEntity("child"); return queryFactory - .selectFrom(commonCodeEntity) - .leftJoin(commonCodeEntity.children, child) - .fetchJoin() - .where( - commonCodeEntity.parent.isNull(), - commonCodeEntity.deleted.isFalse() - ) - .orderBy(commonCodeEntity.order.asc(), child.order.asc()) - .fetch(); + .selectFrom(commonCodeEntity) + .leftJoin(commonCodeEntity.children, child) + .fetchJoin() + .where(commonCodeEntity.parent.isNull(), commonCodeEntity.deleted.isFalse()) + .orderBy(commonCodeEntity.order.asc(), child.order.asc()) + .fetch(); } @Override public void updateOrder(CommonCodeDto.OrderReq req) { - Map orderMap = req.getOrders().stream(). - collect(Collectors.toMap(OrderReqDetail::getId, OrderReqDetail::getOrder)); + Map orderMap = + req.getOrders().stream() + .collect(Collectors.toMap(OrderReqDetail::getId, OrderReqDetail::getOrder)); List entity = findAllByIds(orderMap.keySet()); - entity.forEach(commonCodeEntity -> { - Integer order = orderMap.get(commonCodeEntity.getId()); - if(order != null) { - commonCodeEntity.updateOrder(order); - } - }); + entity.forEach( + commonCodeEntity -> { + Integer order = orderMap.get(commonCodeEntity.getId()); + if (order != null) { + commonCodeEntity.updateOrder(order); + } + }); } private List findAllByIds(Set ids) { return queryFactory - .selectFrom(commonCodeEntity) - .where( - commonCodeEntity.id.in(ids), - commonCodeEntity.deleted.isFalse() - ) - .fetch(); + .selectFrom(commonCodeEntity) + .where(commonCodeEntity.id.in(ids), commonCodeEntity.deleted.isFalse()) + .fetch(); } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepository.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepository.java index 1bffa354..803c0e25 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepository.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepository.java @@ -3,4 +3,5 @@ package com.kamco.cd.kamcoback.postgres.repository.log; import com.kamco.cd.kamcoback.postgres.entity.AuditLogEntity; import org.springframework.data.jpa.repository.JpaRepository; -public interface AuditLogRepository extends JpaRepository, AuditLogRepositoryCustom {} +public interface AuditLogRepository + extends JpaRepository, AuditLogRepositoryCustom {} diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryCustom.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryCustom.java index b979ff97..70d4038c 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryCustom.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryCustom.java @@ -1,21 +1,26 @@ package com.kamco.cd.kamcoback.postgres.repository.log; import com.kamco.cd.kamcoback.log.dto.AuditLogDto; -import org.springframework.data.domain.Page; - import java.time.LocalDate; +import org.springframework.data.domain.Page; public interface AuditLogRepositoryCustom { - Page findLogByDaily(AuditLogDto.DailySearchReq searchReq, LocalDate startDate, LocalDate endDate); + Page findLogByDaily( + AuditLogDto.DailySearchReq searchReq, LocalDate startDate, LocalDate endDate); - Page findLogByMenu(AuditLogDto.MenuUserSearchReq searchReq, String searchValue); + Page findLogByMenu( + AuditLogDto.MenuUserSearchReq searchReq, String searchValue); - Page findLogByAccount(AuditLogDto.MenuUserSearchReq searchReq, String searchValue); + Page findLogByAccount( + AuditLogDto.MenuUserSearchReq searchReq, String searchValue); - Page findLogByDailyResult(AuditLogDto.DailySearchReq searchReq, LocalDate logDate); + Page findLogByDailyResult( + AuditLogDto.DailySearchReq searchReq, LocalDate logDate); - Page findLogByMenuResult(AuditLogDto.MenuUserSearchReq searchReq, String menuId); + Page findLogByMenuResult( + AuditLogDto.MenuUserSearchReq searchReq, String menuId); - Page findLogByAccountResult(AuditLogDto.MenuUserSearchReq searchReq, Long accountId); + Page findLogByAccountResult( + AuditLogDto.MenuUserSearchReq searchReq, Long accountId); } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryImpl.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryImpl.java index 06f4aa43..ac35466b 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryImpl.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/AuditLogRepositoryImpl.java @@ -1,33 +1,32 @@ package com.kamco.cd.kamcoback.postgres.repository.log; +import static com.kamco.cd.kamcoback.postgres.entity.QAuditLogEntity.auditLogEntity; +import static com.kamco.cd.kamcoback.postgres.entity.QErrorLogEntity.errorLogEntity; +import static com.kamco.cd.kamcoback.postgres.entity.QMenuEntity.menuEntity; +import static com.kamco.cd.kamcoback.postgres.entity.QUserEntity.userEntity; + import com.kamco.cd.kamcoback.log.dto.AuditLogDto; import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; import com.kamco.cd.kamcoback.log.dto.EventStatus; import com.kamco.cd.kamcoback.log.dto.EventType; import com.kamco.cd.kamcoback.postgres.entity.AuditLogEntity; +import com.kamco.cd.kamcoback.postgres.entity.QMenuEntity; import com.querydsl.core.types.Projections; import com.querydsl.core.types.dsl.*; -import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import io.micrometer.common.util.StringUtils; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; -import static com.kamco.cd.kamcoback.postgres.entity.QUserEntity.userEntity; -import static com.kamco.cd.kamcoback.postgres.entity.QAuditLogEntity.auditLogEntity; -import static com.kamco.cd.kamcoback.postgres.entity.QErrorLogEntity.errorLogEntity; -import static com.kamco.cd.kamcoback.postgres.entity.QMenuEntity.menuEntity; -import com.kamco.cd.kamcoback.postgres.entity.QMenuEntity; - -public class AuditLogRepositoryImpl extends QuerydslRepositorySupport implements AuditLogRepositoryCustom { +public class AuditLogRepositoryImpl extends QuerydslRepositorySupport + implements AuditLogRepositoryCustom { private final JPAQueryFactory queryFactory; private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)"); @@ -37,304 +36,311 @@ public class AuditLogRepositoryImpl extends QuerydslRepositorySupport implements } @Override - public Page findLogByDaily(AuditLogDto.DailySearchReq searchReq, LocalDate startDate, LocalDate endDate) { + public Page findLogByDaily( + AuditLogDto.DailySearchReq searchReq, LocalDate startDate, LocalDate endDate) { DateTimeExpression groupDateTime = - Expressions.dateTimeTemplate(LocalDateTime.class, "date_trunc('day', {0})", auditLogEntity.createdDate); + Expressions.dateTimeTemplate( + LocalDateTime.class, "date_trunc('day', {0})", auditLogEntity.createdDate); Pageable pageable = searchReq.toPageable(); - List foundContent = queryFactory - .select( - Projections.constructor( - AuditLogDto.AuditList.class, - groupDateTime.as("baseDate"), - readCount().as("readCount"), - cudCount().as("cudCount"), - printCount().as("printCount"), - downloadCount().as("downloadCount"), - auditLogEntity.count().as("totalCount") - ) - ) - .from(auditLogEntity) - .where( - eventEndedAtBetween(startDate, endDate) - ) - .groupBy(groupDateTime) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) - .orderBy(groupDateTime.desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + AuditLogDto.AuditList.class, + groupDateTime.as("baseDate"), + readCount().as("readCount"), + cudCount().as("cudCount"), + printCount().as("printCount"), + downloadCount().as("downloadCount"), + auditLogEntity.count().as("totalCount"))) + .from(auditLogEntity) + .where(eventEndedAtBetween(startDate, endDate)) + .groupBy(groupDateTime) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .orderBy(groupDateTime.desc()) + .fetch(); - Long countQuery = queryFactory - .select(groupDateTime.countDistinct()) - .from(auditLogEntity) - .where( - eventEndedAtBetween(startDate, endDate) - ) - .fetchOne(); + Long countQuery = + queryFactory + .select(groupDateTime.countDistinct()) + .from(auditLogEntity) + .where(eventEndedAtBetween(startDate, endDate)) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @Override - public Page findLogByMenu(AuditLogDto.MenuUserSearchReq searchReq, String searchValue) { + public Page findLogByMenu( + AuditLogDto.MenuUserSearchReq searchReq, String searchValue) { Pageable pageable = searchReq.toPageable(); - List foundContent = queryFactory - .select( - Projections.constructor( - AuditLogDto.AuditList.class, - auditLogEntity.menuUid.as("menuId"), - menuEntity.menuNm.max().as("menuName"), - readCount().as("readCount"), - cudCount().as("cudCount"), - printCount().as("printCount"), - downloadCount().as("downloadCount"), - auditLogEntity.count().as("totalCount") - ) - ) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .where( - menuNameEquals(searchValue) - ) - .groupBy(auditLogEntity.menuUid) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) - .orderBy(auditLogEntity.createdDate.max().desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + AuditLogDto.AuditList.class, + auditLogEntity.menuUid.as("menuId"), + menuEntity.menuNm.max().as("menuName"), + readCount().as("readCount"), + cudCount().as("cudCount"), + printCount().as("printCount"), + downloadCount().as("downloadCount"), + auditLogEntity.count().as("totalCount"))) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .where(menuNameEquals(searchValue)) + .groupBy(auditLogEntity.menuUid) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .orderBy(auditLogEntity.createdDate.max().desc()) + .fetch(); // count query group by 를 지정하면 하나의 row 가 아니라 그룹핑된 여러 row 가 나올 수 있다. // select query 의 group by 대상의 컬럼을 count query 에선 select distinct 로 처리 한다. - Long countQuery = queryFactory - .select(auditLogEntity.menuUid.countDistinct()) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .where(menuNameEquals(searchValue)) - .fetchOne(); + Long countQuery = + queryFactory + .select(auditLogEntity.menuUid.countDistinct()) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .where(menuNameEquals(searchValue)) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @Override - public Page findLogByAccount(AuditLogDto.MenuUserSearchReq searchReq, String searchValue) { + public Page findLogByAccount( + AuditLogDto.MenuUserSearchReq searchReq, String searchValue) { Pageable pageable = searchReq.toPageable(); - List foundContent = queryFactory - .select( - Projections.constructor( - AuditLogDto.AuditList.class, - auditLogEntity.userUid.as("accountId"), - userEntity.userId.as("loginId"), - userEntity.userNm.as("username"), - readCount().as("readCount"), - cudCount().as("cudCount"), - printCount().as("printCount"), - downloadCount().as("downloadCount"), - auditLogEntity.count().as("totalCount") - ) - ) - .from(auditLogEntity) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - loginIdOrUsernameContains(searchValue) - ) - .groupBy(auditLogEntity.userUid, userEntity.userId, userEntity.userNm) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) -// .orderBy(auditLogEntity.eventEndedAt.max().desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + AuditLogDto.AuditList.class, + auditLogEntity.userUid.as("accountId"), + userEntity.userId.as("loginId"), + userEntity.userNm.as("username"), + readCount().as("readCount"), + cudCount().as("cudCount"), + printCount().as("printCount"), + downloadCount().as("downloadCount"), + auditLogEntity.count().as("totalCount"))) + .from(auditLogEntity) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(loginIdOrUsernameContains(searchValue)) + .groupBy(auditLogEntity.userUid, userEntity.userId, userEntity.userNm) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + // .orderBy(auditLogEntity.eventEndedAt.max().desc()) + .fetch(); - Long countQuery = queryFactory - .select(auditLogEntity.userUid.countDistinct()) - .from(auditLogEntity) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where(loginIdOrUsernameContains(searchValue)) - .fetchOne(); + Long countQuery = + queryFactory + .select(auditLogEntity.userUid.countDistinct()) + .from(auditLogEntity) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(loginIdOrUsernameContains(searchValue)) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @Override - public Page findLogByDailyResult(AuditLogDto.DailySearchReq searchReq, LocalDate logDate) { + public Page findLogByDailyResult( + AuditLogDto.DailySearchReq searchReq, LocalDate logDate) { Pageable pageable = searchReq.toPageable(); QMenuEntity parent = new QMenuEntity("parent"); // 1depth menu name StringExpression parentMenuName = - new CaseBuilder() - .when(parent.menuUid.isNull()).then(menuEntity.menuNm) - .otherwise(parent.menuNm); + new CaseBuilder() + .when(parent.menuUid.isNull()) + .then(menuEntity.menuNm) + .otherwise(parent.menuNm); // 2depth menu name StringExpression menuName = - new CaseBuilder() - .when(parent.menuUid.isNull()).then(NULL_STRING) - .otherwise(menuEntity.menuNm); + new CaseBuilder() + .when(parent.menuUid.isNull()) + .then(NULL_STRING) + .otherwise(menuEntity.menuNm); - List foundContent = queryFactory - .select( - Projections.constructor( - AuditLogDto.AuditDetail.class, - auditLogEntity.id.as("logId"), - userEntity.userNm.as("userName"), - userEntity.userId.as("loginId"), - menuEntity.menuNm.as("menuName"), - auditLogEntity.eventType.as("eventType"), - Projections.constructor( - AuditLogDto.LogDetail.class, - Expressions.constant("한국자산관리공사"), //serviceName - parentMenuName.as("parentMenuName"), - menuName, - menuEntity.menuUrl.as("menuUrl"), - menuEntity.description.as("menuDescription"), - menuEntity.menuOrder.as("sortOrder"), - menuEntity.isUse.as("used") - ) - ) - ) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(menuEntity.parent, parent) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - eventEndedAtEqDate(logDate) - ) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) - .orderBy(auditLogEntity.createdDate.desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + AuditLogDto.AuditDetail.class, + auditLogEntity.id.as("logId"), + userEntity.userNm.as("userName"), + userEntity.userId.as("loginId"), + menuEntity.menuNm.as("menuName"), + auditLogEntity.eventType.as("eventType"), + Projections.constructor( + AuditLogDto.LogDetail.class, + Expressions.constant("한국자산관리공사"), // serviceName + parentMenuName.as("parentMenuName"), + menuName, + menuEntity.menuUrl.as("menuUrl"), + menuEntity.description.as("menuDescription"), + menuEntity.menuOrder.as("sortOrder"), + menuEntity.isUse.as("used")))) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(menuEntity.parent, parent) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(eventEndedAtEqDate(logDate)) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .orderBy(auditLogEntity.createdDate.desc()) + .fetch(); - Long countQuery = queryFactory - .select(auditLogEntity.id.countDistinct()) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(menuEntity.parent, parent) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - eventEndedAtEqDate(logDate) - ) - .fetchOne(); + Long countQuery = + queryFactory + .select(auditLogEntity.id.countDistinct()) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(menuEntity.parent, parent) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(eventEndedAtEqDate(logDate)) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @Override - public Page findLogByMenuResult(AuditLogDto.MenuUserSearchReq searchReq, String menuUid) { + public Page findLogByMenuResult( + AuditLogDto.MenuUserSearchReq searchReq, String menuUid) { Pageable pageable = searchReq.toPageable(); QMenuEntity parent = new QMenuEntity("parent"); // 1depth menu name StringExpression parentMenuName = - new CaseBuilder() - .when(parent.menuUid.isNull()).then(menuEntity.menuNm) - .otherwise(parent.menuNm); + new CaseBuilder() + .when(parent.menuUid.isNull()) + .then(menuEntity.menuNm) + .otherwise(parent.menuNm); // 2depth menu name StringExpression menuName = - new CaseBuilder() - .when(parent.menuUid.isNull()).then(NULL_STRING) - .otherwise(menuEntity.menuNm); + new CaseBuilder() + .when(parent.menuUid.isNull()) + .then(NULL_STRING) + .otherwise(menuEntity.menuNm); - List foundContent = queryFactory - .select( - Projections.constructor( - AuditLogDto.AuditDetail.class, - auditLogEntity.id.as("logId"), - auditLogEntity.createdDate.as("logDateTime"), - userEntity.userNm.as("userName"), - userEntity.userId.as("loginId"), - auditLogEntity.eventType.as("eventType"), - Projections.constructor( - AuditLogDto.LogDetail.class, - Expressions.constant("한국자산관리공사"), //serviceName - parentMenuName.as("parentMenuName"), - menuName, - menuEntity.menuUrl.as("menuUrl"), - menuEntity.description.as("menuDescription"), - menuEntity.menuOrder.as("sortOrder"), - menuEntity.isUse.as("used") - ) - ) - ) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(menuEntity.parent, parent) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - menuUidEq(menuUid) - ) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) - .orderBy(auditLogEntity.createdDate.desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + AuditLogDto.AuditDetail.class, + auditLogEntity.id.as("logId"), + auditLogEntity.createdDate.as("logDateTime"), + userEntity.userNm.as("userName"), + userEntity.userId.as("loginId"), + auditLogEntity.eventType.as("eventType"), + Projections.constructor( + AuditLogDto.LogDetail.class, + Expressions.constant("한국자산관리공사"), // serviceName + parentMenuName.as("parentMenuName"), + menuName, + menuEntity.menuUrl.as("menuUrl"), + menuEntity.description.as("menuDescription"), + menuEntity.menuOrder.as("sortOrder"), + menuEntity.isUse.as("used")))) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(menuEntity.parent, parent) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(menuUidEq(menuUid)) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .orderBy(auditLogEntity.createdDate.desc()) + .fetch(); - Long countQuery = queryFactory - .select(auditLogEntity.id.countDistinct()) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(menuEntity.parent, parent) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - menuUidEq(menuUid) - ).fetchOne(); + Long countQuery = + queryFactory + .select(auditLogEntity.id.countDistinct()) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(menuEntity.parent, parent) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(menuUidEq(menuUid)) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @Override - public Page findLogByAccountResult(AuditLogDto.MenuUserSearchReq searchReq, Long userUid) { + public Page findLogByAccountResult( + AuditLogDto.MenuUserSearchReq searchReq, Long userUid) { Pageable pageable = searchReq.toPageable(); QMenuEntity parent = new QMenuEntity("parent"); // 1depth menu name StringExpression parentMenuName = - new CaseBuilder() - .when(parent.menuUid.isNull()).then(menuEntity.menuNm) - .otherwise(parent.menuNm); + new CaseBuilder() + .when(parent.menuUid.isNull()) + .then(menuEntity.menuNm) + .otherwise(parent.menuNm); // 2depth menu name StringExpression menuName = - new CaseBuilder() - .when(parent.menuUid.isNull()).then(NULL_STRING) - .otherwise(menuEntity.menuNm); + new CaseBuilder() + .when(parent.menuUid.isNull()) + .then(NULL_STRING) + .otherwise(menuEntity.menuNm); - List foundContent = queryFactory - .select( - Projections.constructor( - AuditLogDto.AuditDetail.class, - auditLogEntity.id.as("logId"), - auditLogEntity.createdDate.as("logDateTime"), - menuEntity.menuNm.as("menuName"), - auditLogEntity.eventType.as("eventType"), - Projections.constructor( - AuditLogDto.LogDetail.class, - Expressions.constant("한국자산관리공사"), //serviceName - parentMenuName.as("parentMenuName"), - menuName, - menuEntity.menuUrl.as("menuUrl"), - menuEntity.description.as("menuDescription"), - menuEntity.menuOrder.as("sortOrder"), - menuEntity.isUse.as("used") - ) - ) - ) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(menuEntity.parent, parent) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - userUidEq(userUid) - ) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) - .orderBy(auditLogEntity.createdDate.desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + AuditLogDto.AuditDetail.class, + auditLogEntity.id.as("logId"), + auditLogEntity.createdDate.as("logDateTime"), + menuEntity.menuNm.as("menuName"), + auditLogEntity.eventType.as("eventType"), + Projections.constructor( + AuditLogDto.LogDetail.class, + Expressions.constant("한국자산관리공사"), // serviceName + parentMenuName.as("parentMenuName"), + menuName, + menuEntity.menuUrl.as("menuUrl"), + menuEntity.description.as("menuDescription"), + menuEntity.menuOrder.as("sortOrder"), + menuEntity.isUse.as("used")))) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(menuEntity.parent, parent) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(userUidEq(userUid)) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .orderBy(auditLogEntity.createdDate.desc()) + .fetch(); - Long countQuery = queryFactory - .select(auditLogEntity.id.countDistinct()) - .from(auditLogEntity) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(menuEntity.parent, parent) - .leftJoin(userEntity).on(auditLogEntity.userUid.eq(userEntity.id)) - .where( - userUidEq(userUid) - ) - .fetchOne(); + Long countQuery = + queryFactory + .select(auditLogEntity.id.countDistinct()) + .from(auditLogEntity) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(menuEntity.parent, parent) + .leftJoin(userEntity) + .on(auditLogEntity.userUid.eq(userEntity.id)) + .where(userUidEq(userUid)) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @@ -345,8 +351,10 @@ public class AuditLogRepositoryImpl extends QuerydslRepositorySupport implements } LocalDateTime startDateTime = startDate.atStartOfDay(); LocalDateTime endDateTime = endDate.plusDays(1).atStartOfDay(); - return auditLogEntity.createdDate.goe(ZonedDateTime.from(startDateTime)) - .and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime))); + return auditLogEntity + .createdDate + .goe(ZonedDateTime.from(startDateTime)) + .and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime))); } private BooleanExpression menuNameEquals(String searchValue) { @@ -383,7 +391,8 @@ public class AuditLogRepositoryImpl extends QuerydslRepositorySupport implements private BooleanExpression eventEndedAtEqDate(LocalDate logDate) { DateTimeExpression eventEndedDate = - Expressions.dateTimeTemplate(LocalDateTime.class, "date_trunc('day', {0})", auditLogEntity.createdDate); + Expressions.dateTimeTemplate( + LocalDateTime.class, "date_trunc('day', {0})", auditLogEntity.createdDate); LocalDateTime comparisonDate = logDate.atStartOfDay(); return eventEndedDate.eq(comparisonDate); @@ -399,29 +408,33 @@ public class AuditLogRepositoryImpl extends QuerydslRepositorySupport implements private NumberExpression readCount() { return new CaseBuilder() - .when(auditLogEntity.eventType.eq(EventType.READ)).then(1) - .otherwise(0) - .sum(); + .when(auditLogEntity.eventType.eq(EventType.READ)) + .then(1) + .otherwise(0) + .sum(); } private NumberExpression cudCount() { return new CaseBuilder() - .when(auditLogEntity.eventType.in(EventType.CREATE, EventType.UPDATE, EventType.DELETE)).then(1) - .otherwise(0) - .sum(); + .when(auditLogEntity.eventType.in(EventType.CREATE, EventType.UPDATE, EventType.DELETE)) + .then(1) + .otherwise(0) + .sum(); } private NumberExpression printCount() { return new CaseBuilder() - .when(auditLogEntity.eventType.eq(EventType.PRINT)).then(1) - .otherwise(0) - .sum(); + .when(auditLogEntity.eventType.eq(EventType.PRINT)) + .then(1) + .otherwise(0) + .sum(); } private NumberExpression downloadCount() { return new CaseBuilder() - .when(auditLogEntity.eventType.eq(EventType.DOWNLOAD)).then(1) - .otherwise(0) - .sum(); + .when(auditLogEntity.eventType.eq(EventType.DOWNLOAD)) + .then(1) + .otherwise(0) + .sum(); } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepository.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepository.java index b617f5dd..df5dca5d 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepository.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepository.java @@ -3,4 +3,5 @@ package com.kamco.cd.kamcoback.postgres.repository.log; import com.kamco.cd.kamcoback.postgres.entity.ErrorLogEntity; import org.springframework.data.jpa.repository.JpaRepository; -public interface ErrorLogRepository extends JpaRepository, ErrorLogRepositoryCustom {} +public interface ErrorLogRepository + extends JpaRepository, ErrorLogRepositoryCustom {} diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryCustom.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryCustom.java index 0aca6186..7da27a68 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryCustom.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryCustom.java @@ -1,12 +1,8 @@ package com.kamco.cd.kamcoback.postgres.repository.log; -import com.kamco.cd.kamcoback.log.dto.AuditLogDto; import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; -import com.kamco.cd.kamcoback.postgres.entity.AuditLogEntity; import org.springframework.data.domain.Page; -import java.time.LocalDate; - public interface ErrorLogRepositoryCustom { public Page findLogByError(ErrorLogDto.ErrorSearchReq searchReq); } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryImpl.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryImpl.java index 35054b63..854590c4 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryImpl.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/log/ErrorLogRepositoryImpl.java @@ -1,5 +1,10 @@ package com.kamco.cd.kamcoback.postgres.repository.log; +import static com.kamco.cd.kamcoback.postgres.entity.QAuditLogEntity.auditLogEntity; +import static com.kamco.cd.kamcoback.postgres.entity.QErrorLogEntity.errorLogEntity; +import static com.kamco.cd.kamcoback.postgres.entity.QMenuEntity.menuEntity; +import static com.kamco.cd.kamcoback.postgres.entity.QUserEntity.userEntity; + import com.kamco.cd.kamcoback.log.dto.ErrorLogDto; import com.kamco.cd.kamcoback.log.dto.EventStatus; import com.kamco.cd.kamcoback.log.dto.EventType; @@ -9,23 +14,18 @@ import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.StringExpression; import com.querydsl.jpa.impl.JPAQueryFactory; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.List; import java.util.Objects; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; -import static com.kamco.cd.kamcoback.postgres.entity.QAuditLogEntity.auditLogEntity; -import static com.kamco.cd.kamcoback.postgres.entity.QErrorLogEntity.errorLogEntity; -import static com.kamco.cd.kamcoback.postgres.entity.QMenuEntity.menuEntity; -import static com.kamco.cd.kamcoback.postgres.entity.QUserEntity.userEntity; - -public class ErrorLogRepositoryImpl extends QuerydslRepositorySupport implements ErrorLogRepositoryCustom { +public class ErrorLogRepositoryImpl extends QuerydslRepositorySupport + implements ErrorLogRepositoryCustom { private final JPAQueryFactory queryFactory; private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)"); @@ -37,52 +37,57 @@ public class ErrorLogRepositoryImpl extends QuerydslRepositorySupport implements @Override public Page findLogByError(ErrorLogDto.ErrorSearchReq searchReq) { Pageable pageable = searchReq.toPageable(); - List foundContent = queryFactory - .select( - Projections.constructor( - ErrorLogDto.Basic.class, - errorLogEntity.id.as("logId"), - Expressions.constant("한국자산관리공사"), //serviceName - menuEntity.menuNm.as("menuName"), - userEntity.userId.as("loginId"), - userEntity.userNm.as("userName"), - errorLogEntity.errorType.as("eventType"), - errorLogEntity.errorMessage.as("errorName"), // 기존에는 errorName 값이 있었는데 신규 테이블에는 없음. 에러 메세지와 동일 - errorLogEntity.errorLevel.as("errorLevel"), - errorLogEntity.errorCode.as("errorCode"), - errorLogEntity.errorMessage.as("errorMessage"), - errorLogEntity.stackTrace.as("errorDetail"), - errorLogEntity.createdDate - ) - ) - .from(errorLogEntity) - .leftJoin(auditLogEntity).on(errorLogEntity.id.eq(auditLogEntity.errorLogUid)) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(userEntity).on(errorLogEntity.handlerUid.eq(userEntity.id)) - .where( - eventStatusEqFailed(), - eventEndedAtBetween(searchReq.getStartDate(), searchReq.getEndDate()), - eventTypeEq(searchReq.getEventType()), - errorLevelEq(searchReq.getErrorLevel()) - ) - .offset(pageable.getOffset()) - .limit(pageable.getPageSize()) - .orderBy(errorLogEntity.createdDate.desc()) - .fetch(); + List foundContent = + queryFactory + .select( + Projections.constructor( + ErrorLogDto.Basic.class, + errorLogEntity.id.as("logId"), + Expressions.constant("한국자산관리공사"), // serviceName + menuEntity.menuNm.as("menuName"), + userEntity.userId.as("loginId"), + userEntity.userNm.as("userName"), + errorLogEntity.errorType.as("eventType"), + errorLogEntity.errorMessage.as( + "errorName"), // 기존에는 errorName 값이 있었는데 신규 테이블에는 없음. 에러 메세지와 동일 + errorLogEntity.errorLevel.as("errorLevel"), + errorLogEntity.errorCode.as("errorCode"), + errorLogEntity.errorMessage.as("errorMessage"), + errorLogEntity.stackTrace.as("errorDetail"), + errorLogEntity.createdDate)) + .from(errorLogEntity) + .leftJoin(auditLogEntity) + .on(errorLogEntity.id.eq(auditLogEntity.errorLogUid)) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(userEntity) + .on(errorLogEntity.handlerUid.eq(userEntity.id)) + .where( + eventStatusEqFailed(), + eventEndedAtBetween(searchReq.getStartDate(), searchReq.getEndDate()), + eventTypeEq(searchReq.getEventType()), + errorLevelEq(searchReq.getErrorLevel())) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .orderBy(errorLogEntity.createdDate.desc()) + .fetch(); - Long countQuery = queryFactory - .select(errorLogEntity.id.countDistinct()) - .from(errorLogEntity) - .leftJoin(auditLogEntity).on(errorLogEntity.id.eq(auditLogEntity.errorLogUid)) - .leftJoin(menuEntity).on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) - .leftJoin(userEntity).on(errorLogEntity.handlerUid.eq(userEntity.id)) - .where( - eventStatusEqFailed(), - eventEndedAtBetween(searchReq.getStartDate(), searchReq.getEndDate()), - eventTypeEq(searchReq.getEventType()), - errorLevelEq(searchReq.getErrorLevel()) - ) - .fetchOne(); + Long countQuery = + queryFactory + .select(errorLogEntity.id.countDistinct()) + .from(errorLogEntity) + .leftJoin(auditLogEntity) + .on(errorLogEntity.id.eq(auditLogEntity.errorLogUid)) + .leftJoin(menuEntity) + .on(auditLogEntity.menuUid.eq(menuEntity.menuUid)) + .leftJoin(userEntity) + .on(errorLogEntity.handlerUid.eq(userEntity.id)) + .where( + eventStatusEqFailed(), + eventEndedAtBetween(searchReq.getStartDate(), searchReq.getEndDate()), + eventTypeEq(searchReq.getEventType()), + errorLevelEq(searchReq.getErrorLevel())) + .fetchOne(); return new PageImpl<>(foundContent, pageable, countQuery); } @@ -93,8 +98,10 @@ public class ErrorLogRepositoryImpl extends QuerydslRepositorySupport implements } LocalDateTime startDateTime = startDate.atStartOfDay(); LocalDateTime endDateTime = endDate.plusDays(1).atStartOfDay(); - return auditLogEntity.createdDate.goe(ZonedDateTime.from(startDateTime)) - .and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime))); + return auditLogEntity + .createdDate + .goe(ZonedDateTime.from(startDateTime)) + .and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime))); } private BooleanExpression eventStatusEqFailed() {