Merge pull request 'feat/dev_251201' (#133) from feat/dev_251201 into develop

Reviewed-on: https://kamco.gitea.gs.dabeeo.com/dabeeo/kamco-dabeeo-backoffice/pulls/133
This commit is contained in:
2026-01-02 22:18:33 +09:00
13 changed files with 859 additions and 251 deletions

View File

@@ -1,9 +1,10 @@
package com.kamco.cd.kamcoback.label;
import com.kamco.cd.kamcoback.code.dto.CommonCodeDto;
import com.kamco.cd.kamcoback.common.enums.RoleType;
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.WorkerStatsDto.WorkerListResponse;
import com.kamco.cd.kamcoback.label.service.LabelAllocateService;
import io.swagger.v3.oas.annotations.Operation;
@@ -36,185 +37,27 @@ public class LabelAllocateApiController {
@Operation(summary = "배정 가능한 사용자 목록 조회", description = "라벨링 작업 배정을 위한 활성 상태의 사용자 목록을 조회합니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = CommonCodeDto.Basic.class),
examples =
@ExampleObject(
name = "사용자 목록 응답",
value =
"""
{
"data": [
{
"userRole": "LABELER",
"employeeNo": "1234567",
"name": "김라벨"
},
{
"userRole": "LABELER",
"employeeNo": "2345678",
"name": "이작업"
}
]
}
"""))),
@ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
@ApiResponse(responseCode = "200", description = "조회 성공"),
@ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@GetMapping("/avail-user")
public ApiResponseDto<List<LabelAllocateDto.UserList>> availUserList(
@Parameter(description = "사용자 역할 (LABELER: 라벨러, REVIEWER: 검수자)", example = "LABELER")
@Parameter(
description = "사용자 역할",
example = "LABELER",
schema = @Schema(allowableValues = {"LABELER", "REVIEWER"}))
@RequestParam
@Schema()
String role) {
return ApiResponseDto.ok(labelAllocateService.availUserList(role));
}
@Operation(
summary = "작업자 목록 및 3일치 통계 조회",
description = """
학습데이터 제작 현황 조회 API입니다.
""")
@Operation(summary = "작업현황관리(작업자 목록 및 3일치 통계 조회)", description = "학습데이터 제작 현황 조회 API입니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = WorkerListResponse.class),
examples = {
@ExampleObject(
name = "라벨러 조회 예시",
description = "라벨러 작업자들의 통계 정보",
value =
"""
{
"data": {
"progressInfo": {
"labelingProgressRate": 79.34,
"workStatus": "진행중",
"completedCount": 6554,
"totalAssignedCount": 8258,
"labelerCount": 5,
"remainingLabelCount": 1704,
"inspectorCount": 3,
"remainingInspectCount": 890
},
"workers": [
{
"workerId": "1234567",
"workerName": "김라벨",
"workerType": "LABELER",
"totalAssigned": 1500,
"completed": 1100,
"skipped": 50,
"remaining": 350,
"history": {
"day1Ago": 281,
"day2Ago": 302,
"day3Ago": 294,
"average": 292
},
"isStagnated": false
},
{
"workerId": "2345678",
"workerName": "이작업",
"workerType": "LABELER",
"totalAssigned": 2000,
"completed": 1850,
"skipped": 100,
"remaining": 50,
"history": {
"day1Ago": 5,
"day2Ago": 3,
"day3Ago": 8,
"average": 5
},
"isStagnated": true
}
]
}
}
"""),
@ExampleObject(
name = "검수자 조회 예시",
description = "검수자 작업자들의 통계 정보",
value =
"""
{
"data": {
"progressInfo": {
"labelingProgressRate": 79.34,
"workStatus": "진행중",
"completedCount": 6554,
"totalAssignedCount": 8258,
"labelerCount": 5,
"remainingLabelCount": 1704,
"inspectorCount": 3,
"remainingInspectCount": 890
},
"workers": [
{
"workerId": "9876543",
"workerName": "박검수",
"workerType": "REVIEWER",
"totalAssigned": 1200,
"completed": 980,
"skipped": 20,
"remaining": 200,
"history": {
"day1Ago": 150,
"day2Ago": 145,
"day3Ago": 155,
"average": 150
},
"isStagnated": false
}
]
}
}
""")
})),
@ApiResponse(
responseCode = "404",
description = "데이터를 찾을 수 없음",
content =
@Content(
examples =
@ExampleObject(
value =
"""
{
"error": {
"code": "NOT_FOUND",
"message": "해당 분석 ID의 데이터를 찾을 수 없습니다."
}
}
"""))),
@ApiResponse(
responseCode = "500",
description = "서버 오류",
content =
@Content(
examples =
@ExampleObject(
value =
"""
{
"error": {
"code": "INTERNAL_SERVER_ERROR",
"message": "서버에 문제가 발생 하였습니다."
}
}
""")))
@ApiResponse(responseCode = "200", description = "조회 성공"),
@ApiResponse(responseCode = "404", description = "데이터를 찾을 수 없음"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@GetMapping("/admin/workers")
public ApiResponseDto<WorkerListResponse> getWorkerStatistics(
@@ -249,14 +92,15 @@ public class LabelAllocateApiController {
@RequestParam(required = false)
String sort) {
// type이 null이면 전체 조회 (일단 LABELER로 기본 설정)
String workerType = (type == null || type.isEmpty()) ? "LABELER" : type;
// type이 null이면 기본값으로 LABELER 설정
String workerType = (type == null || type.isEmpty()) ? RoleType.LABELER.name() : type;
return ApiResponseDto.ok(
labelAllocateService.getWorkerStatistics(
analUid, workerType, searchName, searchEmployeeNo, sort));
}
@Operation(summary = "작업 배정", description = "작업 배정")
@ApiResponses(
value = {
@ApiResponse(
@@ -265,32 +109,151 @@ public class LabelAllocateApiController {
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = Long.class))),
schema = @Schema(implementation = Long.class),
examples = {
@ExampleObject(
name = "라벨러 할당 예시",
description = "라벨러 할당 예시",
value =
"""
{
"autoType": "AUTO",
"stage": 4,
"labelers": [
{
"userId": "123456",
"demand": 1000
},
{
"userId": "010222297501",
"demand": 400
},
{
"userId": "01022223333",
"demand": 440
}
],
"inspectors": [
{
"inspectorUid": "K20251216001",
"userCount": 1000
},
{
"inspectorUid": "01022225555",
"userCount": 340
},
{
"inspectorUid": "K20251212001",
"userCount": 500
}
]
}
""")
})),
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
@ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@PostMapping("/allocate")
public ApiResponseDto<Void> labelAllocate(
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "라벨링 수량 할당",
required = true,
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = LabelAllocateDto.AllocateDto.class)))
@RequestBody
LabelAllocateDto.AllocateDto dto)
throws Exception {
public ApiResponseDto<Void> labelAllocate(@RequestBody LabelAllocateDto.AllocateDto dto) {
labelAllocateService.allocateAsc(
dto.getAutoType(), dto.getStage(), dto.getLabelers(), dto.getInspectors());
dto.getAutoType(),
dto.getStage(),
dto.getLabelers(),
dto.getInspectors(),
dto.getCompareYyyy(),
dto.getTargetYyyy());
return ApiResponseDto.ok(null);
}
@GetMapping
public ApiResponseDto<InferenceDetail> findInferenceDetail(@RequestParam Long analUid) {
return ApiResponseDto.ok(labelAllocateService.findInferenceDetail(analUid));
@Operation(summary = "추론 상세 조회", description = "분석 ID에 해당하는 추론 상세 정보를 조회합니다.")
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "조회 성공"),
@ApiResponse(responseCode = "404", description = "데이터를 찾을 수 없음"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@GetMapping("/stage-detail")
public ApiResponseDto<InferenceDetail> findInferenceDetail(
@Parameter(description = "비교년도", required = true, example = "2022") @RequestParam
Integer compareYyyy,
@Parameter(description = "기준년도", required = true, example = "2024") @RequestParam
Integer targetYyyy,
@Parameter(description = "회차", required = true, example = "4") @RequestParam Integer stage) {
return ApiResponseDto.ok(
labelAllocateService.findInferenceDetail(compareYyyy, targetYyyy, stage));
}
@Operation(summary = "작업이관 > 라벨러 상세 정보", description = "작업이관 > 라벨러 상세 정보")
@GetMapping("/labeler-detail")
public ApiResponseDto<LabelerDetail> findLabelerDetail(
@RequestParam(defaultValue = "01022223333") String userId,
@Parameter(description = "비교년도", required = true, example = "2022") @RequestParam
Integer compareYyyy,
@Parameter(description = "기준년도", required = true, example = "2024") @RequestParam
Integer targetYyyy,
@Parameter(description = "회차", required = true, example = "4") @RequestParam Integer stage) {
return ApiResponseDto.ok(
labelAllocateService.findLabelerDetail(userId, compareYyyy, targetYyyy, stage));
}
@Operation(summary = "작업 이관", description = "작업 이관")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "201",
description = "등록 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = Long.class),
examples = {
@ExampleObject(
name = "라벨러 할당 예시",
description = "라벨러 할당 예시",
value =
"""
{
"autoType": "AUTO",
"stage": 4,
"labelers": [
{
"userId": "123456",
"demand": 10
},
{
"userId": "010222297501",
"demand": 5
}
]
}
""")
})),
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
@ApiResponse(responseCode = "404", description = "코드를 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@PostMapping("/allocate-move")
public ApiResponseDto<Void> 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) {
labelAllocateService.allocateMove(
dto.getAutoType(),
dto.getStage(),
dto.getLabelers(),
dto.getCompareYyyy(),
dto.getTargetYyyy());
return ApiResponseDto.ok(null);
}
}

View File

@@ -0,0 +1,50 @@
package com.kamco.cd.kamcoback.label;
import com.kamco.cd.kamcoback.code.dto.CommonCodeDto;
import com.kamco.cd.kamcoback.config.api.ApiResponseDto;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto.LabelWorkMng;
import com.kamco.cd.kamcoback.label.service.LabelWorkService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@Tag(name = "라벨링 작업 관리", description = "라벨링 작업 관리")
@RequestMapping({"/api/label"})
@RequiredArgsConstructor
@RestController
public class LabelWorkerApiController {
private final LabelWorkService labelWorkService;
@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)
})
@PostMapping("/label-work-mng-list")
public ApiResponseDto<Page<LabelWorkMng>> labelWorkMngList(
@RequestBody @Valid LabelWorkDto.LabelWorkMngSearchReq searchReq) {
return ApiResponseDto.ok(labelWorkService.labelWorkMngList(searchReq));
}
}

View File

@@ -42,8 +42,10 @@ public class LabelAllocateDto {
@Getter
@AllArgsConstructor
public enum LabelState implements EnumType {
WAIT("대기"),
ASSIGNED("배정"),
SKIP("스킵"),
DONE("완료"),
COMPLETE("완료");
private String desc;
@@ -85,6 +87,15 @@ public class LabelAllocateDto {
@AllArgsConstructor
public static class AllocateDto {
@Schema(description = "분석 ID", example = "3")
private Long analUid;
@Schema(description = "비교년도", example = "2022", required = true)
private Integer compareYyyy;
@Schema(description = "기준년도", example = "2024", required = true)
private Integer targetYyyy;
@Schema(description = "자동/수동여부(AUTO/MANUAL)", example = "AUTO")
private String autoType;
@@ -164,4 +175,39 @@ public class LabelAllocateDto {
private Long labelCnt;
private Long inspectorCnt;
}
@Getter
@Setter
@AllArgsConstructor
public static class LabelerDetail {
private String roleType;
private String name;
private String userId; // 사번
private Long count;
private Long completeCnt;
private Long skipCnt;
private Double percent;
}
@Getter
@Setter
@AllArgsConstructor
public static class AllocateMoveDto {
@Schema(description = "자동/수동여부(AUTO/MANUAL)", example = "AUTO")
private String autoType;
@Schema(description = "회차", example = "4")
private Integer stage;
@Schema(description = "라벨러 할당 목록")
private List<TargetUser> labelers;
@Schema(description = "비교년도", example = "2022")
private Integer compareYyyy;
@Schema(description = "기준년도", example = "2024")
private Integer targetYyyy;
}
}

View File

@@ -0,0 +1,92 @@
package com.kamco.cd.kamcoback.label.dto;
import com.kamco.cd.kamcoback.common.utils.enums.Enums;
import com.kamco.cd.kamcoback.common.utils.interfaces.JsonFormatDttm;
import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.LabelMngState;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.ZonedDateTime;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
public class LabelWorkDto {
@Schema(name = "LabelWorkMng", description = "라벨작업관리")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class LabelWorkMng {
private int compareYyyy;
private int targetYyyy;
private int stage;
@JsonFormatDttm private ZonedDateTime createdDttm;
private Long detectionTotCnt;
private Long labelTotCnt;
private Long labelStopTotCnt;
private Long labelIngTotCnt;
private Long labelCompleteTotCnt;
@JsonFormatDttm private ZonedDateTime labelStartDttm;
public String getLabelState() {
String mngState = "PENDING";
if (this.labelTotCnt == 0) mngState = "PENDING";
else if (this.labelIngTotCnt > 0) mngState = "LABEL_ING";
else if (this.labelTotCnt <= labelCompleteTotCnt) mngState = "LABEL_COMPLETE";
return mngState;
}
public String getLabelStateName() {
String enumId = this.getLabelState();
if (enumId == null || enumId.isEmpty()) {
enumId = "PENDING";
}
LabelMngState type = Enums.fromId(LabelMngState.class, enumId);
return type.getText();
}
public double getLabelRate() {
if (this.labelTotCnt == null || this.labelCompleteTotCnt == 0) {
return 0.0;
}
return (double) this.labelTotCnt / this.labelCompleteTotCnt * 100.0;
}
}
@Schema(name = "LabelWorkMngSearchReq", description = "라벨작업관리 검색 요청")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class LabelWorkMngSearchReq {
// 페이징 파라미터
@Schema(description = "페이지 번호 (0부터 시작) ", example = "0")
private int page = 0;
@Schema(description = "페이지 크기", example = "20")
private int size = 20;
@Schema(description = "변화탐지년도", example = "2024")
private Integer detectYyyy;
@Schema(description = "시작일", example = "20240101")
private String strtDttm;
@Schema(description = "종료일", example = "20241201")
private String endDttm;
public Pageable toPageable() {
return PageRequest.of(page, size);
}
}
}

View File

@@ -2,6 +2,7 @@ package com.kamco.cd.kamcoback.label.service;
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.TargetInspector;
import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.TargetUser;
import com.kamco.cd.kamcoback.label.dto.LabelAllocateDto.UserList;
@@ -18,9 +19,12 @@ import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@Transactional(readOnly = true)
@Transactional
public class LabelAllocateService {
private static final int STAGNATION_THRESHOLD = 10; // 정체 판단 기준 (3일 평균 처리량)
private static final int BATCH_SIZE = 100; // 배정 배치 크기
private final LabelAllocateCoreService labelAllocateCoreService;
public LabelAllocateService(LabelAllocateCoreService labelAllocateCoreService) {
@@ -30,19 +34,24 @@ public class LabelAllocateService {
/**
* 도엽 기준 asc sorting 해서 할당 수만큼 배정하는 로직
*
* @param targetUsers
* @param autoType 자동/수동 배정 타입
* @param stage 회차
* @param targetUsers 라벨러 목록
* @param targetInspectors 검수자 목록
*/
@Transactional
public void allocateAsc(
String autoType,
Integer stage,
List<TargetUser> targetUsers,
List<TargetInspector> targetInspectors)
throws Exception {
List<TargetInspector> targetInspectors,
Integer compareYyyy,
Integer targetYyyy) {
Long lastId = null;
// geom 잔여건수 != 프론트에서 넘어 온 총 건수 -> return
Long chargeCnt = labelAllocateCoreService.findLabelUnAssignedCnt(3L); // TODO
// geom 잔여건수 조회
Long chargeCnt =
labelAllocateCoreService.findLabelUnAssignedCnt(stage, compareYyyy, targetYyyy);
// Long totalDemand = targetUsers.stream().mapToLong(TargetUser::getDemand).sum();
// if (!Objects.equals(chargeCnt, totalDemand)) {
// log.info("chargeCnt != totalDemand");
@@ -53,18 +62,20 @@ public class LabelAllocateService {
return;
}
List<Long> allIds = labelAllocateCoreService.fetchNextIds(lastId, chargeCnt);
List<Long> allIds =
labelAllocateCoreService.fetchNextIds(lastId, chargeCnt, compareYyyy, targetYyyy, stage);
int index = 0;
for (TargetUser target : targetUsers) {
int end = index + target.getDemand();
List<Long> sub = allIds.subList(index, end);
labelAllocateCoreService.assignOwner(sub, target.getUserId());
labelAllocateCoreService.assignOwner(sub, target.getUserId(), compareYyyy, targetYyyy, stage);
index = end;
}
// 검수자에게 userCount명 만큼 할당
List<LabelAllocateDto.Basic> list = labelAllocateCoreService.findAssignedLabelerList(3L);
List<LabelAllocateDto.Basic> list =
labelAllocateCoreService.findAssignedLabelerList(compareYyyy, targetYyyy, stage);
int from = 0;
for (TargetInspector inspector : targetInspectors) {
@@ -137,8 +148,8 @@ public class LabelAllocateService {
worker.setHistory(history);
// 정체 여부 판단 (3일 평균이 특정 기준 미만일 때 - 예: 10건 미만)
if (average < 10) {
// 정체 여부 판단 (3일 평균이 STAGNATION_THRESHOLD 미만일 때)
if (average < STAGNATION_THRESHOLD) {
worker.setIsStagnated(true);
}
}
@@ -146,7 +157,40 @@ public class LabelAllocateService {
return WorkerListResponse.builder().progressInfo(progressInfo).workers(workers).build();
}
public InferenceDetail findInferenceDetail(Long analUid) {
return labelAllocateCoreService.findInferenceDetail(analUid);
public InferenceDetail findInferenceDetail(
Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateCoreService.findInferenceDetail(compareYyyy, targetYyyy, stage);
}
public void allocateMove(
String autoType,
Integer stage,
List<TargetUser> targetUsers,
Integer compareYyyy,
Integer targetYyyy) {
Long lastId = null;
Long chargeCnt = targetUsers.stream().mapToLong(TargetUser::getDemand).sum();
if (chargeCnt <= 0) {
return;
}
List<Long> allIds =
labelAllocateCoreService.fetchNextMoveIds(
lastId, chargeCnt, compareYyyy, targetYyyy, stage);
int index = 0;
for (TargetUser target : targetUsers) {
int end = index + target.getDemand();
List<Long> sub = allIds.subList(index, end);
labelAllocateCoreService.assignOwnerMove(sub, target.getUserId());
index = end;
}
}
public LabelerDetail findLabelerDetail(
String userId, Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateCoreService.findLabelerDetail(userId, compareYyyy, targetYyyy, stage);
}
}

View File

@@ -0,0 +1,24 @@
package com.kamco.cd.kamcoback.label.service;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto.LabelWorkMng;
import com.kamco.cd.kamcoback.postgres.core.LabelWorkCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class LabelWorkService {
private final LabelWorkCoreService labelWorkCoreService;
public LabelWorkService(LabelWorkCoreService labelWorkCoreService) {
this.labelWorkCoreService = labelWorkCoreService;
}
public Page<LabelWorkMng> labelWorkMngList(LabelWorkDto.LabelWorkMngSearchReq searchReq) {
return labelWorkCoreService.labelWorkMngList(searchReq);
}
}

View File

@@ -2,6 +2,7 @@ package com.kamco.cd.kamcoback.postgres.core;
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.UserList;
import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkProgressInfo;
import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkerStatistics;
@@ -19,22 +20,25 @@ public class LabelAllocateCoreService {
private final LabelAllocateRepository labelAllocateRepository;
public List<Long> fetchNextIds(Long lastId, Long batchSize) {
return labelAllocateRepository.fetchNextIds(lastId, batchSize);
public List<Long> fetchNextIds(
Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateRepository.fetchNextIds(lastId, batchSize, compareYyyy, targetYyyy, stage);
}
public void assignOwner(List<Long> ids, String userId) {
labelAllocateRepository.assignOwner(ids, userId);
public void assignOwner(
List<Long> ids, String userId, Integer compareYyyy, Integer targetYyyy, Integer stage) {
labelAllocateRepository.assignOwner(ids, userId, compareYyyy, targetYyyy, stage);
}
public List<LabelAllocateDto.Basic> findAssignedLabelerList(Long analUid) {
return labelAllocateRepository.findAssignedLabelerList(analUid).stream()
public List<LabelAllocateDto.Basic> findAssignedLabelerList(
Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateRepository.findAssignedLabelerList(compareYyyy, targetYyyy, stage).stream()
.map(LabelingAssignmentEntity::toDto)
.toList();
}
public Long findLabelUnAssignedCnt(Long analUid) {
return labelAllocateRepository.findLabelUnAssignedCnt(analUid);
public Long findLabelUnAssignedCnt(Integer stage, Integer compareYyyy, Integer targetYyyy) {
return labelAllocateRepository.findLabelUnAssignedCnt(stage, compareYyyy, targetYyyy);
}
public void assignInspector(UUID assignmentUid, String inspectorUid) {
@@ -68,7 +72,27 @@ public class LabelAllocateCoreService {
labelAllocateRepository.assignInspectorBulk(assignmentUids, inspectorUid);
}
public InferenceDetail findInferenceDetail(Long analUid) {
return labelAllocateRepository.findInferenceDetail(analUid);
public InferenceDetail findInferenceDetail(
Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateRepository.findInferenceDetail(compareYyyy, targetYyyy, stage);
}
public Long findLabelUnCompleteCnt(Long analUid) {
return labelAllocateRepository.findLabelUnCompleteCnt(analUid);
}
public List<Long> fetchNextMoveIds(
Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateRepository.fetchNextMoveIds(
lastId, batchSize, compareYyyy, targetYyyy, stage);
}
public void assignOwnerMove(List<Long> sub, String userId) {
labelAllocateRepository.assignOwnerMove(sub, userId);
}
public LabelerDetail findLabelerDetail(
String userId, Integer compareYyyy, Integer targetYyyy, Integer stage) {
return labelAllocateRepository.findLabelerDetail(userId, compareYyyy, targetYyyy, stage);
}
}

View File

@@ -0,0 +1,19 @@
package com.kamco.cd.kamcoback.postgres.core;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto.LabelWorkMng;
import com.kamco.cd.kamcoback.postgres.repository.label.LabelWorkRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class LabelWorkCoreService {
private final LabelWorkRepository labelWorkRepository;
public Page<LabelWorkMng> labelWorkMngList(LabelWorkDto.LabelWorkMngSearchReq searchReq) {
return labelWorkRepository.labelWorkMngList(searchReq);
}
}

View File

@@ -1,6 +1,7 @@
package com.kamco.cd.kamcoback.postgres.repository.label;
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.UserList;
import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkProgressInfo;
import com.kamco.cd.kamcoback.label.dto.WorkerStatsDto.WorkerStatistics;
@@ -11,13 +12,16 @@ import java.util.UUID;
public interface LabelAllocateRepositoryCustom {
List<Long> fetchNextIds(Long lastId, Long batchSize);
List<Long> fetchNextIds(
Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage);
void assignOwner(List<Long> ids, String userId);
void assignOwner(
List<Long> ids, String userId, Integer compareYyyy, Integer targetYyyy, Integer stage);
List<LabelingAssignmentEntity> findAssignedLabelerList(Long analUid);
List<LabelingAssignmentEntity> findAssignedLabelerList(
Integer compareYyyy, Integer targetYyyy, Integer stage);
Long findLabelUnAssignedCnt(Long analUid);
Long findLabelUnAssignedCnt(Integer stage, Integer compareYyyy, Integer targetYyyy);
void assignInspector(UUID assignmentUid, String userId);
@@ -35,5 +39,15 @@ public interface LabelAllocateRepositoryCustom {
void assignInspectorBulk(List<UUID> assignmentUids, String inspectorUid);
InferenceDetail findInferenceDetail(Long analUid);
InferenceDetail findInferenceDetail(Integer compareYyyy, Integer targetYyyy, Integer stage);
public List<Long> fetchNextMoveIds(
Long lastId, Long batchSize, Integer compareYyyy, Integer targetYyyy, Integer stage);
Long findLabelUnCompleteCnt(Long analUid);
void assignOwnerMove(List<Long> sub, String userId);
LabelerDetail findLabelerDetail(
String userId, Integer compareYyyy, Integer targetYyyy, Integer stage);
}

View File

@@ -1,17 +1,21 @@
package com.kamco.cd.kamcoback.postgres.repository.label;
import static com.kamco.cd.kamcoback.postgres.entity.QLabelingAssignmentEntity.labelingAssignmentEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetAnalDataInferenceEntity.mapSheetAnalDataInferenceEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetAnalDataInferenceGeomEntity.mapSheetAnalDataInferenceGeomEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetAnalEntity.mapSheetAnalEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMemberEntity.memberEntity;
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.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.UserList;
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.MapSheetAnalDataInferenceEntity;
import com.kamco.cd.kamcoback.postgres.entity.MapSheetAnalEntity;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
@@ -23,6 +27,7 @@ import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
@@ -44,16 +49,17 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
@PersistenceContext private EntityManager em;
@Override
public List<Long> fetchNextIds(Long lastId, Long batchSize) {
public List<Long> fetchNextIds(
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(2022),
mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(2024),
mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy),
mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy),
mapSheetAnalDataInferenceGeomEntity.stage.eq(stage),
mapSheetAnalDataInferenceGeomEntity.labelState.isNull())
.orderBy(mapSheetAnalDataInferenceGeomEntity.mapSheetNum.asc())
.limit(batchSize)
@@ -61,24 +67,43 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
}
@Override
public void assignOwner(List<Long> ids, String userId) {
public void assignOwner(
List<Long> ids, String userId, Integer compareYyyy, Integer targetYyyy, Integer stage) {
// analUid로 분석 정보 조회
MapSheetAnalDataInferenceEntity analEntity =
queryFactory
.selectFrom(mapSheetAnalDataInferenceEntity)
.where(
mapSheetAnalDataInferenceEntity.compareYyyy.eq(compareYyyy),
mapSheetAnalDataInferenceEntity.targetYyyy.eq(targetYyyy),
mapSheetAnalDataInferenceEntity.stage.eq(stage))
.orderBy(mapSheetAnalDataInferenceEntity.analUid.asc())
.limit(1)
.fetchOne();
if (Objects.isNull(analEntity)) {
throw new EntityNotFoundException("MapSheetAnalEntity not found for analUid: ");
}
// data_geom 테이블에 label state 를 ASSIGNED 로 update
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(ids))
.execute();
// 라벨러 할당 테이블에 insert
String sql =
"""
insert into tb_labeling_assignment
(assignment_uid, inference_geom_uid, worker_uid,
work_state, assign_group_id, anal_uid)
values (?, ?, ?, ?, ?, ?)
""";
insert into tb_labeling_assignment
(assignment_uid, inference_geom_uid, worker_uid,
work_state, assign_group_id, anal_uid)
values (?, ?, ?, ?, ?, ?)
""";
for (Long geoUid : ids) {
em.createNativeQuery(sql)
@@ -87,7 +112,7 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
.setParameter(3, userId)
.setParameter(4, LabelState.ASSIGNED.getId())
.setParameter(5, "")
.setParameter(6, 3)
.setParameter(6, analEntity.getAnalUid())
.executeUpdate();
}
@@ -96,11 +121,28 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
}
@Override
public List<LabelingAssignmentEntity> findAssignedLabelerList(Long analUid) {
public List<LabelingAssignmentEntity> findAssignedLabelerList(
Integer compareYyyy, Integer targetYyyy, Integer stage) {
// analUid로 분석 정보 조회
MapSheetAnalDataInferenceEntity analEntity =
queryFactory
.selectFrom(mapSheetAnalDataInferenceEntity)
.where(
mapSheetAnalDataInferenceEntity.compareYyyy.eq(compareYyyy),
mapSheetAnalDataInferenceEntity.targetYyyy.eq(targetYyyy),
mapSheetAnalDataInferenceEntity.stage.eq(stage))
.orderBy(mapSheetAnalDataInferenceEntity.analUid.asc())
.limit(1)
.fetchOne();
if (Objects.isNull(analEntity)) {
throw new EntityNotFoundException("MapSheetAnalEntity not found for analUid: ");
}
return queryFactory
.selectFrom(labelingAssignmentEntity)
.where(
labelingAssignmentEntity.analUid.eq(analUid),
labelingAssignmentEntity.analUid.eq(analEntity.getAnalUid()),
labelingAssignmentEntity.workState.eq(LabelState.ASSIGNED.getId()),
labelingAssignmentEntity.inspectorUid.isNull())
.orderBy(labelingAssignmentEntity.workerUid.asc())
@@ -108,24 +150,15 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
}
@Override
public Long findLabelUnAssignedCnt(Long analUid) {
MapSheetAnalEntity entity =
queryFactory
.selectFrom(mapSheetAnalEntity)
.where(mapSheetAnalEntity.id.eq(analUid))
.fetchOne();
if (Objects.isNull(entity)) {
throw new EntityNotFoundException();
}
public Long findLabelUnAssignedCnt(Integer stage, Integer compareYyyy, Integer targetYyyy) {
return queryFactory
.select(mapSheetAnalDataInferenceGeomEntity.geoUid.count())
.from(mapSheetAnalDataInferenceGeomEntity)
.where(
mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(entity.getCompareYyyy()),
mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(entity.getTargetYyyy()),
mapSheetAnalDataInferenceGeomEntity.stage.eq(4), // TODO: 회차 컬럼을 가져와야 할 듯?
mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(compareYyyy),
mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(targetYyyy),
mapSheetAnalDataInferenceGeomEntity.stage.eq(stage),
mapSheetAnalDataInferenceGeomEntity.labelState.isNull())
.fetchOne();
}
@@ -149,7 +182,9 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
memberEntity.employeeNo,
memberEntity.name))
.from(memberEntity)
.where(memberEntity.userRole.eq(role), memberEntity.status.eq("ACTIVE"))
.where(
memberEntity.userRole.eq(role),
memberEntity.status.eq(com.kamco.cd.kamcoback.common.enums.StatusType.ACTIVE.getId()))
.orderBy(memberEntity.name.asc())
.fetch();
}
@@ -164,12 +199,12 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
// 작업자 유형에 따른 필드 선택
StringExpression workerIdField =
"INSPECTOR".equals(workerType)
"REVIEWER".equals(workerType)
? labelingAssignmentEntity.inspectorUid
: labelingAssignmentEntity.workerUid;
BooleanExpression workerCondition =
"INSPECTOR".equals(workerType)
"REVIEWER".equals(workerType)
? labelingAssignmentEntity.inspectorUid.isNotNull()
: labelingAssignmentEntity.workerUid.isNotNull();
@@ -223,7 +258,7 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
.from(labelingAssignmentEntity)
.leftJoin(memberEntity)
.on(
"INSPECTOR".equals(workerType)
"REVIEWER".equals(workerType)
? memberEntity.employeeNo.eq(labelingAssignmentEntity.inspectorUid)
: memberEntity.employeeNo.eq(labelingAssignmentEntity.workerUid))
.where(labelingAssignmentEntity.analUid.eq(analUid), workerCondition, searchCondition)
@@ -364,7 +399,7 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
ZonedDateTime endOfDay = date.atTime(LocalTime.MAX).atZone(ZoneId.systemDefault());
BooleanExpression workerCondition =
"INSPECTOR".equals(workerType)
"REVIEWER".equals(workerType)
? labelingAssignmentEntity.inspectorUid.eq(workerId)
: labelingAssignmentEntity.workerUid.eq(workerId);
@@ -375,7 +410,8 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
.where(
labelingAssignmentEntity.analUid.eq(analUid),
workerCondition,
labelingAssignmentEntity.workState.in("DONE", "SKIP"),
labelingAssignmentEntity.workState.in(
LabelState.DONE.getId(), LabelState.SKIP.getId()),
labelingAssignmentEntity.modifiedDate.between(startOfDay, endOfDay))
.fetchOne();
@@ -394,7 +430,20 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
}
@Override
public InferenceDetail findInferenceDetail(Long analUid) {
public InferenceDetail findInferenceDetail(
Integer compareYyyy, Integer targetYyyy, Integer stage) {
// analUid로 분석 정보 조회
MapSheetAnalDataInferenceEntity analEntity =
queryFactory
.selectFrom(mapSheetAnalDataInferenceEntity)
.where(
mapSheetAnalDataInferenceEntity.compareYyyy.eq(compareYyyy),
mapSheetAnalDataInferenceEntity.targetYyyy.eq(targetYyyy),
mapSheetAnalDataInferenceEntity.stage.eq(stage))
.orderBy(mapSheetAnalDataInferenceEntity.analUid.asc())
.limit(1)
.fetchOne();
return queryFactory
.select(
Projections.constructor(
@@ -408,11 +457,139 @@ public class LabelAllocateRepositoryImpl implements LabelAllocateRepositoryCusto
.from(mapSheetAnalEntity)
.innerJoin(labelingAssignmentEntity)
.on(mapSheetAnalEntity.id.eq(labelingAssignmentEntity.analUid))
.where(mapSheetAnalEntity.id.eq(analUid))
.where(mapSheetAnalEntity.id.eq(analEntity.getAnalUid()))
.groupBy(
mapSheetAnalEntity.analTitle,
mapSheetAnalEntity.gukyuinApplyDttm,
mapSheetAnalEntity.detectingCnt)
.fetchOne();
}
@Override
public List<Long> fetchNextMoveIds(
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();
}
@Override
public Long findLabelUnCompleteCnt(Long analUid) {
MapSheetAnalEntity entity =
queryFactory
.selectFrom(mapSheetAnalEntity)
.where(mapSheetAnalEntity.id.eq(analUid))
.fetchOne();
if (Objects.isNull(entity)) {
throw new EntityNotFoundException();
}
return queryFactory
.select(mapSheetAnalDataInferenceGeomEntity.geoUid.count())
.from(mapSheetAnalDataInferenceGeomEntity)
.where(
mapSheetAnalDataInferenceGeomEntity.compareYyyy.eq(entity.getCompareYyyy()),
mapSheetAnalDataInferenceGeomEntity.targetYyyy.eq(entity.getTargetYyyy()),
mapSheetAnalDataInferenceGeomEntity.stage.eq(4), // TODO: 회차 컬럼을 가져와야 할 듯?
mapSheetAnalDataInferenceGeomEntity.labelState.in(
LabelState.ASSIGNED.getId(), LabelState.SKIP.getId()))
.fetchOne();
}
@Transactional
@Override
public void assignOwnerMove(List<Long> sub, String userId) {
queryFactory
.update(labelingAssignmentEntity)
.set(labelingAssignmentEntity.workerUid, userId)
.where(labelingAssignmentEntity.inferenceGeomUid.in(sub))
.execute();
em.clear();
}
@Override
public LabelerDetail findLabelerDetail(
String userId, Integer compareYyyy, Integer targetYyyy, Integer stage) {
NumberExpression<Long> assignedCnt =
new CaseBuilder()
.when(labelingAssignmentEntity.workState.eq(LabelState.ASSIGNED.getId()))
.then(1L)
.otherwise((Long) null)
.count();
NumberExpression<Long> skipCnt =
new CaseBuilder()
.when(labelingAssignmentEntity.workState.eq(LabelState.SKIP.getId()))
.then(1L)
.otherwise((Long) null)
.count();
NumberExpression<Long> completeCnt =
new CaseBuilder()
.when(labelingAssignmentEntity.workState.eq(LabelState.COMPLETE.getId()))
.then(1L)
.otherwise((Long) null)
.count();
NumberExpression<Double> percent =
new CaseBuilder()
.when(completeCnt.eq(0L))
.then(0.0)
.otherwise(
Expressions.numberTemplate(
Double.class,
"round({0} / {1}, 2)",
labelingAssignmentEntity.count(),
completeCnt));
// analUid로 분석 정보 조회
MapSheetAnalDataInferenceEntity analEntity =
queryFactory
.selectFrom(mapSheetAnalDataInferenceEntity)
.where(
mapSheetAnalDataInferenceEntity.compareYyyy.eq(compareYyyy),
mapSheetAnalDataInferenceEntity.targetYyyy.eq(targetYyyy),
mapSheetAnalDataInferenceEntity.stage.eq(stage))
.orderBy(mapSheetAnalDataInferenceEntity.analUid.asc())
.limit(1)
.fetchOne();
if (Objects.isNull(analEntity)) {
throw new EntityNotFoundException("MapSheetAnalEntity not found for analUid: ");
}
return queryFactory
.select(
Projections.constructor(
LabelerDetail.class,
memberEntity.userRole,
memberEntity.name,
memberEntity.employeeNo,
assignedCnt,
skipCnt,
completeCnt,
percent))
.from(memberEntity)
.innerJoin(labelingAssignmentEntity)
.on(
memberEntity.employeeNo.eq(labelingAssignmentEntity.workerUid),
labelingAssignmentEntity.analUid.eq(analEntity.getAnalUid()))
.where(memberEntity.employeeNo.eq(userId))
.groupBy(memberEntity.userRole, memberEntity.name, memberEntity.employeeNo)
.fetchOne();
}
}

View File

@@ -0,0 +1,7 @@
package com.kamco.cd.kamcoback.postgres.repository.label;
import com.kamco.cd.kamcoback.postgres.entity.MapSheetAnalDataInferenceGeomEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LabelWorkRepository
extends JpaRepository<MapSheetAnalDataInferenceGeomEntity, Long>, LabelWorkRepositoryCustom {}

View File

@@ -0,0 +1,10 @@
package com.kamco.cd.kamcoback.postgres.repository.label;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto.LabelWorkMng;
import org.springframework.data.domain.Page;
public interface LabelWorkRepositoryCustom {
public Page<LabelWorkMng> labelWorkMngList(LabelWorkDto.LabelWorkMngSearchReq searchReq);
}

View File

@@ -0,0 +1,138 @@
package com.kamco.cd.kamcoback.postgres.repository.label;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetAnalDataInferenceEntity.mapSheetAnalDataInferenceEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetAnalDataInferenceGeomEntity.mapSheetAnalDataInferenceGeomEntity;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto;
import com.kamco.cd.kamcoback.label.dto.LabelWorkDto.LabelWorkMng;
import com.kamco.cd.kamcoback.postgres.entity.MapSheetAnalDataGeomEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.CaseBuilder;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.time.format.DateTimeFormatter;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
import org.springframework.stereotype.Repository;
@Slf4j
@Repository
public class LabelWorkRepositoryImpl extends QuerydslRepositorySupport
implements LabelWorkRepositoryCustom {
private final JPAQueryFactory queryFactory;
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
@PersistenceContext private EntityManager em;
public LabelWorkRepositoryImpl(JPAQueryFactory queryFactory) {
super(MapSheetAnalDataGeomEntity.class);
this.queryFactory = queryFactory;
}
@Override
public Page<LabelWorkMng> labelWorkMngList(LabelWorkDto.LabelWorkMngSearchReq searchReq) {
Pageable pageable = PageRequest.of(searchReq.getPage(), searchReq.getSize());
BooleanBuilder whereBuilder = new BooleanBuilder();
BooleanBuilder whereSubBuilder = new BooleanBuilder();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
if (searchReq.getDetectYyyy() != null) {
whereBuilder.and(mapSheetAnalDataInferenceEntity.targetYyyy.eq(searchReq.getDetectYyyy()));
}
// mapSheetAnalDataInferenceGeomEntity.dataUid.eq(mapSheetAnalDataInferenceEntity.id)
whereSubBuilder.and(
mapSheetAnalDataInferenceGeomEntity.dataUid.eq(mapSheetAnalDataInferenceEntity.id));
if (searchReq.getStrtDttm() != null
&& !searchReq.getStrtDttm().isEmpty()
&& searchReq.getEndDttm() != null
&& !searchReq.getEndDttm().isEmpty()) {
// whereSubBuilder.and(mapSheetAnalDataInferenceGeomEntity.labelStateDttm.isNotNull());
whereSubBuilder.and(
Expressions.stringTemplate(
"to_char({0}, 'YYYYMMDD')", mapSheetAnalDataInferenceGeomEntity.labelStateDttm)
.between(searchReq.getStrtDttm(), searchReq.getEndDttm()));
// whereBuilder.and(mapSheetAnalDataInferenceGeomEntity.labelStateDttm.min().isNotNull());
}
List<LabelWorkMng> foundContent =
queryFactory
.select(
Projections.constructor(
LabelWorkMng.class,
mapSheetAnalDataInferenceEntity.compareYyyy,
mapSheetAnalDataInferenceEntity.targetYyyy,
mapSheetAnalDataInferenceEntity.stage,
mapSheetAnalDataInferenceEntity.createdDttm.min(),
mapSheetAnalDataInferenceGeomEntity.dataUid.count(),
mapSheetAnalDataInferenceGeomEntity.dataUid.count(),
new CaseBuilder()
.when(mapSheetAnalDataInferenceGeomEntity.labelState.eq("STOP"))
.then(1L)
.otherwise(0L)
.sum(),
new CaseBuilder()
.when(mapSheetAnalDataInferenceGeomEntity.labelState.eq("LABEL_ING"))
.then(1L)
.otherwise(0L)
.sum(),
new CaseBuilder()
.when(mapSheetAnalDataInferenceGeomEntity.labelState.eq("LABEL_COMPLETE"))
.then(1L)
.otherwise(0L)
.sum(),
mapSheetAnalDataInferenceGeomEntity.labelStateDttm.min()))
.from(mapSheetAnalDataInferenceEntity)
.innerJoin(mapSheetAnalDataInferenceGeomEntity)
.on(whereSubBuilder)
.where(whereBuilder)
.groupBy(
mapSheetAnalDataInferenceEntity.compareYyyy,
mapSheetAnalDataInferenceEntity.targetYyyy,
mapSheetAnalDataInferenceEntity.stage)
.orderBy(
mapSheetAnalDataInferenceEntity.targetYyyy.desc(),
mapSheetAnalDataInferenceEntity.stage.desc())
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();
/*
Long countQuery =
queryFactory
.select(mapSheetAnalDataInferenceEntity.count())
.from(mapSheetAnalDataInferenceEntity)
.leftJoin(mapSheetAnalDataInferenceGeomEntity)
.on(whereSubBuilder)
.where(whereBuilder)
.groupBy(
mapSheetAnalDataInferenceEntity.compareYyyy,
mapSheetAnalDataInferenceEntity.targetYyyy,
mapSheetAnalDataInferenceEntity.stage
)
.fetchOne();
*/
Long countQuery = foundContent.stream().count();
return new PageImpl<>(foundContent, pageable, countQuery);
}
}