package com.kri.contact.server.service; import com.kri.common.feature.web.BusinessException; import com.kri.common.feature.web.RequestUserContext; import com.kri.common.feature.web.page.PageRequestDto; import com.kri.common.feature.web.page.PageResponseDto; import com.kri.common.feature.web.page.Pageables; import com.kri.contact.server.common.consts.ContactConstant; import com.kri.contact.server.common.external.shorturl.ShortUrlApiClient; import com.kri.contact.server.dto.project.ProjectCreateRequestDto; import com.kri.contact.server.dto.project.ProjectInfoDto; import com.kri.contact.server.dto.project.ProjectMainTemplateUpdateRequestDto; import com.kri.contact.server.dto.project.ProjectOwnerResponseDto; import com.kri.contact.server.dto.project.ProjectSearchRequestDto; import com.kri.contact.server.dto.project.ProjectSurveyDto; import com.kri.contact.server.dto.project.ProjectUpdateRequestDto; import com.kri.contact.server.persistence.entity.TPrjctEntity; import com.kri.contact.server.persistence.entity.TPrjctMainTmplatEntity; import com.kri.contact.server.persistence.entity.TPrjctSurveyEntity; import com.kri.contact.server.persistence.query.ProjectSpecs; import com.kri.contact.server.persistence.repository.ProjectMainTemplateRepository; import com.kri.contact.server.persistence.repository.ProjectRepository; import com.kri.contact.server.persistence.repository.ProjectSurveyRepository; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @RequiredArgsConstructor public class ProjectService { private static final List STATUS_0_1 = List.of((short) 0, (short) 1); private static final List STATUS_1 = List.of((short) 1); private static final String PRJCT_SURVEY_IDX_TOKEN = "[$prjctSurveyIdx]"; private static final String KON_URL_TOKEN = "[$KON-URL]"; private static final String KIWI_URL_TOKEN = "[$KIWI-URL]"; private static final String KON_SURVEY_BASE_URL = "https://kon.kric.com/project/"; private static final String KIWI_SURVEY_BASE_URL = "https://kon.kiwisurvey.kr/project/"; private final AssignService assignService; private final ResultCodeService resultCodeService; private final ListHeaderService listHeaderService; private final ProjectRepository projectRepository; private final ProjectMainTemplateRepository projectMainTemplateRepository; private final ProjectSurveyRepository projectSurveyRepository; private final ShortUrlApiClient shortUrlApiClient; @Transactional public ProjectInfoDto createProject( ProjectCreateRequestDto req, String regUser, LocalDateTime regDt ) { String itrnt = req.getItrntPrjctCd(); try { String prjctCd = this.makePrjctCd(itrnt); TPrjctEntity entity = TPrjctEntity.create(req, prjctCd, regUser, regDt); ProjectInfoDto savedProject = withSurveys(projectRepository.save(entity), List.of()); resultCodeService.copyResultCodeFromDefault(savedProject.getPrjctIdx(), regUser, regDt); listHeaderService.copyDefaultHeader(savedProject.getPrjctIdx(), regUser, regDt); return savedProject; } catch (DataIntegrityViolationException e) { throw BusinessException.conflict( "PROJECT_CODE_CONFLICT", "프로젝트 코드 생성 중 충돌이 발생했습니다. 다시 시도해주세요." ).with("itrntPrjctCd", itrnt); } } @Transactional(readOnly = true) public ProjectInfoDto getProject(Long prjctIdx) { return withSurveys(projectRepository.findByPrjctIdxAndDelFalse(prjctIdx)); } @Transactional(readOnly = true) public Long getProjectIdxByCode(String prjctCd) { return projectRepository.findByPrjctCdAndDelFalse(prjctCd) .map(TPrjctEntity::getPrjctIdx) .orElseThrow(() -> BusinessException.notFound("PROJECT_NOT_FOUND", "프로젝트를 찾을 수 없습니다.") .with("prjctCd", prjctCd)); } @Transactional(readOnly = true) public List getTopProject( int topCount, String keyword, String userId, String userCmpn, String userTeam, Integer userRole ) { Specification spec = ProjectSpecs.keywordLike(keyword) .and(ProjectSpecs.isDelFalse()); if (isTeamUserRole(userRole)) { spec = spec.and(ProjectSpecs.ownerDeptEqual(userTeam)); } else if (userRole >= ContactConstant.OUTSOURCE_USER_ROLE) { if (userRole >= ContactConstant.FIELDWORK_USER_ROLE) { spec = spec.and(ProjectSpecs.statusIn(STATUS_1)); } else { spec = spec.and(ProjectSpecs.statusIn(STATUS_0_1)); } spec = spec.and(userRole >= ContactConstant.FIELDWORK_USER_ROLE ? ProjectSpecs.assignedToUserAndNotExcluded(userId) : ProjectSpecs.assignedToCmpn(userCmpn)); } Pageable pageable = PageRequest.of(0, topCount, Sort.by(Sort.Direction.DESC, "regDt")); return withSurveys(projectRepository.findAll(spec, pageable).getContent()); } @Transactional(readOnly = true) public PageResponseDto searchProject( ProjectSearchRequestDto req, String userId, String userCmpn, String userTeam, Integer userRole ) { Specification spec = ProjectSpecs.keywordLike(req.getPrjctText()) .and(ProjectSpecs.isDelFalse()) .and(ProjectSpecs.statusIn(req.getPrjctStatusList())) .and(ProjectSpecs.ownerDeptIn(req.getOwnerDeptList())) .and(ProjectSpecs.ownerFwIn(req.getOwnerFwList())); if (isTeamUserRole(userRole)) { spec = spec.and(ProjectSpecs.ownerDeptEqual(userTeam)); } else if (userRole >= ContactConstant.OUTSOURCE_USER_ROLE) { if (userRole >= ContactConstant.FIELDWORK_USER_ROLE) { spec = spec.and(ProjectSpecs.statusIn(STATUS_1)); } else { spec = spec.and(ProjectSpecs.statusIn(STATUS_0_1)); } spec = spec.and(userRole >= ContactConstant.FIELDWORK_USER_ROLE ? ProjectSpecs.assignedToUserAndNotExcluded(userId) : ProjectSpecs.assignedToCmpn(userCmpn)); } PageRequestDto pageReq = req.getPageRequest(); Pageable pageable = Pageables.of(pageReq, TPrjctEntity.class, Map.of( "prjctName", "prjctNm" )); Page page = projectRepository.findAll(spec, pageable); Map> surveyMap = findSurveyMap( page.getContent().stream() .map(TPrjctEntity::getPrjctIdx) .toList() ); return PageResponseDto.from(page.map(entity -> withSurveys( entity, surveyMap.getOrDefault(entity.getPrjctIdx(), List.of()) ))); } public ProjectOwnerResponseDto getOwnerList(Integer userRole) { ProjectOwnerResponseDto responseDto = new ProjectOwnerResponseDto(); responseDto.setOwnerDeptList(this.getOwnerDeptList(userRole)); responseDto.setOwnerFwList(this.getOwnerFwList(userRole)); return responseDto; } public List getOwnerDeptList(Integer userRole) { final List statusList = userRole < ContactConstant.OUTSOURCE_USER_ROLE ? null : userRole < ContactConstant.FIELDWORK_USER_ROLE ? STATUS_0_1 : STATUS_1; return projectRepository.findDistinctOwnerDept(statusList); } public List getOwnerFwList(Integer userRole) { final List statusList = userRole < ContactConstant.OUTSOURCE_USER_ROLE ? null : userRole < ContactConstant.FIELDWORK_USER_ROLE ? STATUS_0_1 : STATUS_1; return projectRepository.findDistinctOwnerFw(statusList); } public Long getMainTemplateIdx(Long prjctIdx, Short chnnlTy) { return projectMainTemplateRepository.findByIdPrjctIdxAndIdChnnlTy(prjctIdx, chnnlTy) .map(TPrjctMainTmplatEntity::getTmplatIdx) .orElse(null); } @Transactional public void updateProject( long prjctIdx, ProjectUpdateRequestDto req, String modUser, LocalDateTime modDt, RequestUserContext ctx ) { TPrjctEntity entity = projectRepository.findById(prjctIdx) .orElseThrow(() -> BusinessException.notFound("PROJECT_NOT_FOUND", "프로젝트를 찾을 수 없습니다.") .with("prjctIdx", prjctIdx)); entity.updateFrom(req.getProjectInfo(), modUser, modDt); updateProjectSurveys(prjctIdx, req.getProjectInfo().getSurveys(), modUser, modDt, ctx); assignService.upsertPrjctCmpnAssign(prjctIdx, req.getAssignCmpnIdList(), modUser, modDt); resultCodeService.updateResultCode(prjctIdx, req.getResultCodeList(), modUser, modDt); } @Transactional public void updateProjectMainTemplate(ProjectMainTemplateUpdateRequestDto req, String modUser, LocalDateTime modDt) { Short chnnlTy = req.getChnnlTy().getCode(); projectMainTemplateRepository.deleteByIdPrjctIdxAndIdChnnlTy(req.getPrjctIdx(), chnnlTy); if (req.getTmplatIdx() == null) { return; } TPrjctMainTmplatEntity entity = TPrjctMainTmplatEntity.create(req, modUser, modDt); projectMainTemplateRepository.save(entity); } @Transactional public void deleteProject(Long prjctIdx, String delUser, LocalDateTime delDt) { int deleteCount = projectRepository.softDeleteByPrjctIdx(prjctIdx, delUser, delDt); if (deleteCount == 0) { throw BusinessException.notFound("PROJECT_NOT_FOUND", "프로젝트를 찾을 수 없습니다.") .with("prjctIdx", prjctIdx); } } private ProjectInfoDto withSurveys(TPrjctEntity entity) { if (entity == null) { return null; } List surveys = projectSurveyRepository .findByPrjctIdxOrderBySurveyOrderAscPrjctSurveyIdxAsc(entity.getPrjctIdx()) .stream() .map(ProjectSurveyDto::from) .toList(); return withSurveys(entity, surveys); } private ProjectInfoDto withSurveys(TPrjctEntity entity, List surveys) { ProjectInfoDto dto = ProjectInfoDto.from(entity); if (dto != null) { dto.setSurveys(surveys == null ? new ArrayList<>() : surveys); } return dto; } private List withSurveys(List entities) { Map> surveyMap = findSurveyMap( entities.stream() .map(TPrjctEntity::getPrjctIdx) .toList() ); return entities.stream() .map(entity -> withSurveys(entity, surveyMap.getOrDefault(entity.getPrjctIdx(), List.of()))) .toList(); } private Map> findSurveyMap(Collection prjctIdxs) { if (prjctIdxs == null || prjctIdxs.isEmpty()) { return Map.of(); } return projectSurveyRepository .findByPrjctIdxInOrderByPrjctIdxAscSurveyOrderAscPrjctSurveyIdxAsc(prjctIdxs) .stream() .collect(Collectors.groupingBy( TPrjctSurveyEntity::getPrjctIdx, LinkedHashMap::new, Collectors.mapping(ProjectSurveyDto::from, Collectors.toList()) )); } private void updateProjectSurveys( Long prjctIdx, List surveys, String modUser, LocalDateTime modDt, RequestUserContext ctx ) { List requestSurveys = surveys == null ? List.of() : surveys; Map existingMap = projectSurveyRepository .findByPrjctIdxOrderBySurveyOrderAscPrjctSurveyIdxAsc(prjctIdx) .stream() .collect(Collectors.toMap( TPrjctSurveyEntity::getPrjctSurveyIdx, Function.identity(), (left, right) -> left, LinkedHashMap::new )); Set requestedIds = requestSurveys.stream() .map(ProjectSurveyDto::getPrjctSurveyIdx) .filter(Objects::nonNull) .collect(Collectors.toSet()); List deleteTargets = existingMap.values().stream() .filter(entity -> !requestedIds.contains(entity.getPrjctSurveyIdx())) .toList(); if (!deleteTargets.isEmpty()) { projectSurveyRepository.deleteAllInBatch(deleteTargets); } List saveTargets = new ArrayList<>(); for (ProjectSurveyDto survey : requestSurveys) { if (survey.getPrjctSurveyIdx() == null) { saveTargets.add(TPrjctSurveyEntity.create(prjctIdx, survey, modUser, modDt)); continue; } TPrjctSurveyEntity entity = existingMap.get(survey.getPrjctSurveyIdx()); if (entity == null || !Objects.equals(entity.getPrjctIdx(), prjctIdx)) { throw BusinessException.badRequest("PROJECT_SURVEY_NOT_FOUND", "프로젝트 설문을 찾을 수 없습니다.") .with("prjctSurveyIdx", survey.getPrjctSurveyIdx()); } entity.updateFrom(survey, modUser, modDt); saveTargets.add(entity); } if (!saveTargets.isEmpty()) { List savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets); replacePrjctSurveyIdxToken(savedTargets); resolveSurveyUrls(savedTargets, ctx); } } private void replacePrjctSurveyIdxToken(List surveys) { for (TPrjctSurveyEntity survey : surveys) { String surveyUrl = survey.getSurveyUrl(); Long prjctSurveyIdx = survey.getPrjctSurveyIdx(); if (surveyUrl == null || prjctSurveyIdx == null || !surveyUrl.contains(PRJCT_SURVEY_IDX_TOKEN)) { continue; } survey.setSurveyUrl(surveyUrl.replace(PRJCT_SURVEY_IDX_TOKEN, prjctSurveyIdx.toString())); } } private void resolveSurveyUrls(List surveys, RequestUserContext ctx) { for (TPrjctSurveyEntity survey : surveys) { ResolvedSurveyUrl resolved = resolveSurveyUrl(survey, ctx); if (resolved == null) { continue; } survey.setSurveyUrl(resolved.finalUrl()); survey.setSurveyFullUrl(resolved.fullUrl()); survey.setSurveyShortUrl(resolved.shortUrl()); } } private ResolvedSurveyUrl resolveSurveyUrl(TPrjctSurveyEntity survey, RequestUserContext ctx) { String requestedUrl = survey.getSurveyUrl(); if (requestedUrl == null || requestedUrl.isBlank()) { survey.setSurveyFullUrl(null); survey.setSurveyShortUrl(null); return null; } String baseUrl = resolveSurveyBaseUrl(survey); if (baseUrl == null) { survey.setSurveyFullUrl(null); survey.setSurveyShortUrl(null); return null; } String queryString = extractQueryString(requestedUrl); String fullUrl = appendQueryString(baseUrl, queryString); String shortUrl = shortUrlApiClient.createShortUrl(baseUrl, ctx) .map(url -> appendQueryString(url, queryString)) .orElse(null); return new ResolvedSurveyUrl(shortUrl == null ? fullUrl : shortUrl, fullUrl, shortUrl); } private String resolveSurveyBaseUrl(TPrjctSurveyEntity survey) { String surveyUrl = survey.getSurveyUrl(); String surveyPrjctCd = survey.getSurveyPrjctCd(); Long prjctSurveyIdx = survey.getPrjctSurveyIdx(); if (surveyUrl == null || surveyPrjctCd == null || surveyPrjctCd.isBlank() || prjctSurveyIdx == null) { return null; } if (surveyUrl.contains(KON_URL_TOKEN)) { return KON_SURVEY_BASE_URL + surveyPrjctCd + "/INDEX.asp?psidx=" + prjctSurveyIdx; } if (surveyUrl.contains(KIWI_URL_TOKEN)) { return KIWI_SURVEY_BASE_URL + surveyPrjctCd + "/INDEX.asp?psidx=" + prjctSurveyIdx; } return null; } private String extractQueryString(String url) { int queryIndex = url.indexOf('?'); if (queryIndex < 0 || queryIndex + 1 >= url.length()) { return ""; } return url.substring(queryIndex + 1); } private String appendQueryString(String baseUrl, String queryString) { if (queryString == null || queryString.isBlank()) { return baseUrl; } return baseUrl + (baseUrl.contains("?") ? "&" : "?") + queryString; } private record ResolvedSurveyUrl(String finalUrl, String fullUrl, String shortUrl) { } private boolean isTeamUserRole(Integer userRole) { return userRole != null && userRole >= ContactConstant.RESEARCHER_USER_ROLE && userRole < ContactConstant.RESEARCHER_USER_ROLE + 1000; } private String makePrjctCd(String itrntPrjctCd) { String prefix = itrntPrjctCd + "_"; List sameItrnt = projectRepository.findByItrntPrjctCd(itrntPrjctCd); int maxSubCode = sameItrnt.stream() .map(TPrjctEntity::getPrjctCd) .filter(Objects::nonNull) .filter(cd -> cd.startsWith(prefix)) .map(cd -> cd.substring(prefix.length())) .filter(s -> s.matches("\\d+")) .mapToInt(Integer::parseInt) .max() .orElse(0); return prefix + String.format("%03d", maxSubCode + 1); } }