diff --git a/src/main/java/com/kamco/cd/kamcoback/label/LabelAllocateApiController.java b/src/main/java/com/kamco/cd/kamcoback/label/LabelAllocateApiController.java index 1395f42b..b235ccd9 100644 --- a/src/main/java/com/kamco/cd/kamcoback/label/LabelAllocateApiController.java +++ b/src/main/java/com/kamco/cd/kamcoback/label/LabelAllocateApiController.java @@ -5,6 +5,7 @@ import com.kamco.cd.kamcoback.config.api.ApiResponseDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.InferenceDetail; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelerDetail; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelingStatDto; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkerListResponse; import com.kamco.cd.kamcoback.label.service.LabelAllocateService; import io.swagger.v3.oas.annotations.Operation; @@ -18,6 +19,7 @@ import jakarta.validation.Valid; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -36,168 +38,204 @@ public class LabelAllocateApiController { @Operation(summary = "배정 가능한 사용자 목록 조회", description = "라벨링 작업 배정을 위한 활성 상태의 사용자 목록을 조회합니다.") @ApiResponses( - value = { - @ApiResponse(responseCode = "200", description = "조회 성공"), - @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음"), - @ApiResponse(responseCode = "500", description = "서버 오류") - }) + value = { + @ApiResponse(responseCode = "200", description = "조회 성공"), + @ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음"), + @ApiResponse(responseCode = "500", description = "서버 오류") + }) @GetMapping("/avail-user") public ApiResponseDto> availUserList( - @Parameter( - description = "사용자 역할", - example = "LABELER", - schema = @Schema(allowableValues = {"LABELER", "REVIEWER"})) - @RequestParam - String role) { + @Parameter( + description = "사용자 역할", + example = "LABELER", + schema = @Schema(allowableValues = {"LABELER", "REVIEWER"})) + @RequestParam + String role) { return ApiResponseDto.ok(labelAllocateService.availUserList(role)); } @Operation( - summary = "작업현황 관리 (라벨링, 검수 진행률 요약정보, 작업자 목록)", - description = "작업현황 관리 (라벨링, 검수 진행률 요약정보, 작업자 목록)") + summary = "작업현황 관리 (라벨링, 검수 진행률 요약정보, 작업자 목록)", + description = "작업현황 관리 (라벨링, 검수 진행률 요약정보, 작업자 목록)") @ApiResponses( - value = { - @ApiResponse(responseCode = "200", description = "조회 성공"), - @ApiResponse(responseCode = "404", description = "데이터를 찾을 수 없음"), - @ApiResponse(responseCode = "500", description = "서버 오류") - }) + value = { + @ApiResponse(responseCode = "200", description = "조회 성공"), + @ApiResponse(responseCode = "404", description = "데이터를 찾을 수 없음"), + @ApiResponse(responseCode = "500", description = "서버 오류") + }) @GetMapping("/admin/workers") public ApiResponseDto getWorkerStatistics( - @Parameter(description = "분석 ID (선택)", example = "3") @RequestParam(required = false) - Long analUid, - @Parameter( - description = "작업자 유형 (선택) - 미입력 시 LABELER로 조회", - example = "LABELER", - schema = - @Schema( - allowableValues = {"LABELER", "REVIEWER"}, - defaultValue = "LABELER")) - @RequestParam(required = false) - String type, - @Parameter(description = "검색어 (작업자 이름 또는 사번으로 검색, 부분 일치)", example = "김라벨") - @RequestParam(required = false) - String search, - @Parameter( - description = "정렬 조건 (선택) - 미입력 시 이름 오름차순", - example = "REMAINING_DESC", - schema = - @Schema( - allowableValues = { - "REMAINING_DESC", - "REMAINING_ASC", - "NAME_ASC", - "NAME_DESC" - }, - defaultValue = "NAME_ASC")) - @RequestParam(required = false) - String sort, - @Parameter(description = "페이지 번호 (0부터 시작)", example = "0") - @RequestParam(defaultValue = "0") - Integer page, - @Parameter(description = "페이지 크기", example = "20") - @RequestParam(defaultValue = "20") - Integer size) { + @Parameter(description = "분석 ID (선택)", example = "3") @RequestParam(required = false) + Long analUid, + @Parameter( + description = "작업자 유형 (선택) - 미입력 시 LABELER로 조회", + example = "LABELER", + schema = + @Schema( + allowableValues = {"LABELER", "REVIEWER"}, + defaultValue = "LABELER")) + @RequestParam(required = false) + String type, + @Parameter(description = "검색어 (작업자 이름 또는 사번으로 검색, 부분 일치)", example = "김라벨") + @RequestParam(required = false) + String search, + @Parameter( + description = "정렬 조건 (선택) - 미입력 시 이름 오름차순", + example = "REMAINING_DESC", + schema = + @Schema( + allowableValues = { + "REMAINING_DESC", + "REMAINING_ASC", + "NAME_ASC", + "NAME_DESC" + }, + defaultValue = "NAME_ASC")) + @RequestParam(required = false) + String sort, + @Parameter(description = "페이지 번호 (0부터 시작)", example = "0") + @RequestParam(defaultValue = "0") + Integer page, + @Parameter(description = "페이지 크기", example = "20") + @RequestParam(defaultValue = "20") + Integer size) { // type이 null이면 기본값으로 LABELER 설정 String workerType = (type == null || type.isEmpty()) ? RoleType.LABELER.name() : type; return ApiResponseDto.ok( - labelAllocateService.getWorkerStatistics( - analUid, workerType, search, sort, page, size)); + labelAllocateService.getWorkerStatistics( + analUid, workerType, search, sort, page, size)); } @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("/allocate") public ApiResponseDto labelAllocate( - @RequestBody @Valid LabelAllocateDto.AllocateDto dto) { + @RequestBody @Valid LabelAllocateDto.AllocateDto dto) { return ApiResponseDto.okObject( - labelAllocateService.allocateAsc( - dto.getStage(), - dto.getLabelers(), - dto.getInspectors(), - dto.getCompareYyyy(), - dto.getTargetYyyy())); + labelAllocateService.allocateAsc( + dto.getStage(), + dto.getLabelers(), + dto.getInspectors(), + dto.getCompareYyyy(), + dto.getTargetYyyy())); } @Operation(summary = "작업현황 관리 > 변화탐지 회차 정보", description = "작업현황 관리 > 변화탐지 회차 정보") @ApiResponses( - value = { - @ApiResponse(responseCode = "200", description = "조회 성공"), - @ApiResponse(responseCode = "404", description = "데이터를 찾을 수 없음"), - @ApiResponse(responseCode = "500", description = "서버 오류") - }) + value = { + @ApiResponse(responseCode = "200", description = "조회 성공"), + @ApiResponse(responseCode = "404", description = "데이터를 찾을 수 없음"), + @ApiResponse(responseCode = "500", description = "서버 오류") + }) @GetMapping("/stage-detail") public ApiResponseDto findInferenceDetail( - @Parameter( - description = "회차 마스터 key", - required = true, - example = "8584e8d4-53b3-4582-bde2-28a81495a626") - @RequestParam - String uuid) { + @Parameter( + description = "회차 마스터 key", + required = true, + example = "8584e8d4-53b3-4582-bde2-28a81495a626") + @RequestParam + String uuid) { return ApiResponseDto.ok(labelAllocateService.findInferenceDetail(uuid)); } @Operation( - summary = "작업현황 관리 > 라벨러 상세 정보, 작업이관 팝업 내 라벨러 상세 정보 동일", - description = "작업현황 관리 > 라벨러 상세 정보, 작업이관 팝업 내 라벨러 상세 정보 동일") - @GetMapping("/labeler-detail") - public ApiResponseDto findLabelerDetail( - @RequestParam(defaultValue = "01022223333", required = true) String userId, - @Parameter( - description = "회차 마스터 key", - required = true, - example = "8584e8d4-53b3-4582-bde2-28a81495a626") - @RequestParam - String uuid) { - return ApiResponseDto.ok(labelAllocateService.findLabelerDetail(userId, uuid)); + summary = "작업현황 관리 > 라벨러/검수자 상세 정보, 작업이관 팝업 내 라벨러 상세 정보 동일", + description = "작업현황 관리 > 라벨러/검수자 상세 정보, 작업이관 팝업 내 라벨러 상세 정보 동일") + @GetMapping("/user-detail") + public ApiResponseDto findUserDetail( + @RequestParam(defaultValue = "01022223333", required = true) String userId, + @Parameter( + description = "회차 마스터 key", + required = true, + example = "8584e8d4-53b3-4582-bde2-28a81495a626") + @RequestParam + String uuid, + @Schema( + allowableValues = {"LABELER", "REVIEWER"}, + defaultValue = "LABELER") + @Parameter( + description = "라벨러/검수자(LABELER/REVIEWER)", + required = true) @RequestParam String type + ) { + return ApiResponseDto.ok(labelAllocateService.findUserDetail(userId, uuid, type)); } @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("/allocate-move") public ApiResponseDto labelAllocateMove( - @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "라벨링 이관", - required = true, - content = - @Content( - mediaType = "application/json", - schema = @Schema(implementation = LabelAllocateDto.AllocateMoveDto.class))) - @RequestBody - LabelAllocateDto.AllocateMoveDto dto) { + @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "라벨링 이관", + required = true, + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = LabelAllocateDto.AllocateMoveDto.class))) + @RequestBody + LabelAllocateDto.AllocateMoveDto dto) { return ApiResponseDto.okObject( - labelAllocateService.allocateMove( - dto.getAutoType(), - dto.getStage(), - dto.getLabelers(), - dto.getCompareYyyy(), - dto.getTargetYyyy())); + labelAllocateService.allocateMove( + dto.getAutoType(), + dto.getStage(), + dto.getLabelers(), + dto.getCompareYyyy(), + dto.getTargetYyyy())); + } + + @Operation( + summary = "라벨링작업 관리 > 상세 > 라벨러/검수자 일별 작업량 목록", + description = "라벨링작업 관리 > 상세 > 라벨러/검수자 일별 작업량 목록") + @GetMapping("/daily-list") + public ApiResponseDto> findDaliyList( + @RequestParam(defaultValue = "0", required = true) int page, + @RequestParam(defaultValue = "20", required = true) int size, + @Parameter( + description = "회차 마스터 key", + required = true, + example = "8584e8d4-53b3-4582-bde2-28a81495a626") + @RequestParam + String uuid, + @Parameter( + description = "사번", + required = true, + example = "123456") + @RequestParam String userId, + @Schema( + allowableValues = {"LABELER", "REVIEWER"}, + defaultValue = "LABELER") + @Parameter( + description = "라벨러/검수자(LABELER/REVIEWER)", + required = true) @RequestParam String type + ) { + LabelAllocateDto.searchReq searchReq = new LabelAllocateDto.searchReq(page, size, ""); + return ApiResponseDto.ok(labelAllocateService.findDaliyList(searchReq, uuid, userId, type)); } } diff --git a/src/main/java/com/kamco/cd/kamcoback/label/dto/LabelAllocateDto.java b/src/main/java/com/kamco/cd/kamcoback/label/dto/LabelAllocateDto.java index f5a060a8..e931ce40 100644 --- a/src/main/java/com/kamco/cd/kamcoback/label/dto/LabelAllocateDto.java +++ b/src/main/java/com/kamco/cd/kamcoback/label/dto/LabelAllocateDto.java @@ -8,7 +8,11 @@ import java.util.List; import java.util.UUID; import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; public class LabelAllocateDto { @@ -97,9 +101,9 @@ public class LabelAllocateDto { private Integer stage; @Schema( - description = "라벨러 할당 목록", - example = - """ + description = "라벨러 할당 목록", + example = + """ [ { "userId": "123456", @@ -118,9 +122,9 @@ public class LabelAllocateDto { private List labelers; @Schema( - description = "검수자 할당 목록", - example = - """ + description = "검수자 할당 목록", + example = + """ ["K20251216001", "01022225555", "K20251212001" @@ -171,6 +175,9 @@ public class LabelAllocateDto { private Long analUid; private ZonedDateTime createdDttm; private ZonedDateTime updatedDttm; + private String inspectState; + private ZonedDateTime workStatDttm; + private ZonedDateTime inspectStatDttm; } @Getter @@ -210,7 +217,7 @@ public class LabelAllocateDto { private Double percent; private Integer ranking; private ZonedDateTime createdDttm; - private String inspectorName; + private String ownerName; } @Getter @@ -225,9 +232,9 @@ public class LabelAllocateDto { private Integer stage; @Schema( - description = "라벨러 할당 목록", - example = - """ + description = "라벨러 할당 목록", + example = + """ [ { "userId": "123456", @@ -256,4 +263,43 @@ public class LabelAllocateDto { private Long geoUid; private Long mapSheetNum; } + + @Getter + @Setter + @AllArgsConstructor + public static class LabelingStatDto { + + private String workDate; + private Long dailyTotalCnt; + private Long totalCnt; + private Long assignedCnt; + private Long skipCnt; + private Long completeCnt; + private Long remainCnt; + } + + @Schema(name = "searchReq", description = "일자별 작업 목록 요청") + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class searchReq { + + // 페이징 파라미터 + private int page = 0; + private int size = 20; + private String sort; + + public Pageable toPageable() { + if (sort != null && !sort.isEmpty()) { + String[] sortParams = sort.split(","); + String property = sortParams[0]; + Sort.Direction direction = + 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); + } + } + } diff --git a/src/main/java/com/kamco/cd/kamcoback/label/service/LabelAllocateService.java b/src/main/java/com/kamco/cd/kamcoback/label/service/LabelAllocateService.java index 7da6156c..057506e8 100644 --- a/src/main/java/com/kamco/cd/kamcoback/label/service/LabelAllocateService.java +++ b/src/main/java/com/kamco/cd/kamcoback/label/service/LabelAllocateService.java @@ -6,6 +6,7 @@ import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.AllocateInfoDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.InferenceDetail; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelerDetail; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelingStatDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.TargetUser; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.UserList; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.DailyHistory; @@ -16,6 +17,7 @@ import java.time.LocalDate; import java.util.List; import java.util.Objects; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -36,22 +38,22 @@ public class LabelAllocateService { /** * 도엽 기준 asc sorting 해서 할당 수만큼 배정하는 로직 * - * @param stage 회차 - * @param targetUsers 라벨러 목록 + * @param stage 회차 + * @param targetUsers 라벨러 목록 * @param targetInspectors 검수자 목록 */ @Transactional public ApiResponseDto.ResponseObj allocateAsc( - Integer stage, - List targetUsers, - List targetInspectors, - Integer compareYyyy, - Integer targetYyyy) { + Integer stage, + List targetUsers, + List targetInspectors, + Integer compareYyyy, + Integer targetYyyy) { Long lastId = null; // geom 잔여건수 조회 Long chargeCnt = - labelAllocateCoreService.findLabelUnAssignedCnt(stage, compareYyyy, targetYyyy); + labelAllocateCoreService.findLabelUnAssignedCnt(stage, compareYyyy, targetYyyy); if (chargeCnt <= 0) { return new ApiResponseDto.ResponseObj(ApiResponseCode.DUPLICATE_DATA, "이미 배정완료된 회차 입니다."); } @@ -59,15 +61,15 @@ public class LabelAllocateService { Long totalDemand = targetUsers.stream().mapToLong(TargetUser::getDemand).sum(); if (!Objects.equals(chargeCnt, totalDemand)) { return new ApiResponseDto.ResponseObj( - ApiResponseCode.BAD_REQUEST, "총 잔여건수와 요청 값의 합계가 맞지 않습니다."); + ApiResponseCode.BAD_REQUEST, "총 잔여건수와 요청 값의 합계가 맞지 않습니다."); } List allIds = - labelAllocateCoreService.fetchNextIds(lastId, chargeCnt, compareYyyy, targetYyyy, stage); + labelAllocateCoreService.fetchNextIds(lastId, chargeCnt, compareYyyy, targetYyyy, stage); // MapSheetAnalInferenceEntity analUid 가져오기 Long analUid = - labelAllocateCoreService.findMapSheetAnalInferenceUid(compareYyyy, targetYyyy, stage); + labelAllocateCoreService.findMapSheetAnalInferenceUid(compareYyyy, targetYyyy, stage); int index = 0; for (TargetUser target : targetUsers) { @@ -113,52 +115,52 @@ public class LabelAllocateService { /** * 작업자 통계 조회 * - * @param analUid 분석 ID + * @param analUid 분석 ID * @param workerType 작업자 유형 (LABELER/INSPECTOR) - * @param search 검색어 (이름 또는 사번) - * @param sortType 정렬 조건 - * @param page 페이지 번호 (0부터 시작) - * @param size 페이지 크기 + * @param search 검색어 (이름 또는 사번) + * @param sortType 정렬 조건 + * @param page 페이지 번호 (0부터 시작) + * @param size 페이지 크기 * @return 작업자 목록 및 통계 */ public WorkerListResponse getWorkerStatistics( - Long analUid, - String workerType, - String search, - String sortType, - Integer page, - Integer size) { + Long analUid, + String workerType, + String search, + String sortType, + Integer page, + Integer size) { // 작업 진행 현황 조회 var progressInfo = labelAllocateCoreService.findWorkProgressInfo(analUid); // 작업자 통계 조회 List workers = - labelAllocateCoreService.findWorkerStatistics( - analUid, workerType, search, sortType); + labelAllocateCoreService.findWorkerStatistics( + analUid, workerType, search, sortType); // 각 작업자별 3일치 처리량 조회 LocalDate today = LocalDate.now(); for (WorkerStatistics worker : workers) { Long day1Count = - labelAllocateCoreService.findDailyProcessedCount( - worker.getWorkerId(), workerType, today.minusDays(1), analUid); + labelAllocateCoreService.findDailyProcessedCount( + worker.getWorkerId(), workerType, today.minusDays(1), analUid); Long day2Count = - labelAllocateCoreService.findDailyProcessedCount( - worker.getWorkerId(), workerType, today.minusDays(2), analUid); + labelAllocateCoreService.findDailyProcessedCount( + worker.getWorkerId(), workerType, today.minusDays(2), analUid); Long day3Count = - labelAllocateCoreService.findDailyProcessedCount( - worker.getWorkerId(), workerType, today.minusDays(3), analUid); + labelAllocateCoreService.findDailyProcessedCount( + worker.getWorkerId(), workerType, today.minusDays(3), analUid); long average = (day1Count + day2Count + day3Count) / 3; DailyHistory history = - DailyHistory.builder() - .day1Ago(day1Count) - .day2Ago(day2Count) - .day3Ago(day3Count) - .average(average) - .build(); + DailyHistory.builder() + .day1Ago(day1Count) + .day2Ago(day2Count) + .day3Ago(day3Count) + .average(average) + .build(); worker.setHistory(history); @@ -175,16 +177,16 @@ public class LabelAllocateService { int toIndex = Math.min(fromIndex + size, workers.size()); List pagedWorkers = - (fromIndex < workers.size()) ? workers.subList(fromIndex, toIndex) : List.of(); + (fromIndex < workers.size()) ? workers.subList(fromIndex, toIndex) : List.of(); return WorkerListResponse.builder() - .progressInfo(progressInfo) - .workers(pagedWorkers) - .currentPage(page) - .pageSize(size) - .totalElements(totalElements) - .totalPages(totalPages) - .build(); + .progressInfo(progressInfo) + .workers(pagedWorkers) + .currentPage(page) + .pageSize(size) + .totalElements(totalElements) + .totalPages(totalPages) + .build(); } public InferenceDetail findInferenceDetail(String uuid) { @@ -192,11 +194,11 @@ public class LabelAllocateService { } public ApiResponseDto.ResponseObj allocateMove( - String autoType, - Integer stage, - List targetUsers, - Integer compareYyyy, - Integer targetYyyy) { + String autoType, + Integer stage, + List targetUsers, + Integer compareYyyy, + Integer targetYyyy) { Long lastId = null; Long chargeCnt = targetUsers.stream().mapToLong(TargetUser::getDemand).sum(); @@ -206,8 +208,8 @@ public class LabelAllocateService { } List allIds = - labelAllocateCoreService.fetchNextMoveIds( - lastId, chargeCnt, compareYyyy, targetYyyy, stage); + labelAllocateCoreService.fetchNextMoveIds( + lastId, chargeCnt, compareYyyy, targetYyyy, stage); int index = 0; for (TargetUser target : targetUsers) { int end = index + target.getDemand(); @@ -220,7 +222,19 @@ public class LabelAllocateService { return new ApiResponseDto.ResponseObj(ApiResponseCode.OK, "이관을 완료하였습니다."); } - public LabelerDetail findLabelerDetail(String userId, String uuid) { - return labelAllocateCoreService.findLabelerDetail(userId, uuid); + public LabelerDetail findUserDetail(String userId, String uuid, String type) { + if (type.equals("LABELER")) { + return labelAllocateCoreService.findLabelerDetail(userId, uuid); + } else { + return labelAllocateCoreService.findInspectorDetail(userId, uuid); + } + } + + public Page findDaliyList(LabelAllocateDto.searchReq searchReq, String uuid, String userId, String type) { + if (type.equals("LABELER")) { + return labelAllocateCoreService.findLabelerDailyStat(searchReq, uuid, userId); + } else { + return labelAllocateCoreService.findInspectorDailyStat(searchReq, uuid, userId); + } } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/core/LabelAllocateCoreService.java b/src/main/java/com/kamco/cd/kamcoback/postgres/core/LabelAllocateCoreService.java index d71471c0..fb7301e0 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/core/LabelAllocateCoreService.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/core/LabelAllocateCoreService.java @@ -4,7 +4,9 @@ import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.AllocateInfoDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.InferenceDetail; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelerDetail; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelingStatDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.UserList; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.searchReq; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkProgressInfo; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkerStatistics; import com.kamco.cd.kamcoback.postgres.entity.LabelingAssignmentEntity; @@ -13,6 +15,7 @@ import java.time.LocalDate; import java.util.List; import java.util.UUID; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; @Service @@ -22,7 +25,7 @@ public class LabelAllocateCoreService { private final LabelAllocateRepository labelAllocateRepository; public List fetchNextIds( - Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { + Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { return labelAllocateRepository.fetchNextIds(lastId, batchSize, compareYyyy, targetYyyy, stage); } @@ -32,8 +35,8 @@ public class LabelAllocateCoreService { public List findAssignedLabelerList(Long analUid) { return labelAllocateRepository.findAssignedLabelerList(analUid).stream() - .map(LabelingAssignmentEntity::toDto) - .toList(); + .map(LabelingAssignmentEntity::toDto) + .toList(); } public Long findLabelUnAssignedCnt(Integer stage, Integer compareYyyy, Integer targetYyyy) { @@ -49,12 +52,12 @@ public class LabelAllocateCoreService { } public List findWorkerStatistics( - Long analUid, - String workerType, - String search, - String sortType) { + Long analUid, + String workerType, + String search, + String sortType) { return labelAllocateRepository.findWorkerStatistics( - analUid, workerType, search, sortType); + analUid, workerType, search, sortType); } public WorkProgressInfo findWorkProgressInfo(Long analUid) { @@ -62,7 +65,7 @@ public class LabelAllocateCoreService { } public Long findDailyProcessedCount( - String workerId, String workerType, LocalDate date, Long analUid) { + String workerId, String workerType, LocalDate date, Long analUid) { return labelAllocateRepository.findDailyProcessedCount(workerId, workerType, date, analUid); } @@ -75,9 +78,9 @@ public class LabelAllocateCoreService { } public List fetchNextMoveIds( - Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { + Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { return labelAllocateRepository.fetchNextMoveIds( - lastId, batchSize, compareYyyy, targetYyyy, stage); + lastId, batchSize, compareYyyy, targetYyyy, stage); } public void assignOwnerMove(List sub, String userId) { @@ -95,4 +98,16 @@ public class LabelAllocateCoreService { public void insertInspector(Long analUid, String inspector) { labelAllocateRepository.insertInspector(analUid, inspector); } + + public Page findLabelerDailyStat(searchReq searchReq, String uuid, String userId) { + return labelAllocateRepository.findLabelerDailyStat(searchReq, uuid, userId); + } + + public Page findInspectorDailyStat(searchReq searchReq, String uuid, String userId) { + return labelAllocateRepository.findInspectorDailyStat(searchReq, uuid, userId); + } + + public LabelerDetail findInspectorDetail(String userId, String uuid) { + return labelAllocateRepository.findInspectorDetail(userId, uuid); + } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/LabelingAssignmentEntity.java b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/LabelingAssignmentEntity.java index 22afd4aa..88b5a15b 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/entity/LabelingAssignmentEntity.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/entity/LabelingAssignmentEntity.java @@ -6,6 +6,7 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; +import java.time.ZonedDateTime; import java.util.UUID; @Entity @@ -40,18 +41,31 @@ public class LabelingAssignmentEntity extends CommonDateEntity { @Column(name = "anal_uid") private Long analUid; + @Column(name = "inspect_state") + private String inspectState; + + @Column(name = "work_stat_dttm") + private ZonedDateTime workStatDttm; + + @Column(name = "inspect_stat_dttm") + private ZonedDateTime inspectStatDttm; + public LabelAllocateDto.Basic toDto() { return new LabelAllocateDto.Basic( - this.assignmentUid, - this.inferenceGeomUid, - this.workerUid, - this.inspectorUid, - this.workState, - this.stagnationYn, - this.assignGroupId, - this.learnGeomUid, - this.analUid, - super.getCreatedDate(), - super.getModifiedDate()); + this.assignmentUid, + this.inferenceGeomUid, + this.workerUid, + this.inspectorUid, + this.workState, + this.stagnationYn, + this.assignGroupId, + this.learnGeomUid, + this.analUid, + super.getCreatedDate(), + super.getModifiedDate(), + this.inspectState, + this.workStatDttm, + this.inspectStatDttm + ); } } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryCustom.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryCustom.java index a127e142..9177bceb 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryCustom.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryCustom.java @@ -1,8 +1,10 @@ package com.kamco.cd.kamcoback.postgres.repository.label; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.AllocateInfoDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.InferenceDetail; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelerDetail; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelingStatDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.UserList; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkProgressInfo; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkerStatistics; @@ -10,11 +12,12 @@ import com.kamco.cd.kamcoback.postgres.entity.LabelingAssignmentEntity; import java.time.LocalDate; import java.util.List; import java.util.UUID; +import org.springframework.data.domain.Page; public interface LabelAllocateRepositoryCustom { List fetchNextIds( - Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage); + Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage); void assignOwner(List ids, String userId, Long analUid); @@ -28,7 +31,7 @@ public interface LabelAllocateRepositoryCustom { // 작업자 통계 조회 List findWorkerStatistics( - Long analUid, String workerType, String search, String sortType); + Long analUid, String workerType, String search, String sortType); // 작업 진행 현황 조회 WorkProgressInfo findWorkProgressInfo(Long analUid); @@ -41,7 +44,7 @@ public interface LabelAllocateRepositoryCustom { InferenceDetail findInferenceDetail(String uuid); List fetchNextMoveIds( - Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage); + Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage); void assignOwnerMove(List sub, String userId); @@ -50,4 +53,10 @@ public interface LabelAllocateRepositoryCustom { Long findMapSheetAnalInferenceUid(Integer compareYyyy, Integer targetYyyy, Integer stage); void insertInspector(Long analUid, String inspector); + + Page findLabelerDailyStat(LabelAllocateDto.searchReq searchReq, String uuid, String userId); + + Page findInspectorDailyStat(LabelAllocateDto.searchReq searchReq, String uuid, String userId); + + LabelerDetail findInspectorDetail(String userId, String uuid); } diff --git a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryImpl.java b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryImpl.java index 6d973dad..c7173589 100644 --- a/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryImpl.java +++ b/src/main/java/com/kamco/cd/kamcoback/postgres/repository/label/LabelAllocateRepositoryImpl.java @@ -13,12 +13,15 @@ import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.InferenceDetail; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.InspectState; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelState; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelerDetail; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelingStatDto; import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.UserList; +import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.searchReq; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkProgressInfo; import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkerStatistics; import com.kamco.cd.kamcoback.postgres.entity.LabelingAssignmentEntity; import com.kamco.cd.kamcoback.postgres.entity.MapSheetAnalInferenceEntity; import com.kamco.cd.kamcoback.postgres.entity.QMemberEntity; +import com.querydsl.core.types.Expression; import com.querydsl.core.types.Projections; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.CaseBuilder; @@ -39,6 +42,9 @@ import java.util.Objects; import java.util.UUID; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @Slf4j @@ -48,28 +54,29 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto private final JPAQueryFactory queryFactory; - @PersistenceContext private EntityManager em; + @PersistenceContext + private EntityManager em; @Override public List fetchNextIds( - Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { + Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { return queryFactory - .select( - Projections.constructor( - AllocateInfoDto.class, - mapSheetAnalDataInferenceGeomEntity.geoUid, - mapSheetAnalDataInferenceGeomEntity.mapSheetNum)) - .from(mapSheetAnalDataInferenceGeomEntity) - .where( - lastId == null ? null : mapSheetAnalDataInferenceGeomEntity.geoUid.gt(lastId), - mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy), - mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy), - mapSheetAnalDataInferenceGeomEntity.stage.eq(stage), - mapSheetAnalDataInferenceGeomEntity.labelState.isNull()) - .orderBy(mapSheetAnalDataInferenceGeomEntity.mapSheetNum.asc()) - .limit(batchSize) - .fetch(); + .select( + Projections.constructor( + AllocateInfoDto.class, + mapSheetAnalDataInferenceGeomEntity.geoUid, + mapSheetAnalDataInferenceGeomEntity.mapSheetNum)) + .from(mapSheetAnalDataInferenceGeomEntity) + .where( + lastId == null ? null : mapSheetAnalDataInferenceGeomEntity.geoUid.gt(lastId), + mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy), + mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy), + mapSheetAnalDataInferenceGeomEntity.stage.eq(stage), + mapSheetAnalDataInferenceGeomEntity.labelState.isNull()) + .orderBy(mapSheetAnalDataInferenceGeomEntity.mapSheetNum.asc()) + .limit(batchSize) + .fetch(); } @Override @@ -77,10 +84,10 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto // analUid로 분석 정보 조회 MapSheetAnalInferenceEntity analEntity = - queryFactory - .selectFrom(mapSheetAnalInferenceEntity) - .where(mapSheetAnalInferenceEntity.id.eq(analUid)) - .fetchOne(); + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.id.eq(analUid)) + .fetchOne(); if (Objects.isNull(analEntity)) { throw new EntityNotFoundException("MapSheetAnalInferenceEntity not found for analUid: "); @@ -88,20 +95,20 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto // data_geom 테이블에 label state 를 ASSIGNED 로 update List geoUidList = - ids.stream().map(AllocateInfoDto::getGeoUid).filter(Objects::nonNull).toList(); + ids.stream().map(AllocateInfoDto::getGeoUid).filter(Objects::nonNull).toList(); queryFactory - .update(mapSheetAnalDataInferenceGeomEntity) - .set(mapSheetAnalDataInferenceGeomEntity.labelState, LabelState.ASSIGNED.getId()) - .set(mapSheetAnalDataInferenceGeomEntity.labelStateDttm, ZonedDateTime.now()) - .set(mapSheetAnalDataInferenceGeomEntity.testState, InspectState.UNCONFIRM.getId()) - .set(mapSheetAnalDataInferenceGeomEntity.testStateDttm, ZonedDateTime.now()) - .where(mapSheetAnalDataInferenceGeomEntity.geoUid.in(geoUidList)) - .execute(); + .update(mapSheetAnalDataInferenceGeomEntity) + .set(mapSheetAnalDataInferenceGeomEntity.labelState, LabelState.ASSIGNED.getId()) + .set(mapSheetAnalDataInferenceGeomEntity.labelStateDttm, ZonedDateTime.now()) + .set(mapSheetAnalDataInferenceGeomEntity.testState, InspectState.UNCONFIRM.getId()) + .set(mapSheetAnalDataInferenceGeomEntity.testStateDttm, ZonedDateTime.now()) + .where(mapSheetAnalDataInferenceGeomEntity.geoUid.in(geoUidList)) + .execute(); // 라벨러 할당 테이블에 insert String sql = - """ + """ insert into tb_labeling_assignment (assignment_uid, inference_geom_uid, worker_uid, work_state, assign_group_id, anal_uid) @@ -110,13 +117,13 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto for (AllocateInfoDto info : ids) { em.createNativeQuery(sql) - .setParameter(1, UUID.randomUUID()) - .setParameter(2, info.getGeoUid()) - .setParameter(3, userId) - .setParameter(4, LabelState.ASSIGNED.getId()) - .setParameter(5, info.getMapSheetNum()) - .setParameter(6, analEntity.getId()) - .executeUpdate(); + .setParameter(1, UUID.randomUUID()) + .setParameter(2, info.getGeoUid()) + .setParameter(3, userId) + .setParameter(4, LabelState.ASSIGNED.getId()) + .setParameter(5, info.getMapSheetNum()) + .setParameter(6, analEntity.getId()) + .executeUpdate(); } em.flush(); @@ -127,137 +134,137 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto public List findAssignedLabelerList(Long analUid) { // analUid로 분석 정보 조회 MapSheetAnalInferenceEntity analEntity = - queryFactory - .selectFrom(mapSheetAnalInferenceEntity) - .where(mapSheetAnalInferenceEntity.id.eq(analUid)) - .fetchOne(); + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.id.eq(analUid)) + .fetchOne(); if (Objects.isNull(analEntity)) { throw new EntityNotFoundException("mapSheetAnalInferenceEntity not found for analUid: "); } return queryFactory - .selectFrom(labelingAssignmentEntity) - .where( - labelingAssignmentEntity.analUid.eq(analEntity.getId()), - labelingAssignmentEntity.workState.eq(LabelState.ASSIGNED.getId()), - labelingAssignmentEntity.inspectorUid.isNull()) - .orderBy(labelingAssignmentEntity.workerUid.asc()) - .fetch(); + .selectFrom(labelingAssignmentEntity) + .where( + labelingAssignmentEntity.analUid.eq(analEntity.getId()), + labelingAssignmentEntity.workState.eq(LabelState.ASSIGNED.getId()), + labelingAssignmentEntity.inspectorUid.isNull()) + .orderBy(labelingAssignmentEntity.workerUid.asc()) + .fetch(); } @Override public Long findLabelUnAssignedCnt(Integer stage, Integer compareYyyy, Integer targetYyyy) { return queryFactory - .select(mapSheetAnalDataInferenceGeomEntity.geoUid.count()) - .from(mapSheetAnalDataInferenceGeomEntity) - .where( - mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy), - mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy), - mapSheetAnalDataInferenceGeomEntity.stage.eq(stage), - mapSheetAnalDataInferenceGeomEntity.labelState.isNull()) - .fetchOne(); + .select(mapSheetAnalDataInferenceGeomEntity.geoUid.count()) + .from(mapSheetAnalDataInferenceGeomEntity) + .where( + mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy), + mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy), + mapSheetAnalDataInferenceGeomEntity.stage.eq(stage), + mapSheetAnalDataInferenceGeomEntity.labelState.isNull()) + .fetchOne(); } @Override public void assignInspector(UUID assignmentUid, String inspectorUid) { queryFactory - .update(labelingAssignmentEntity) - .set(labelingAssignmentEntity.inspectorUid, inspectorUid) - .where(labelingAssignmentEntity.assignmentUid.eq(assignmentUid)) - .execute(); + .update(labelingAssignmentEntity) + .set(labelingAssignmentEntity.inspectorUid, inspectorUid) + .where(labelingAssignmentEntity.assignmentUid.eq(assignmentUid)) + .execute(); } @Override public List availUserList(String role) { return queryFactory - .select( - Projections.constructor( - LabelAllocateDto.UserList.class, - memberEntity.userRole, - memberEntity.employeeNo, - memberEntity.name)) - .from(memberEntity) - .where( - memberEntity.userRole.eq(role), - memberEntity.status.eq(com.kamco.cd.kamcoback.common.enums.StatusType.ACTIVE.getId())) - .orderBy(memberEntity.name.asc()) - .fetch(); + .select( + Projections.constructor( + LabelAllocateDto.UserList.class, + memberEntity.userRole, + memberEntity.employeeNo, + memberEntity.name)) + .from(memberEntity) + .where( + memberEntity.userRole.eq(role), + memberEntity.status.eq(com.kamco.cd.kamcoback.common.enums.StatusType.ACTIVE.getId())) + .orderBy(memberEntity.name.asc()) + .fetch(); } @Override public List findWorkerStatistics( - Long analUid, - String workerType, - String search, - String sortType) { + Long analUid, + String workerType, + String search, + String sortType) { // 작업자 유형에 따른 필드 선택 StringExpression workerIdField = - "REVIEWER".equals(workerType) - ? labelingAssignmentEntity.inspectorUid - : labelingAssignmentEntity.workerUid; + "REVIEWER".equals(workerType) + ? labelingAssignmentEntity.inspectorUid + : labelingAssignmentEntity.workerUid; BooleanExpression workerCondition = - "REVIEWER".equals(workerType) - ? labelingAssignmentEntity.inspectorUid.isNotNull() - : labelingAssignmentEntity.workerUid.isNotNull(); + "REVIEWER".equals(workerType) + ? labelingAssignmentEntity.inspectorUid.isNotNull() + : labelingAssignmentEntity.workerUid.isNotNull(); // 검색 조건 (이름 또는 사번으로 검색) BooleanExpression searchCondition = null; if (search != null && !search.isEmpty()) { searchCondition = memberEntity.name.contains(search) - .or(memberEntity.employeeNo.contains(search)); + .or(memberEntity.employeeNo.contains(search)); } // 완료, 스킵, 남은 작업 계산 NumberExpression completedSum = - new CaseBuilder() - .when(labelingAssignmentEntity.workState.eq("DONE")) - .then(1L) - .otherwise(0L) - .sum(); + new CaseBuilder() + .when(labelingAssignmentEntity.workState.eq("DONE")) + .then(1L) + .otherwise(0L) + .sum(); NumberExpression skippedSum = - new CaseBuilder() - .when(labelingAssignmentEntity.workState.eq("SKIP")) - .then(1L) - .otherwise(0L) - .sum(); + new CaseBuilder() + .when(labelingAssignmentEntity.workState.eq("SKIP")) + .then(1L) + .otherwise(0L) + .sum(); NumberExpression remainingSum = - new CaseBuilder() - .when( - labelingAssignmentEntity - .workState - .notIn("DONE", "SKIP") - .and(labelingAssignmentEntity.workState.isNotNull())) - .then(1L) - .otherwise(0L) - .sum(); + new CaseBuilder() + .when( + labelingAssignmentEntity + .workState + .notIn("DONE", "SKIP") + .and(labelingAssignmentEntity.workState.isNotNull())) + .then(1L) + .otherwise(0L) + .sum(); // 기본 통계 조회 쿼리 BooleanExpression analUidCondition = analUid != null ? labelingAssignmentEntity.analUid.eq(analUid) : null; var baseQuery = - queryFactory - .select( - workerIdField, - memberEntity.name, - workerIdField.count(), - completedSum, - skippedSum, - remainingSum, - labelingAssignmentEntity.stagnationYn.max()) - .from(labelingAssignmentEntity) - .leftJoin(memberEntity) - .on( - "REVIEWER".equals(workerType) - ? memberEntity.employeeNo.eq(labelingAssignmentEntity.inspectorUid) - : memberEntity.employeeNo.eq(labelingAssignmentEntity.workerUid)) - .where(analUidCondition, workerCondition, searchCondition) - .groupBy(workerIdField, memberEntity.name); + queryFactory + .select( + workerIdField, + memberEntity.name, + workerIdField.count(), + completedSum, + skippedSum, + remainingSum, + labelingAssignmentEntity.stagnationYn.max()) + .from(labelingAssignmentEntity) + .leftJoin(memberEntity) + .on( + "REVIEWER".equals(workerType) + ? memberEntity.employeeNo.eq(labelingAssignmentEntity.inspectorUid) + : memberEntity.employeeNo.eq(labelingAssignmentEntity.workerUid)) + .where(analUidCondition, workerCondition, searchCondition) + .groupBy(workerIdField, memberEntity.name); // 정렬 조건 적용 if (sortType != null) { @@ -283,22 +290,22 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto // 결과를 DTO로 변환 return baseQuery.fetch().stream() - .map( - tuple -> { - Character maxStagnationYn = tuple.get(labelingAssignmentEntity.stagnationYn.max()); - return WorkerStatistics.builder() - .workerId(tuple.get(workerIdField)) - .workerName(tuple.get(memberEntity.name)) - .workerType(workerType) - .totalAssigned(tuple.get(workerIdField.count())) - .completed(tuple.get(completedSum)) - .skipped(tuple.get(skippedSum)) - .remaining(tuple.get(remainingSum)) - .history(null) // 3일 이력은 Service에서 채움 - .isStagnated(maxStagnationYn != null && maxStagnationYn == 'Y') - .build(); - }) - .toList(); + .map( + tuple -> { + Character maxStagnationYn = tuple.get(labelingAssignmentEntity.stagnationYn.max()); + return WorkerStatistics.builder() + .workerId(tuple.get(workerIdField)) + .workerName(tuple.get(memberEntity.name)) + .workerType(workerType) + .totalAssigned(tuple.get(workerIdField.count())) + .completed(tuple.get(completedSum)) + .skipped(tuple.get(skippedSum)) + .remaining(tuple.get(remainingSum)) + .history(null) // 3일 이력은 Service에서 채움 + .isStagnated(maxStagnationYn != null && maxStagnationYn == 'Y') + .build(); + }) + .toList(); } @Override @@ -307,112 +314,112 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto // 전체 배정 건수 Long totalAssigned = - queryFactory - .select(labelingAssignmentEntity.count()) - .from(labelingAssignmentEntity) - .where(analUidCondition) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.count()) + .from(labelingAssignmentEntity) + .where(analUidCondition) + .fetchOne(); // 완료 + 스킵 건수 Long completedCount = - queryFactory - .select(labelingAssignmentEntity.count()) - .from(labelingAssignmentEntity) - .where( - analUidCondition, - labelingAssignmentEntity.workState.in("DONE", "SKIP")) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.count()) + .from(labelingAssignmentEntity) + .where( + analUidCondition, + labelingAssignmentEntity.workState.in("DONE", "SKIP")) + .fetchOne(); // 투입된 라벨러 수 (고유한 worker_uid 수) Long labelerCount = - queryFactory - .select(labelingAssignmentEntity.workerUid.countDistinct()) - .from(labelingAssignmentEntity) - .where( - analUidCondition, - labelingAssignmentEntity.workerUid.isNotNull()) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.workerUid.countDistinct()) + .from(labelingAssignmentEntity) + .where( + analUidCondition, + labelingAssignmentEntity.workerUid.isNotNull()) + .fetchOne(); // 남은 라벨링 작업 데이터 수 Long remainingLabelCount = - queryFactory - .select(labelingAssignmentEntity.count()) - .from(labelingAssignmentEntity) - .where( - analUidCondition, - labelingAssignmentEntity.workerUid.isNotNull(), - labelingAssignmentEntity.workState.notIn("DONE", "SKIP")) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.count()) + .from(labelingAssignmentEntity) + .where( + analUidCondition, + labelingAssignmentEntity.workerUid.isNotNull(), + labelingAssignmentEntity.workState.notIn("DONE", "SKIP")) + .fetchOne(); // 투입된 검수자 수 (고유한 inspector_uid 수) Long inspectorCount = - queryFactory - .select(labelingAssignmentEntity.inspectorUid.countDistinct()) - .from(labelingAssignmentEntity) - .where( - analUidCondition, - labelingAssignmentEntity.inspectorUid.isNotNull()) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.inspectorUid.countDistinct()) + .from(labelingAssignmentEntity) + .where( + analUidCondition, + labelingAssignmentEntity.inspectorUid.isNotNull()) + .fetchOne(); // 남은 검수 작업 데이터 수 Long remainingInspectCount = - queryFactory - .select(labelingAssignmentEntity.count()) - .from(labelingAssignmentEntity) - .where( - analUidCondition, - labelingAssignmentEntity.inspectorUid.isNotNull(), - labelingAssignmentEntity.workState.notIn("DONE")) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.count()) + .from(labelingAssignmentEntity) + .where( + analUidCondition, + labelingAssignmentEntity.inspectorUid.isNotNull(), + labelingAssignmentEntity.workState.notIn("DONE")) + .fetchOne(); // 진행률 계산 double progressRate = 0.0; if (totalAssigned != null && totalAssigned > 0) { progressRate = - (completedCount != null ? completedCount.doubleValue() : 0.0) / totalAssigned * 100; + (completedCount != null ? completedCount.doubleValue() : 0.0) / totalAssigned * 100; } // 작업 상태 판단 (간단하게 진행률 100%면 종료, 아니면 진행중) String workStatus = (progressRate >= 100.0) ? "종료" : "진행중"; return WorkProgressInfo.builder() - .labelingProgressRate(progressRate) - .workStatus(workStatus) - .completedCount(completedCount != null ? completedCount : 0L) - .totalAssignedCount(totalAssigned != null ? totalAssigned : 0L) - .labelerCount(labelerCount != null ? labelerCount : 0L) - .remainingLabelCount(remainingLabelCount != null ? remainingLabelCount : 0L) - .inspectorCount(inspectorCount != null ? inspectorCount : 0L) - .remainingInspectCount(remainingInspectCount != null ? remainingInspectCount : 0L) - .build(); + .labelingProgressRate(progressRate) + .workStatus(workStatus) + .completedCount(completedCount != null ? completedCount : 0L) + .totalAssignedCount(totalAssigned != null ? totalAssigned : 0L) + .labelerCount(labelerCount != null ? labelerCount : 0L) + .remainingLabelCount(remainingLabelCount != null ? remainingLabelCount : 0L) + .inspectorCount(inspectorCount != null ? inspectorCount : 0L) + .remainingInspectCount(remainingInspectCount != null ? remainingInspectCount : 0L) + .build(); } @Override public Long findDailyProcessedCount( - String workerId, String workerType, LocalDate date, Long analUid) { + String workerId, String workerType, LocalDate date, Long analUid) { // 해당 날짜의 시작과 끝 시간 ZonedDateTime startOfDay = date.atStartOfDay(ZoneId.systemDefault()); ZonedDateTime endOfDay = date.atTime(LocalTime.MAX).atZone(ZoneId.systemDefault()); BooleanExpression workerCondition = - "REVIEWER".equals(workerType) - ? labelingAssignmentEntity.inspectorUid.eq(workerId) - : labelingAssignmentEntity.workerUid.eq(workerId); + "REVIEWER".equals(workerType) + ? labelingAssignmentEntity.inspectorUid.eq(workerId) + : labelingAssignmentEntity.workerUid.eq(workerId); BooleanExpression analUidCondition = analUid != null ? labelingAssignmentEntity.analUid.eq(analUid) : null; Long count = - queryFactory - .select(labelingAssignmentEntity.count()) - .from(labelingAssignmentEntity) - .where( - analUidCondition, - workerCondition, - labelingAssignmentEntity.workState.in( - LabelState.DONE.getId(), LabelState.SKIP.getId()), - labelingAssignmentEntity.modifiedDate.between(startOfDay, endOfDay)) - .fetchOne(); + queryFactory + .select(labelingAssignmentEntity.count()) + .from(labelingAssignmentEntity) + .where( + analUidCondition, + workerCondition, + labelingAssignmentEntity.workState.in( + LabelState.DONE.getId(), LabelState.SKIP.getId()), + labelingAssignmentEntity.modifiedDate.between(startOfDay, endOfDay)) + .fetchOne(); return count != null ? count : 0L; } @@ -420,10 +427,10 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto @Override public void assignInspectorBulk(List assignmentUids, String inspectorUid) { queryFactory - .update(labelingAssignmentEntity) - .set(labelingAssignmentEntity.inspectorUid, inspectorUid) - .where(labelingAssignmentEntity.assignmentUid.in(assignmentUids)) - .execute(); + .update(labelingAssignmentEntity) + .set(labelingAssignmentEntity.inspectorUid, inspectorUid) + .where(labelingAssignmentEntity.assignmentUid.in(assignmentUids)) + .execute(); em.clear(); } @@ -432,64 +439,64 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto public InferenceDetail findInferenceDetail(String uuid) { // analUid로 분석 정보 조회 MapSheetAnalInferenceEntity analEntity = - queryFactory - .selectFrom(mapSheetAnalInferenceEntity) - .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) - .fetchOne(); + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) + .fetchOne(); if (Objects.isNull(analEntity)) { throw new EntityNotFoundException("MapSheetAnalInferenceEntity not found for analUid: "); } return queryFactory - .select( - Projections.constructor( - InferenceDetail.class, - mapSheetAnalEntity.analTitle, - Expressions.numberTemplate(Integer.class, "{0}", 4), - mapSheetAnalEntity.gukyuinApplyDttm, - mapSheetAnalEntity.detectingCnt, - labelingAssignmentEntity.workerUid.countDistinct(), - labelingAssignmentEntity.inspectorUid.countDistinct())) - .from(mapSheetAnalEntity) - .innerJoin(labelingAssignmentEntity) - .on(mapSheetAnalEntity.id.eq(labelingAssignmentEntity.analUid)) - .where(mapSheetAnalEntity.id.eq(analEntity.getId())) - .groupBy( - mapSheetAnalEntity.analTitle, - mapSheetAnalEntity.gukyuinApplyDttm, - mapSheetAnalEntity.detectingCnt) - .fetchOne(); + .select( + Projections.constructor( + InferenceDetail.class, + mapSheetAnalEntity.analTitle, + Expressions.numberTemplate(Integer.class, "{0}", 4), + mapSheetAnalEntity.gukyuinApplyDttm, + mapSheetAnalEntity.detectingCnt, + labelingAssignmentEntity.workerUid.countDistinct(), + labelingAssignmentEntity.inspectorUid.countDistinct())) + .from(mapSheetAnalEntity) + .innerJoin(labelingAssignmentEntity) + .on(mapSheetAnalEntity.id.eq(labelingAssignmentEntity.analUid)) + .where(mapSheetAnalEntity.id.eq(analEntity.getId())) + .groupBy( + mapSheetAnalEntity.analTitle, + mapSheetAnalEntity.gukyuinApplyDttm, + mapSheetAnalEntity.detectingCnt) + .fetchOne(); } @Override public List fetchNextMoveIds( - Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { + Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) { return queryFactory - .select(mapSheetAnalDataInferenceGeomEntity.geoUid) - .from(mapSheetAnalDataInferenceGeomEntity) - .where( - // mapSheetAnalDataGeomEntity.pnu.isNotNull(), //TODO: Mockup 진행 이후 확인하기 - lastId == null ? null : mapSheetAnalDataInferenceGeomEntity.geoUid.gt(lastId), - mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy), - mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy), - mapSheetAnalDataInferenceGeomEntity.stage.eq(stage), - mapSheetAnalDataInferenceGeomEntity.labelState.in( - LabelState.ASSIGNED.getId(), LabelState.SKIP.getId())) - .orderBy(mapSheetAnalDataInferenceGeomEntity.mapSheetNum.asc()) - .limit(batchSize) - .fetch(); + .select(mapSheetAnalDataInferenceGeomEntity.geoUid) + .from(mapSheetAnalDataInferenceGeomEntity) + .where( + // mapSheetAnalDataGeomEntity.pnu.isNotNull(), //TODO: Mockup 진행 이후 확인하기 + lastId == null ? null : mapSheetAnalDataInferenceGeomEntity.geoUid.gt(lastId), + mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy), + mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy), + mapSheetAnalDataInferenceGeomEntity.stage.eq(stage), + mapSheetAnalDataInferenceGeomEntity.labelState.in( + LabelState.ASSIGNED.getId(), LabelState.SKIP.getId())) + .orderBy(mapSheetAnalDataInferenceGeomEntity.mapSheetNum.asc()) + .limit(batchSize) + .fetch(); } @Transactional @Override public void assignOwnerMove(List sub, String userId) { queryFactory - .update(labelingAssignmentEntity) - .set(labelingAssignmentEntity.workerUid, userId) - .where(labelingAssignmentEntity.inferenceGeomUid.in(sub)) - .execute(); + .update(labelingAssignmentEntity) + .set(labelingAssignmentEntity.workerUid, userId) + .where(labelingAssignmentEntity.inferenceGeomUid.in(sub)) + .execute(); em.clear(); } @@ -497,43 +504,43 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto @Override public LabelerDetail findLabelerDetail(String userId, String uuid) { NumberExpression assignedCnt = - new CaseBuilder() - .when(labelingAssignmentEntity.workState.eq(LabelState.ASSIGNED.getId())) - .then(1L) - .otherwise((Long) null) - .count(); + new CaseBuilder() + .when(labelingAssignmentEntity.workState.eq(LabelState.ASSIGNED.getId())) + .then(1L) + .otherwise((Long) null) + .count(); NumberExpression skipCnt = - new CaseBuilder() - .when(labelingAssignmentEntity.workState.eq(LabelState.SKIP.getId())) - .then(1L) - .otherwise((Long) null) - .count(); + new CaseBuilder() + .when(labelingAssignmentEntity.workState.eq(LabelState.SKIP.getId())) + .then(1L) + .otherwise((Long) null) + .count(); NumberExpression completeCnt = - new CaseBuilder() - .when(labelingAssignmentEntity.workState.eq(LabelState.COMPLETE.getId())) - .then(1L) - .otherwise((Long) null) - .count(); + new CaseBuilder() + .when(labelingAssignmentEntity.workState.eq(LabelState.COMPLETE.getId())) + .then(1L) + .otherwise((Long) null) + .count(); NumberExpression percent = - new CaseBuilder() - .when(completeCnt.eq(0L)) - .then(0.0) - .otherwise( - Expressions.numberTemplate( - Double.class, - "round({0} / {1}, 2)", - labelingAssignmentEntity.count(), - completeCnt)); + new CaseBuilder() + .when(completeCnt.eq(0L)) + .then(0.0) + .otherwise( + Expressions.numberTemplate( + Double.class, + "round({0} / {1}, 2)", + labelingAssignmentEntity.count(), + completeCnt)); // analUid로 분석 정보 조회 MapSheetAnalInferenceEntity analEntity = - queryFactory - .selectFrom(mapSheetAnalInferenceEntity) - .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) - .fetchOne(); + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) + .fetchOne(); if (Objects.isNull(analEntity)) { throw new EntityNotFoundException("MapSheetAnalInferenceEntity not found for analUid: "); @@ -543,55 +550,339 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto QMemberEntity inspector = new QMemberEntity("inspector"); return queryFactory - .select( - Projections.constructor( - LabelerDetail.class, - worker.userRole, - worker.name, - worker.employeeNo, - assignedCnt, - skipCnt, - completeCnt, - percent, - Expressions.constant(0), // TODO: 순위, 꼭 해야할지? - labelingAssignmentEntity.createdDate.min(), - inspector.name.min())) - .from(worker) - .innerJoin(labelingAssignmentEntity) - .on( - worker.employeeNo.eq(labelingAssignmentEntity.workerUid), - labelingAssignmentEntity.analUid.eq(analEntity.getId())) - .leftJoin(inspector) - .on(labelingAssignmentEntity.inspectorUid.eq(inspector.employeeNo)) - .where(worker.employeeNo.eq(userId)) - .groupBy(worker.userRole, worker.name, worker.employeeNo) - .fetchOne(); + .select( + Projections.constructor( + LabelerDetail.class, + worker.userRole, + worker.name, + worker.employeeNo, + assignedCnt, + skipCnt, + completeCnt, + percent, + Expressions.constant(0), // TODO: 순위, 꼭 해야할지? + labelingAssignmentEntity.workStatDttm.min(), + inspector.name.min())) + .from(worker) + .innerJoin(labelingAssignmentEntity) + .on( + worker.employeeNo.eq(labelingAssignmentEntity.workerUid), + labelingAssignmentEntity.analUid.eq(analEntity.getId())) + .leftJoin(inspector) + .on(labelingAssignmentEntity.inspectorUid.eq(inspector.employeeNo)) + .where(worker.employeeNo.eq(userId)) + .groupBy(worker.userRole, worker.name, worker.employeeNo) + .fetchOne(); } @Override public Long findMapSheetAnalInferenceUid(Integer compareYyyy, Integer targetYyyy, Integer stage) { return queryFactory - .select(mapSheetAnalInferenceEntity.id) - .from(mapSheetAnalInferenceEntity) - .where( - mapSheetAnalInferenceEntity.compareYyyy.eq(compareYyyy), - mapSheetAnalInferenceEntity.targetYyyy.eq(targetYyyy), - mapSheetAnalInferenceEntity.stage.eq(stage)) - .fetchOne(); + .select(mapSheetAnalInferenceEntity.id) + .from(mapSheetAnalInferenceEntity) + .where( + mapSheetAnalInferenceEntity.compareYyyy.eq(compareYyyy), + mapSheetAnalInferenceEntity.targetYyyy.eq(targetYyyy), + mapSheetAnalInferenceEntity.stage.eq(stage)) + .fetchOne(); } @Override public void insertInspector(Long analUid, String inspector) { queryFactory - .insert(labelingInspectorEntity) - .columns( - labelingInspectorEntity.operatorUid, - labelingInspectorEntity.analUid, - labelingInspectorEntity.inspectorUid) - .values(UUID.randomUUID(), analUid, inspector) - .execute(); + .insert(labelingInspectorEntity) + .columns( + labelingInspectorEntity.operatorUid, + labelingInspectorEntity.analUid, + labelingInspectorEntity.inspectorUid) + .values(UUID.randomUUID(), analUid, inspector) + .execute(); em.flush(); em.clear(); } + + @Override + public Page findLabelerDailyStat(LabelAllocateDto.searchReq searchReq, String uuid, String userId) { + // 날짜 포맷 + Expression workDate = + Expressions.stringTemplate( + "TO_CHAR({0}, 'YYYY-MM-DD')", + labelingAssignmentEntity.workStatDttm + ); + + // 날짜별 전체 건수 + Expression dailyTotalCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*)" + ); + + // ⭐ 전체 기간 총 건수 (윈도우 함수) + Expression totalCnt = + Expressions.numberTemplate( + Long.class, + "SUM(COUNT(*)) OVER ()" + ); + + // 상태별 카운트 (Postgres FILTER 사용) + Expression assignedCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*) FILTER (WHERE {0} = 'ASSIGNED')", + labelingAssignmentEntity.workState + ); + + Expression skipCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*) FILTER (WHERE {0} = 'SKIP')", + labelingAssignmentEntity.workState + ); + + Expression completeCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*) FILTER (WHERE {0} = 'COMPLETE')", + labelingAssignmentEntity.workState + ); + + Expression remainCnt = + Expressions.numberTemplate( + Long.class, + "({0} - {1} - {2})", + totalCnt, + skipCnt, + completeCnt + ); + + // analUid로 분석 정보 조회 + MapSheetAnalInferenceEntity analEntity = + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) + .fetchOne(); + + if (Objects.isNull(analEntity)) { + throw new EntityNotFoundException("MapSheetAnalInferenceEntity not found for analUid: "); + } + + Pageable pageable = searchReq.toPageable(); + List foundContent = queryFactory + .select( + Projections.constructor( + LabelingStatDto.class, + workDate, + dailyTotalCnt, + totalCnt, // ⭐ 전체 일자 배정 건수 + assignedCnt, + skipCnt, + completeCnt, + remainCnt + ) + ) + .from(labelingAssignmentEntity) + .where( + labelingAssignmentEntity.workerUid.eq(userId), + labelingAssignmentEntity.analUid.eq(analEntity.getId()) + ) + .groupBy(workDate) + .orderBy(labelingAssignmentEntity.workStatDttm.min().asc()) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .fetch(); + + Long countQuery = queryFactory + .select(workDate) + .from(labelingAssignmentEntity) + .where( + labelingAssignmentEntity.workerUid.eq(userId), + labelingAssignmentEntity.analUid.eq(analEntity.getId()) + ) + .distinct() + .fetch() + .stream() + .count(); + + return new PageImpl<>(foundContent, pageable, countQuery); + } + + @Override + public Page findInspectorDailyStat(searchReq searchReq, String uuid, String userId) { + // 날짜 포맷 + Expression workDate = + Expressions.stringTemplate( + "TO_CHAR({0}, 'YYYY-MM-DD')", + labelingAssignmentEntity.inspectStatDttm + ); + + // 날짜별 전체 건수 + Expression dailyTotalCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*)" + ); + + // ⭐ 전체 기간 총 건수 (윈도우 함수) + Expression totalCnt = + Expressions.numberTemplate( + Long.class, + "SUM(COUNT(*)) OVER ()" + ); + + // 상태별 카운트 (Postgres FILTER 사용) + Expression assignedCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*) FILTER (WHERE {0} = 'UNCONFIRM')", + labelingAssignmentEntity.inspectState + ); + + Expression skipCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*) FILTER (WHERE {0} = 'EXCEPT')", + labelingAssignmentEntity.inspectState + ); + + Expression completeCnt = + Expressions.numberTemplate( + Long.class, + "COUNT(*) FILTER (WHERE {0} = 'COMPLETE')", + labelingAssignmentEntity.inspectState + ); + + Expression remainCnt = + Expressions.numberTemplate( + Long.class, + "({0} - {1} - {2})", + totalCnt, + skipCnt, + completeCnt + ); + + // analUid로 분석 정보 조회 + MapSheetAnalInferenceEntity analEntity = + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) + .fetchOne(); + + if (Objects.isNull(analEntity)) { + throw new EntityNotFoundException("MapSheetAnalInferenceEntity not found for analUid: "); + } + + Pageable pageable = searchReq.toPageable(); + List foundContent = queryFactory + .select( + Projections.constructor( + LabelingStatDto.class, + workDate, + dailyTotalCnt, + totalCnt, // ⭐ 전체 일자 배정 건수 + assignedCnt, + skipCnt, + completeCnt, + remainCnt + ) + ) + .from(labelingAssignmentEntity) + .where( + labelingAssignmentEntity.inspectorUid.eq(userId), + labelingAssignmentEntity.analUid.eq(analEntity.getId()) + ) + .groupBy(workDate) + .orderBy(labelingAssignmentEntity.inspectStatDttm.min().asc()) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .fetch(); + + Long countQuery = queryFactory + .select(workDate) + .from(labelingAssignmentEntity) + .where( + labelingAssignmentEntity.inspectorUid.eq(userId), + labelingAssignmentEntity.analUid.eq(analEntity.getId()) + ) + .distinct() + .fetch() + .stream() + .count(); + + return new PageImpl<>(foundContent, pageable, countQuery); + } + + @Override + public LabelerDetail findInspectorDetail(String userId, String uuid) { + NumberExpression assignedCnt = + new CaseBuilder() + .when(labelingAssignmentEntity.inspectState.eq(InspectState.UNCONFIRM.getId())) + .then(1L) + .otherwise((Long) null) + .count(); + + NumberExpression skipCnt = + new CaseBuilder() + .when(labelingAssignmentEntity.inspectState.eq(InspectState.EXCEPT.getId())) + .then(1L) + .otherwise((Long) null) + .count(); + + NumberExpression completeCnt = + new CaseBuilder() + .when(labelingAssignmentEntity.inspectState.eq(InspectState.COMPLETE.getId())) + .then(1L) + .otherwise((Long) null) + .count(); + + NumberExpression percent = + new CaseBuilder() + .when(completeCnt.eq(0L)) + .then(0.0) + .otherwise( + Expressions.numberTemplate( + Double.class, + "round({0} / {1}, 2)", + labelingAssignmentEntity.count(), + completeCnt)); + + // analUid로 분석 정보 조회 + MapSheetAnalInferenceEntity analEntity = + queryFactory + .selectFrom(mapSheetAnalInferenceEntity) + .where(mapSheetAnalInferenceEntity.uuid.eq(UUID.fromString(uuid))) + .fetchOne(); + + if (Objects.isNull(analEntity)) { + throw new EntityNotFoundException("MapSheetAnalInferenceEntity not found for analUid: "); + } + + QMemberEntity inspector = QMemberEntity.memberEntity; + QMemberEntity worker = new QMemberEntity("worker"); + + return queryFactory + .select( + Projections.constructor( + LabelerDetail.class, + inspector.userRole, + inspector.name, + inspector.employeeNo, + assignedCnt, + skipCnt, + completeCnt, + percent, + Expressions.constant(0), // TODO: 순위, 꼭 해야할지? + labelingAssignmentEntity.inspectStatDttm.min(), + worker.name.min())) + .from(inspector) + .innerJoin(labelingAssignmentEntity) + .on( + inspector.employeeNo.eq(labelingAssignmentEntity.inspectorUid), + labelingAssignmentEntity.analUid.eq(analEntity.getId())) + .leftJoin(worker) + .on(labelingAssignmentEntity.workerUid.eq(worker.employeeNo)) + .where(inspector.employeeNo.eq(userId)) + .groupBy(inspector.userRole, inspector.name, inspector.employeeNo) + .fetchOne(); + } }