추론 수정

This commit is contained in:
2026-02-26 23:18:31 +09:00
parent 046f4f06d3
commit 8904de0e3d
8 changed files with 853 additions and 454 deletions

View File

@@ -1,14 +1,8 @@
package com.kamco.cd.kamcoback.postgres.core;
import com.kamco.cd.kamcoback.common.enums.MngStateType;
import com.kamco.cd.kamcoback.common.exception.CustomApiException;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter.ImageFeature;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter.Scene;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.DetectOption;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetFallbackYearDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetScope;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.MngListCompareDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.MngListDto;
@@ -22,11 +16,11 @@ import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.Valid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -37,7 +31,6 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -55,9 +48,6 @@ public class MapSheetMngCoreService {
@Value("${file.sync-root-dir}")
private String syncRootDir;
@Value("${inference.geojson-dir}")
private String inferenceDir;
public List<MapSheetMngDto.MngDto> findMapSheetMngList() {
return mapSheetMngRepository.findMapSheetMngList();
}
@@ -235,124 +225,29 @@ public class MapSheetMngCoreService {
}
/**
* geojson 생성
* geojson 생성시 필요한 영상파일 정보 조회
*
* @param yyyy
* @param scenes
* @param mapSheetScope
* @param detectOption
* @return
*/
public Scene getSceneInference(
String yyyy, List<String> scenes, String mapSheetScope, String detectOption) {
List<ImageFeature> features = loadSceneInferenceBySheets(yyyy, scenes);
return writeSceneGeoJson(yyyy, mapSheetScope, detectOption, features);
}
/**
* geojson 생성
*
* @param yearDtos
* @param yyyy
* @param mapSheetScope
* @param detectOption
* @return
*/
public Scene getSceneInference(
List<MapSheetFallbackYearDto> yearDtos,
String yyyy,
String mapSheetScope,
String detectOption) {
List<ImageFeature> features = loadSceneInferenceByFallbackYears(yearDtos);
return writeSceneGeoJson(yyyy, mapSheetScope, detectOption, features);
}
/**
* 파일 경로/이름 , 파일 생성 , 도엽번호 반환
*
* @param yyyy
* @param mapSheetScope
* @param detectOption
* @param sceneInference
* @return Scene
*/
private Scene writeSceneGeoJson(
String yyyy, String mapSheetScope, String detectOption, List<ImageFeature> sceneInference) {
boolean isAll = MapSheetScope.ALL.getId().equals(mapSheetScope);
String optionSuffix = buildOptionSuffix(detectOption);
String targetDir =
"local".equals(activeEnv) ? System.getProperty("user.home") + "/geojson" : inferenceDir;
String filename =
isAll
? String.format("%s_%s_ALL%s.geojson", yyyy, activeEnv, optionSuffix)
: String.format("%s_%s%s.geojson", yyyy, activeEnv, optionSuffix);
Path outputPath = Paths.get(targetDir, filename);
if (sceneInference == null || sceneInference.isEmpty()) {
log.warn("NOT_FOUND_TARGET_YEAR: yyyy={}, isAll={}, featuresSize={}", yyyy, isAll, 0);
throw new CustomApiException("NOT_FOUND_TARGET_YEAR", HttpStatus.NOT_FOUND);
}
try {
log.info("create Directories outputPath: {}", outputPath);
log.info(
"activeEnv={}, inferenceDir={}, targetDir={}, filename={}",
activeEnv,
inferenceDir,
targetDir,
filename);
log.info("outputPath={}, parent={}", outputPath.toAbsolutePath(), outputPath.getParent());
Files.createDirectories(outputPath.getParent());
new GeoJsonFileWriter()
.exportToFile(sceneInference, "scene_inference_" + yyyy, 5186, outputPath.toString());
Scene scene = new Scene();
scene.setFeatures(sceneInference);
scene.setFilePath(outputPath.toString());
return scene;
} catch (IOException e) {
log.error(
"FAIL_CREATE_MAP_SHEET_FILE: yyyy={}, isAll={}, path={}", yyyy, isAll, outputPath, e);
throw new CustomApiException("INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, e);
}
}
/**
* geojson 파일명 Suffix
*
* @param detectOption
* @return
*/
private String buildOptionSuffix(String detectOption) {
if (DetectOption.EXCL.getId().equals(detectOption)) return "_EXCL";
if (DetectOption.PREV.getId().equals(detectOption)) return "_PREV";
return "";
}
/**
* 년도, 도엽번호로 조회
*
* @param yyyy
* @param scenes
* @param mapSheetNums
* @return ImageFeature
*/
private List<ImageFeature> loadSceneInferenceBySheets(String yyyy, List<String> scenes) {
List<ImageFeature> sceneInference = mapSheetMngRepository.getSceneInference(yyyy, scenes);
public List<ImageFeature> loadSceneInferenceBySheets(String yyyy, List<String> mapSheetNums) {
if (sceneInference == null || sceneInference.isEmpty()) {
log.warn(
"NOT_FOUND_TARGET_YEAR: yyyy={}, scenesSize={}",
yyyy,
scenes == null ? 0 : scenes.size());
throw new CustomApiException("NOT_FOUND_TARGET_YEAR", HttpStatus.NOT_FOUND);
if (mapSheetNums == null || mapSheetNums.isEmpty()) {
return List.of();
}
return sceneInference;
// CHUNK_SIZE 단위로 나누어 여러 번 조회한다.
final int CHUNK_SIZE = 1000;
List<ImageFeature> features = new ArrayList<>();
// i부터 CHUNK_SIZE만큼 잘라서 조회
// 마지막 구간은 남은 개수만큼만 처리하기 위해 Math.min 사용
for (int i = 0; i < mapSheetNums.size(); i += CHUNK_SIZE) {
List<String> chunk = mapSheetNums.subList(i, Math.min(i + CHUNK_SIZE, mapSheetNums.size()));
features.addAll(mapSheetMngRepository.getSceneInference(yyyy, chunk));
}
return features;
}
/**
@@ -361,33 +256,32 @@ public class MapSheetMngCoreService {
* @param yearDtos
* @return ImageFeature
*/
private List<ImageFeature> loadSceneInferenceByFallbackYears(
List<MapSheetFallbackYearDto> yearDtos) {
public List<ImageFeature> loadSceneInferenceByFallbackYears(List<MngListDto> yearDtos) {
if (yearDtos == null || yearDtos.isEmpty()) {
return List.of();
}
// 년도 별로 루프를 돌리기위해 년도별 정리
Map<Integer, List<MapSheetFallbackYearDto>> groupedByYear =
Map<Integer, List<MngListDto>> groupedByYear =
yearDtos.stream()
.filter(d -> d.getMngYyyy() != null && d.getMapSheetNum() != null)
.collect(Collectors.groupingBy(MapSheetFallbackYearDto::getMngYyyy));
.filter(d -> d.getMngYyyy() != 0 && d.getMapSheetNum() != null)
.collect(Collectors.groupingBy(MngListDto::getMngYyyy));
List<ImageFeature> sceneInference = new ArrayList<>();
for (Map.Entry<Integer, List<MapSheetFallbackYearDto>> entry : groupedByYear.entrySet()) {
for (Map.Entry<Integer, List<MngListDto>> entry : groupedByYear.entrySet()) {
Integer year = entry.getKey();
// 년도별 mapSheetNum 만들기
List<String> sheetNums =
entry.getValue().stream()
.map(MapSheetFallbackYearDto::getMapSheetNum)
.map(MngListDto::getMapSheetNum)
.filter(Objects::nonNull)
.distinct()
.toList();
// tif파일 정보 조회
List<ImageFeature> temp = mapSheetMngRepository.getSceneInference(year.toString(), sheetNums);
List<ImageFeature> temp = loadSceneInferenceBySheets(year.toString(), sheetNums);
if (temp != null && !temp.isEmpty()) {
sceneInference.addAll(temp);
@@ -400,15 +294,35 @@ public class MapSheetMngCoreService {
/**
* 변화탐지 실행 가능 기준 년도 조회
*
* @param req
* @return
* @param compareYear 비교 연도
* @param targetYear 기준 연도
* @param mapSheetScope 부분실행, 전체실행
* @param mapSheetNums 도엽번호 목록
* @return 실행가능한 도엽번호 목록
*/
public List<MngListDto> getHstMapSheetList(InferenceResultDto.RegReq req) {
return mapSheetMngRepository.findByHstMapSheetTargetList(req);
public List<MngListDto> findExecutableSheets(
Integer compareYear, Integer targetYear, String mapSheetScope, List<String> mapSheetNums) {
return mapSheetMngRepository.findExecutableSheets(
compareYear, targetYear, mapSheetScope, mapSheetNums);
}
public List<MngListDto> getHstMapSheetList(int mngYyyy, List<String> mapIds) {
return mapSheetMngRepository.findByHstMapSheetTargetList(mngYyyy, mapIds);
public List<MngListDto> fetchBaseWithCompare(
Integer compareYear, Integer targetYear, String mapSheetScope, List<String> mapSheetNums) {
return mapSheetMngRepository.fetchBaseWithCompare(
compareYear, targetYear, mapSheetScope, mapSheetNums);
}
/**
* 실행가능 도엽 count
*
* @param year 연도
* @param mapSheetScope 부분, 전체 구분
* @param mapSheetNums 도엽 목록
* @return count
*/
public int countExecutableSheetsDistinct(
Integer year, String mapSheetScope, List<String> mapSheetNums) {
return mapSheetMngRepository.countExecutableSheetsDistinct(year, mapSheetScope, mapSheetNums);
}
public void updateMapSheetMngHstUploadId(Long hstUid, UUID uuid, String uploadId) {
@@ -431,36 +345,32 @@ public class MapSheetMngCoreService {
return mapSheetMngYearRepository.findByHstMapSheetCompareList(mngYyyy, mapId);
}
/**
* 연도 조건으로 실행 가능 도엽번호 조회
*
* @param year 연도
* @return 추론 가능한 도엽 정보
*/
public List<String> getMapSheetNumByHst(Integer year) {
List<MapSheetMngHstEntity> entity = mapSheetMngRepository.getMapSheetMngHst(year);
return entity.stream().map(MapSheetMngHstEntity::getMapSheetNum).toList();
public List<MngListDto> getMapSheetMngHst(
Integer year, String mapSheetScope, List<String> mapSheetNum) {
return mapSheetMngRepository.getMapSheetMngHst(year, mapSheetScope, mapSheetNum);
}
/**
* 특정 연도의 도엽 이력 데이터를 조회
* 이전 년도 도엽 조회
*
* @param year
* @param mapIds
* @return
*/
public List<MapSheetFallbackYearDto> getMapSheetNumDtoByHst(Integer year) {
List<MapSheetMngHstEntity> entity = mapSheetMngRepository.getMapSheetMngHst(year);
return entity.stream()
.map(
e ->
new MapSheetFallbackYearDto(
e.getMapSheetNum(), e.getMngYyyy() // 조회 기준 연도
))
.toList();
}
public List<MngListDto> findFallbackCompareYearByMapSheets(Integer year, List<String> mapIds) {
if (mapIds == null || mapIds.isEmpty()) {
return Collections.emptyList();
}
public List<MapSheetFallbackYearDto> findFallbackCompareYearByMapSheets(
Integer year, List<String> mapIds) {
return mapSheetMngRepository.findFallbackCompareYearByMapSheets(year, mapIds);
int chunkSize = 1000;
List<MngListDto> result = new ArrayList<>();
for (int i = 0; i < mapIds.size(); i += chunkSize) {
List<String> chunk = mapIds.subList(i, Math.min(i + chunkSize, mapIds.size()));
result.addAll(mapSheetMngRepository.findFallbackCompareYearByMapSheets(year, chunk));
}
return result;
}
}

View File

@@ -1,8 +1,6 @@
package com.kamco.cd.kamcoback.postgres.repository.mapsheet;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter.ImageFeature;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetFallbackYearDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.AddReq;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.MngListDto;
@@ -65,14 +63,38 @@ public interface MapSheetMngRepositoryCustom {
List<MapSheetMngDto.MngFilesDto> findByHstUidMapSheetFileList(Long hstUid);
/**
* 기준년도 추론 실행 가능 도엽 조회
* 추론 실행 가능 도엽 조회 (추론 제외)
*
* @param req 조회 연도, 도엽번호 목록,
* @return 실행 가능한 도엽번호
* @param compareYear 비교 연도
* @param targetYear 기준 연도
* @param mapSheetScope 부분실행, 전체실행
* @param mapSheetNums 도엽번호 목록
* @return 실행가능한 도엽번호 목록
*/
List<MngListDto> findByHstMapSheetTargetList(InferenceResultDto.RegReq req);
List<MngListDto> findExecutableSheets(
Integer compareYear, Integer targetYear, String mapSheetScope, List<String> mapSheetNums);
List<MngListDto> findByHstMapSheetTargetList(int mngYyyy, List<String> mapIds);
/**
* 추론 실행 가능 도엽 조회 (이전년도 사용가능)
*
* @param targetYear
* @param compareYear
* @param mapSheetScope
* @param mapSheetNums
* @return
*/
List<MngListDto> fetchBaseWithCompare(
Integer targetYear, Integer compareYear, String mapSheetScope, List<String> mapSheetNums);
/**
* 실행가능 도엽 count
*
* @param year 연도
* @param mapSheetScope 부분, 전체 구분
* @param mapSheetNums 도엽 목록
* @return count
*/
int countExecutableSheetsDistinct(Integer year, String mapSheetScope, List<String> mapSheetNums);
MapSheetMngDto.MngFilesDto findByFileUidMapSheetFile(Long fileUid);
@@ -82,6 +104,13 @@ public interface MapSheetMngRepositoryCustom {
Page<YearEntity> getYears(YearSearchReq req);
/**
* 도엽 영상파일 정보 조회
*
* @param yyyy 연도
* @param mapSheetNums 도엽목록
* @return 도엽 영상파일 정보
*/
List<ImageFeature> getSceneInference(String yyyy, List<String> mapSheetNums);
void updateMapSheetMngHstUploadId(Long hstUid, UUID uuid, String uploadId);
@@ -94,8 +123,7 @@ public interface MapSheetMngRepositoryCustom {
* @param year 연도
* @return 추론 가능한 도엽 정보
*/
List<MapSheetMngHstEntity> getMapSheetMngHst(Integer year);
List<MngListDto> getMapSheetMngHst(Integer year, String mapSheetScope, List<String> mapSheetNum);
List<MapSheetFallbackYearDto> findFallbackCompareYearByMapSheets(
Integer year, List<String> mapIds);
List<MngListDto> findFallbackCompareYearByMapSheets(Integer year, List<String> mapIds);
}

View File

@@ -5,36 +5,41 @@ import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngEntity.mapSheet
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngFileEntity.mapSheetMngFileEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngHstEntity.mapSheetMngHstEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngTileEntity.mapSheetMngTileEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngYearYnEntity.mapSheetMngYearYnEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QYearEntity.yearEntity;
import static com.querydsl.core.types.dsl.Expressions.nullExpression;
import com.kamco.cd.kamcoback.common.enums.CommonUseStatus;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter.ImageFeature;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetFallbackYearDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetScope;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.AddReq;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.MngListDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.YearSearchReq;
import com.kamco.cd.kamcoback.postgres.entity.MapSheetMngHstEntity;
import com.kamco.cd.kamcoback.postgres.entity.QMapInkx5kEntity;
import com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngFileEntity;
import com.kamco.cd.kamcoback.postgres.entity.QMapSheetMngHstEntity;
import com.kamco.cd.kamcoback.postgres.entity.QYearEntity;
import com.kamco.cd.kamcoback.postgres.entity.YearEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.CaseBuilder;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.validation.Valid;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@@ -573,80 +578,201 @@ public class MapSheetMngRepositoryImpl extends QuerydslRepositorySupport
}
@Override
public List<MngListDto> findByHstMapSheetTargetList(InferenceResultDto.RegReq req) {
BooleanBuilder whereBuilder = new BooleanBuilder();
public List<MngListDto> findExecutableSheets(
Integer compareYear, Integer targetYear, String mapSheetScope, List<String> mapSheetNums) {
whereBuilder.and(mapSheetMngHstEntity.dataState.eq("DONE"));
whereBuilder.and(
mapSheetMngHstEntity
.syncState
.eq("DONE")
.or(mapSheetMngHstEntity.syncCheckState.eq("DONE")));
whereBuilder.and(mapSheetMngHstEntity.useInference.eq("USE"));
QMapSheetMngHstEntity t = new QMapSheetMngHstEntity("t");
QMapSheetMngHstEntity c = new QMapSheetMngHstEntity("c");
whereBuilder.and(mapSheetMngHstEntity.mngYyyy.eq(req.getTargetYyyy()));
QMapInkx5kEntity ti = new QMapInkx5kEntity("ti");
QMapInkx5kEntity ci = new QMapInkx5kEntity("ci");
QMapSheetMngFileEntity tf = new QMapSheetMngFileEntity("tf");
QMapSheetMngFileEntity cf = new QMapSheetMngFileEntity("cf");
BooleanBuilder whereBuilderere = new BooleanBuilder();
whereBuilderere.and(t.dataState.eq("DONE"));
whereBuilderere.and(t.syncState.eq("DONE").or(t.syncCheckState.eq("DONE")));
whereBuilderere.and(t.useInference.eq("USE"));
whereBuilderere.and(t.mngYyyy.eq(targetYear));
// target: tif + DONE 파일 존재
whereBuilderere.and(
JPAExpressions.selectOne()
.from(tf)
.where(tf.hstUid.eq(t.hstUid).and(tf.fileExt.eq("tif")).and(tf.fileState.eq("DONE")))
.exists());
// PART scope면 prefix like 조건 추가
BooleanBuilder likeBuilder = new BooleanBuilder();
// 부분 선택 실행이면 도엽번호 검색조건 추가
if (MapSheetScope.PART.getId().equals(req.getMapSheetScope())) {
List<String> list = req.getMapSheetNum();
if (list == null || list.isEmpty()) {
if (MapSheetScope.PART.getId().equals(mapSheetScope)) {
if (mapSheetNums == null || mapSheetNums.isEmpty()) {
return List.of();
}
for (String prefix : list) {
if (prefix == null || prefix.isBlank()) {
continue;
}
// 50k 도엽번호로 Like 하여 5k 도엽번호 검색
likeBuilder.or(mapSheetMngHstEntity.mapSheetNum.like(prefix.trim() + "%"));
for (String prefix : mapSheetNums) {
if (prefix == null || prefix.isBlank()) continue;
likeBuilder.or(t.mapSheetNum.like(prefix.trim() + "%"));
}
if (likeBuilder.hasValue()) {
whereBuilderere.and(likeBuilder);
}
}
if (likeBuilder.hasValue()) {
whereBuilder.and(likeBuilder);
}
// compare 조건은 EXISTS 서브쿼리 안에서 체크
BooleanExpression compareExists =
JPAExpressions.selectOne()
.from(c)
.join(ci)
.on(ci.mapidcdNo.eq(c.mapSheetNum).and(ci.useInference.eq(CommonUseStatus.USE)))
.where(
c.mapSheetNum
.eq(t.mapSheetNum) // 핵심: 같은 도엽번호
.and(c.dataState.eq("DONE"))
.and(c.syncState.eq("DONE").or(c.syncCheckState.eq("DONE")))
.and(c.useInference.eq("USE"))
.and(c.mngYyyy.eq(compareYear))
.and(
JPAExpressions.selectOne()
.from(cf)
.where(
cf.hstUid
.eq(c.hstUid)
.and(cf.fileExt.eq("tif"))
.and(cf.fileState.eq("DONE")))
.exists()))
.exists();
return queryFactory
.select(
Projections.constructor(
MngListDto.class,
mapSheetMngHstEntity.mngYyyy,
mapSheetMngHstEntity.mapSheetNum,
mapSheetMngHstEntity.mapSheetName,
nullExpression(Integer.class),
nullExpression(Boolean.class)))
.from(mapSheetMngHstEntity)
.innerJoin(mapInkx5kEntity)
.on(
mapInkx5kEntity
.mapidcdNo
.eq(mapSheetMngHstEntity.mapSheetNum)
.and(mapInkx5kEntity.useInference.eq(CommonUseStatus.USE)))
.where(whereBuilder)
t.mngYyyy, // int mngYyyy
t.mapSheetNum, // String mapSheetNum
t.mapSheetName, // String mapSheetName
Expressions.nullExpression(Integer.class),
Expressions.nullExpression(Boolean.class)))
.from(t)
.join(ti)
.on(ti.mapidcdNo.eq(t.mapSheetNum).and(ti.useInference.eq(CommonUseStatus.USE)))
.where(whereBuilderere.and(compareExists))
.distinct()
.fetch();
}
@Override
public List<MngListDto> findByHstMapSheetTargetList(int mngYyyy, List<String> mapIds) {
BooleanBuilder whereBuilder = new BooleanBuilder();
whereBuilder.and(mapSheetMngHstEntity.mngYyyy.eq(mngYyyy));
whereBuilder.and(mapSheetMngHstEntity.mapSheetNum.in(mapIds));
whereBuilder.and(mapSheetMngHstEntity.dataState.eq("DONE"));
whereBuilder.and(mapSheetMngHstEntity.syncState.eq("DONE")); // TODO 싱크체크 or조건 추가
whereBuilder.and(mapSheetMngHstEntity.useInference.eq("USE"));
public List<MngListDto> fetchBaseWithCompare(
Integer compareYear, // 예: 2024 (비교 상한)
Integer targetYear, // 예: 2026 (기준 고정)
String mapSheetScope,
List<String> mapSheetNums) {
return queryFactory
.select(
Projections.constructor(
MngListDto.class,
mapSheetMngHstEntity.mngYyyy,
mapSheetMngHstEntity.mapSheetNum,
mapSheetMngHstEntity.mapSheetName))
.from(mapSheetMngHstEntity)
.where(whereBuilder)
.fetch();
QMapSheetMngHstEntity h = QMapSheetMngHstEntity.mapSheetMngHstEntity; // base
QMapSheetMngHstEntity h2 = new QMapSheetMngHstEntity("h2"); // cmp
QMapInkx5kEntity i = QMapInkx5kEntity.mapInkx5kEntity;
QMapSheetMngFileEntity f = QMapSheetMngFileEntity.mapSheetMngFileEntity;
QMapSheetMngFileEntity f2 = new QMapSheetMngFileEntity("f2");
// -----------------------
// 공통: tif DONE exists
// -----------------------
BooleanExpression baseTifExists =
JPAExpressions.selectOne()
.from(f)
.where(f.hstUid.eq(h.hstUid), f.fileExt.eq("tif"), f.fileState.eq("DONE"))
.exists();
BooleanExpression cmpTifExists =
JPAExpressions.selectOne()
.from(f2)
.where(f2.hstUid.eq(h2.hstUid), f2.fileExt.eq("tif"), f2.fileState.eq("DONE"))
.exists();
// -----------------------
// 1) base 조회 (CTE base)
// -----------------------
BooleanBuilder baseWhere =
new BooleanBuilder()
.and(h.mngYyyy.eq(targetYear))
.and(h.dataState.eq("DONE"))
.and(h.useInference.eq("USE"))
.and(h.syncState.eq("DONE").or(h.syncCheckState.eq("DONE")))
.and(baseTifExists);
// PART 조건
if (MapSheetScope.PART.getId().equals(mapSheetScope)) {
if (mapSheetNums == null || mapSheetNums.isEmpty()) return List.of();
BooleanBuilder like = new BooleanBuilder();
for (String prefix : mapSheetNums) {
if (prefix == null || prefix.isBlank()) continue;
like.or(h.mapSheetNum.like(prefix.trim() + "%"));
}
if (!like.hasValue()) return List.of();
baseWhere.and(like);
}
// base: distinct map_sheet_num, mng_yyyy, map_sheet_name
List<Tuple> baseTuples =
queryFactory
.select(h.mapSheetNum, h.mngYyyy, h.mapSheetName)
.distinct()
.from(h)
.join(i)
.on(i.mapidcdNo.eq(h.mapSheetNum), i.useInference.eq(CommonUseStatus.USE))
.where(baseWhere)
.fetch();
if (baseTuples.isEmpty()) return List.of();
List<String> baseNums = baseTuples.stream().map(t -> t.get(h.mapSheetNum)).toList();
// -----------------------
// 2) cmp 집계 (CTE cmp)
// map_sheet_num별 max(mng_yyyy <= 2024)
// -----------------------
List<Tuple> cmpTuples =
queryFactory
.select(h2.mapSheetNum, h2.mngYyyy.max())
.from(h2)
.where(
h2.mapSheetNum.in(baseNums),
h2.mngYyyy.loe(compareYear),
h2.dataState.eq("DONE"),
h2.useInference.eq("USE"),
h2.syncState.eq("DONE").or(h2.syncCheckState.eq("DONE")),
cmpTifExists)
.groupBy(h2.mapSheetNum)
.fetch();
Map<String, Integer> beforeYearMap = new HashMap<>(cmpTuples.size());
for (Tuple t : cmpTuples) {
String num = t.get(h2.mapSheetNum);
Integer beforeYear = t.get(h2.mngYyyy.max());
beforeYearMap.put(num, beforeYear);
}
// -----------------------
// 3) base JOIN cmp (메모리)
// - SQL에서 join cmp c on c.map_sheet_num = b.map_sheet_num 동일
// -----------------------
List<MngListDto> result = new ArrayList<>();
for (Tuple bt : baseTuples) {
String num = bt.get(h.mapSheetNum);
Integer beforeYear = beforeYearMap.get(num);
if (beforeYear == null) continue; // SQL의 inner join cmp 효과
result.add(
new MngListDto(
bt.get(h.mngYyyy), // 2026
num,
bt.get(h.mapSheetName),
beforeYear, // <=2024 max
null // isSuccess
));
}
return result;
}
@Override
@@ -1099,42 +1225,161 @@ public class MapSheetMngRepositoryImpl extends QuerydslRepositorySupport
}
@Override
public List<MapSheetMngHstEntity> getMapSheetMngHst(Integer year) {
return queryFactory
.select(mapSheetMngHstEntity)
.from(mapSheetMngHstEntity)
.innerJoin(mapSheetMngFileEntity)
.on(mapSheetMngFileEntity.hstUid.eq(mapSheetMngHstEntity.hstUid))
.where(
mapSheetMngHstEntity
.mngYyyy
.eq(year)
.and(
mapSheetMngHstEntity
.syncState
.eq("DONE")
.or(mapSheetMngHstEntity.syncCheckState.eq("DONE")))
.and(mapSheetMngFileEntity.fileExt.eq("tif")))
.fetch();
}
public List<MngListDto> getMapSheetMngHst(
Integer year, String mapSheetScope, List<String> mapSheetNum) {
BooleanBuilder whereBuilder = new BooleanBuilder();
@Override
public List<MapSheetFallbackYearDto> findFallbackCompareYearByMapSheets(
Integer year, List<String> mapIds) {
BooleanBuilder builder = new BooleanBuilder();
builder.and(mapSheetMngYearYnEntity.id.mapSheetNum.in(mapIds));
builder.and(mapSheetMngYearYnEntity.id.mngYyyy.lt(year));
builder.and(mapSheetMngYearYnEntity.yn.eq("Y"));
whereBuilder.and(mapSheetMngHstEntity.dataState.eq("DONE"));
whereBuilder.and(
mapSheetMngHstEntity
.syncState
.eq("DONE")
.or(mapSheetMngHstEntity.syncCheckState.eq("DONE")));
whereBuilder.and(mapSheetMngHstEntity.useInference.eq("USE"));
whereBuilder.and(mapSheetMngHstEntity.mngYyyy.eq(year));
BooleanBuilder likeBuilder = new BooleanBuilder();
if (MapSheetScope.PART.getId().equals(mapSheetScope)) {
List<String> list = mapSheetNum;
if (list == null || list.isEmpty()) {
return List.of();
}
for (String prefix : list) {
if (prefix == null || prefix.isBlank()) {
continue;
}
likeBuilder.or(mapSheetMngHstEntity.mapSheetNum.like(prefix.trim() + "%"));
}
}
if (likeBuilder.hasValue()) {
whereBuilder.and(likeBuilder);
}
return queryFactory
.select(
Projections.constructor(
MapSheetFallbackYearDto.class,
mapSheetMngYearYnEntity.id.mapSheetNum,
mapSheetMngYearYnEntity.id.mngYyyy.max()))
.from(mapSheetMngYearYnEntity)
.where(builder)
.groupBy(mapSheetMngYearYnEntity.id.mapSheetNum)
MngListDto.class,
mapSheetMngHstEntity.mngYyyy,
mapSheetMngHstEntity.mapSheetNum,
mapSheetMngHstEntity.mapSheetName,
nullExpression(Integer.class),
nullExpression(Boolean.class)))
.from(mapSheetMngHstEntity)
.innerJoin(mapInkx5kEntity)
.on(
mapInkx5kEntity
.mapidcdNo
.eq(mapSheetMngHstEntity.mapSheetNum)
.and(mapInkx5kEntity.useInference.eq(CommonUseStatus.USE)))
.where(whereBuilder)
.fetch();
}
@Override
public List<MngListDto> findFallbackCompareYearByMapSheets(Integer year, List<String> mapIds) {
QMapSheetMngHstEntity h = QMapSheetMngHstEntity.mapSheetMngHstEntity;
QMapSheetMngHstEntity h2 = new QMapSheetMngHstEntity("h2");
QMapSheetMngFileEntity f = QMapSheetMngFileEntity.mapSheetMngFileEntity;
QMapSheetMngFileEntity f2 = new QMapSheetMngFileEntity("f2");
QMapInkx5kEntity inkk = QMapInkx5kEntity.mapInkx5kEntity;
return queryFactory
.select(
Projections.constructor(
MngListDto.class,
h.mngYyyy,
h.mapSheetNum,
h.mapSheetName,
nullExpression(Integer.class),
nullExpression(Boolean.class)))
.from(h)
.innerJoin(inkk)
.on(inkk.mapidcdNo.eq(h.mapSheetNum).and(inkk.useInference.eq(CommonUseStatus.USE)))
.where(
h.mapSheetNum.in(mapIds),
h.mngYyyy.lt(year),
h.dataState.eq("DONE"),
h.useInference.eq("USE"),
h.syncState.eq("DONE").or(h.syncCheckState.eq("DONE")),
JPAExpressions.selectOne()
.from(f)
.where(f.hstUid.eq(h.hstUid), f.fileExt.eq("tif"), f.fileState.eq("DONE"))
.exists(),
// mapSheetNum별 최대 mngYyyy인 행만 남김
h.mngYyyy.eq(
JPAExpressions.select(h2.mngYyyy.max())
.from(h2)
.where(
h2.mapSheetNum.eq(h.mapSheetNum),
h2.mngYyyy.lt(year),
h2.dataState.eq("DONE"),
h2.useInference.eq("USE"),
h2.syncState.eq("DONE").or(h2.syncCheckState.eq("DONE")),
JPAExpressions.selectOne()
.from(f2)
.where(
f2.hstUid.eq(h2.hstUid),
f2.fileExt.eq("tif"),
f2.fileState.eq("DONE"))
.exists())))
.fetch();
}
@Override
public int countExecutableSheetsDistinct(
Integer year, String mapSheetScope, List<String> mapSheetNum) {
QMapSheetMngHstEntity h = QMapSheetMngHstEntity.mapSheetMngHstEntity;
QMapInkx5kEntity i = QMapInkx5kEntity.mapInkx5kEntity;
QMapSheetMngFileEntity f = QMapSheetMngFileEntity.mapSheetMngFileEntity;
BooleanBuilder where = new BooleanBuilder();
// 실행가능 조건
where.and(h.dataState.eq("DONE"));
where.and(h.syncState.eq("DONE").or(h.syncCheckState.eq("DONE")));
where.and(h.useInference.eq("USE"));
where.and(h.mngYyyy.eq(year));
// tif + DONE 파일 존재 조건 AND EXISTS
where.and(
JPAExpressions.selectOne()
.from(f)
.where(f.hstUid.eq(h.hstUid).and(f.fileExt.eq("tif")).and(f.fileState.eq("DONE")))
.exists());
// PART scope prefix 조건
if (MapSheetScope.PART.getId().equals(mapSheetScope)) {
if (mapSheetNum == null || mapSheetNum.isEmpty()) {
return 0;
}
BooleanBuilder likeBuilder = new BooleanBuilder();
for (String prefix : mapSheetNum) {
if (prefix == null || prefix.isBlank()) continue;
likeBuilder.or(h.mapSheetNum.like(prefix.trim() + "%"));
}
if (likeBuilder.hasValue()) {
where.and(likeBuilder);
}
}
// DISTINCT mapSheetNum 기준 카운트
Long count =
queryFactory
.select(h.mapSheetNum.countDistinct())
.from(h)
.join(i)
.on(i.mapidcdNo.eq(h.mapSheetNum).and(i.useInference.eq(CommonUseStatus.USE)))
.where(where)
.fetchOne();
return count != null ? count.intValue() : 0;
}
}