diff --git a/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java b/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java new file mode 100644 index 0000000..7d69582 --- /dev/null +++ b/src/main/java/com/kri/contact/server/common/external/contactsurvey/ContactSurveyApiClient.java @@ -0,0 +1,105 @@ +package com.kri.contact.server.common.external.contactsurvey; + +import com.kri.common.feature.http.ExternalApiClient; +import com.kri.common.feature.http.ExternalApiResponse; +import com.kri.common.feature.web.BusinessException; +import com.kri.contact.server.common.enums.SurveyType; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class ContactSurveyApiClient { + + private static final String CONTACT_SURVEY_PATH = "/include/ajax_contact.asp"; + private static final String CONTACT_SURVEY_COMMAND = "CONTACT_SURVEY"; + private static final int MAX_PKEY_LENGTH = 20; + + private final ExternalApiClient externalApiClient = new ExternalApiClient(); + + @Value("${kri.api-url.kon-contact-survey}") + private String konBaseUrl; + + @Value("${kri.api-url.kiwi-contact-survey}") + private String kiwiBaseUrl; + + @Value("${kri.auth.apikey.header-name:X-API-Key}") + private String apiKeyHeaderName; + + @Value("${kri.auth.apikey.key}") + private String apiKey; + + public void insert(SurveyType surveyType, String pkey, Long psidx) { + request(surveyType, ContactSurveyCrud.INSERT, pkey, psidx); + } + + public void delete(SurveyType surveyType, String pkey, Long psidx) { + request(surveyType, ContactSurveyCrud.DELETE, pkey, psidx); + } + + private void request( + SurveyType surveyType, + ContactSurveyCrud crud, + String pkey, + Long psidx + ) { + validate(pkey, psidx); + + String url = baseUrl(surveyType) + CONTACT_SURVEY_PATH; + String body = "CRUD=" + crud + + "&COMMAND=" + CONTACT_SURVEY_COMMAND + + "&PKEY=" + encode(pkey) + + "&PSIDX=" + psidx; + + externalApiClient.post(url, headers(), body); + } + + private String baseUrl(SurveyType surveyType) { + String baseUrl = switch (surveyType) { + case KON -> konBaseUrl; + case KIWI -> kiwiBaseUrl; + case EXTERNAL -> throw BusinessException.badRequest( + "CONTACT_SURVEY_SYSTEM_NOT_SUPPORTED", + "외부 설문은 CONTACT_SURVEY 매핑 API를 지원하지 않습니다." + ); + }; + return baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + } + + private void validate(String pkey, Long psidx) { + if (pkey == null || pkey.isBlank() || pkey.length() > MAX_PKEY_LENGTH) { + throw BusinessException.badRequest( + "CONTACT_SURVEY_INVALID_PKEY", + "설문 프로젝트 코드가 올바르지 않습니다." + ) + .with("maxLength", MAX_PKEY_LENGTH); + } + if (psidx == null || psidx < 0) { + throw BusinessException.badRequest( + "CONTACT_SURVEY_INVALID_PSIDX", + "프로젝트 설문 고유번호가 올바르지 않습니다." + ); + } + } + + private String encode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); + } + + private Map headers() { + Map headers = new HashMap<>(); + headers.put(apiKeyHeaderName, apiKey); + headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); + return headers; + } + + private enum ContactSurveyCrud { + INSERT, + DELETE + } +} diff --git a/src/main/java/com/kri/contact/server/service/ProjectService.java b/src/main/java/com/kri/contact/server/service/ProjectService.java index 8ad64e0..aeffe0e 100644 --- a/src/main/java/com/kri/contact/server/service/ProjectService.java +++ b/src/main/java/com/kri/contact/server/service/ProjectService.java @@ -6,6 +6,8 @@ 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.enums.SurveyType; +import com.kri.contact.server.common.external.contactsurvey.ContactSurveyApiClient; 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; @@ -25,6 +27,7 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -59,6 +62,7 @@ public class ProjectService { private final ProjectRepository projectRepository; private final ProjectMainTemplateRepository projectMainTemplateRepository; private final ProjectSurveyRepository projectSurveyRepository; + private final ContactSurveyApiClient contactSurveyApiClient; private final ShortUrlApiClient shortUrlApiClient; @Transactional @@ -211,10 +215,17 @@ public class ProjectService { .with("prjctIdx", prjctIdx)); entity.updateFrom(req.getProjectInfo(), modUser, modDt); - updateProjectSurveys(prjctIdx, req.getProjectInfo().getSurveys(), modUser, modDt, ctx); + SurveyMappingSyncPlan surveyMappingSyncPlan = updateProjectSurveys( + prjctIdx, + req.getProjectInfo().getSurveys(), + modUser, + modDt, + ctx + ); assignService.upsertPrjctCmpnAssign(prjctIdx, req.getAssignCmpnIdList(), modUser, modDt); resultCodeService.updateResultCode(prjctIdx, req.getResultCodeList(), modUser, modDt); + synchronizeSurveyMappings(surveyMappingSyncPlan); } @Transactional @@ -286,7 +297,7 @@ public class ProjectService { )); } - private void updateProjectSurveys( + private SurveyMappingSyncPlan updateProjectSurveys( Long prjctIdx, List surveys, String modUser, @@ -303,6 +314,13 @@ public class ProjectService { (left, right) -> left, LinkedHashMap::new )); + Map existingMappingMap = existingMap.values().stream() + .collect(Collectors.toMap( + TPrjctSurveyEntity::getPrjctSurveyIdx, + this::toSurveyMapping, + (left, right) -> left, + LinkedHashMap::new + )); Set requestedIds = requestSurveys.stream() .map(ProjectSurveyDto::getPrjctSurveyIdx) @@ -331,11 +349,64 @@ public class ProjectService { entity.updateFrom(survey, modUser, modDt); saveTargets.add(entity); } + List savedTargets = List.of(); if (!saveTargets.isEmpty()) { - List savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets); + savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets); replacePrjctSurveyIdxToken(savedTargets); resolveSurveyUrls(savedTargets, ctx); } + return createSurveyMappingSyncPlan(existingMappingMap, savedTargets); + } + + private SurveyMappingSyncPlan createSurveyMappingSyncPlan( + Map existingMappingMap, + List savedSurveys + ) { + Map savedMappingMap = savedSurveys.stream() + .collect(Collectors.toMap( + TPrjctSurveyEntity::getPrjctSurveyIdx, + this::toSurveyMapping, + (left, right) -> right, + LinkedHashMap::new + )); + + Set mappingIds = new LinkedHashSet<>(existingMappingMap.keySet()); + mappingIds.addAll(savedMappingMap.keySet()); + + List deleteMappings = new ArrayList<>(); + List insertMappings = new ArrayList<>(); + for (Long mappingId : mappingIds) { + SurveyMapping existingMapping = existingMappingMap.get(mappingId); + SurveyMapping savedMapping = savedMappingMap.get(mappingId); + if (Objects.equals(existingMapping, savedMapping)) { + continue; + } + if (existingMapping != null && existingMapping.isManaged()) { + deleteMappings.add(existingMapping); + } + if (savedMapping != null && savedMapping.isManaged()) { + insertMappings.add(savedMapping); + } + } + + return new SurveyMappingSyncPlan(deleteMappings, insertMappings); + } + + private void synchronizeSurveyMappings(SurveyMappingSyncPlan syncPlan) { + syncPlan.deleteMappings().forEach(mapping -> contactSurveyApiClient.delete( + mapping.surveyType(), mapping.pkey(), mapping.psidx() + )); + syncPlan.insertMappings().forEach(mapping -> contactSurveyApiClient.insert( + mapping.surveyType(), mapping.pkey(), mapping.psidx() + )); + } + + private SurveyMapping toSurveyMapping(TPrjctSurveyEntity survey) { + return new SurveyMapping( + SurveyType.fromCode(survey.getSurveyTy()), + survey.getSurveyPrjctCd(), + survey.getPrjctSurveyIdx() + ); } private void replacePrjctSurveyIdxToken(List surveys) { @@ -378,7 +449,7 @@ public class ProjectService { String fullUrl = appendQueryString(baseUrl, queryString); String finalUrl; - if (isResolvedShortUrl(requestedUrl)) { + if (isResolvedShortUrl(requestedUrl) && isSameSurveyTarget(survey.getSurveyFullUrl(), baseUrl)) { // 재저장 시 이미 발급된 short URL은 재발급하지 않고 쿼리스트링만 새 요청 값으로 교체한다. finalUrl = appendQueryString(stripQueryString(requestedUrl), queryString); } else { @@ -391,6 +462,11 @@ public class ProjectService { return new ResolvedSurveyUrl(finalUrl, fullUrl); } + private boolean isSameSurveyTarget(String previousFullUrl, String baseUrl) { + return previousFullUrl != null + && (previousFullUrl.equals(baseUrl) || previousFullUrl.startsWith(baseUrl + "&")); + } + // 토큰이 남아있으면 최초 저장, KON/KIWI full URL로 시작하면 short 미발급 상태이므로, // 둘 다 아니면 이미 발급된 short URL(재저장)로 간주한다. private boolean isResolvedShortUrl(String requestedUrl) { @@ -415,19 +491,13 @@ public class ProjectService { return null; } - // 최초 저장 시에는 surveyUrl의 토큰으로, 재저장 시에는 이미 확정된 surveyFullUrl prefix로 판별한다. + // URL 문자열보다 요청 경계에서 검증된 설문 타입을 KON/KIWI 판별 기준으로 사용한다. private boolean isKonSurvey(TPrjctSurveyEntity survey) { - String surveyUrl = survey.getSurveyUrl(); - String surveyFullUrl = survey.getSurveyFullUrl(); - return (surveyUrl != null && surveyUrl.contains(KON_URL_TOKEN)) - || (surveyFullUrl != null && surveyFullUrl.startsWith(KON_SURVEY_BASE_URL)); + return Objects.equals(survey.getSurveyTy(), SurveyType.KON.getCode()); } private boolean isKiwiSurvey(TPrjctSurveyEntity survey) { - String surveyUrl = survey.getSurveyUrl(); - String surveyFullUrl = survey.getSurveyFullUrl(); - return (surveyUrl != null && surveyUrl.contains(KIWI_URL_TOKEN)) - || (surveyFullUrl != null && surveyFullUrl.startsWith(KIWI_SURVEY_BASE_URL)); + return Objects.equals(survey.getSurveyTy(), SurveyType.KIWI.getCode()); } private String extractQueryString(String url) { @@ -453,6 +523,19 @@ public class ProjectService { private record ResolvedSurveyUrl(String finalUrl, String fullUrl) { } + private record SurveyMapping(SurveyType surveyType, String pkey, Long psidx) { + + private boolean isManaged() { + return surveyType == SurveyType.KON || surveyType == SurveyType.KIWI; + } + } + + private record SurveyMappingSyncPlan( + List deleteMappings, + List insertMappings + ) { + } + private boolean isTeamUserRole(Integer userRole) { return userRole != null && userRole >= ContactConstant.RESEARCHER_USER_ROLE diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index b88e822..6ce9c3a 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -3,6 +3,8 @@ kri: intranet-extension: https://intranet-ext.kric.com/api/v1 noti-hub: https://noti-hub.kric.com/api/v1 short-url: https://short-url.kric.com/api/v1 + kon-contact-survey: https://kon.kric.com + kiwi-contact-survey: https://kon.kiwisurvey.kr spring: datasource: diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml index 11b6030..d851840 100644 --- a/src/main/resources/application-local.yml +++ b/src/main/resources/application-local.yml @@ -5,6 +5,10 @@ kri: #noti-hub: http://localhost:4011/api/v1 noti-hub: https://noti-hub.kric.com/api/v1 short-url: https://short-url.kric.com/api/v1 + kon-contact-survey: https://kon.kric.com + kiwi-contact-survey: https://kon.kiwisurvey.kr + #kon-contact-survey: http://localhost:8088 + #kiwi-contact-survey: http://localhost:8099 spring: datasource: diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index 393bbe2..8449827 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -3,6 +3,8 @@ kri: intranet-extension: https://intranet-ext.kric.com/api/v1 noti-hub: https://noti-hub.kric.com/api/v1 short-url: https://short-url.kric.com/api/v1 + kon-contact-survey: https://kon.kric.com + kiwi-contact-survey: https://kon.kiwisurvey.kr spring: datasource: