260922_01_ENH: KON, KIWI 설문 연동 시 KON, KIWI에 매핑 정보 입력 및 삭제 요청 추가

This commit is contained in:
2026-09-22 14:48:07 +09:00
parent b30f7604bf
commit 8abba997dd
5 changed files with 209 additions and 13 deletions

View File

@@ -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<String, String> headers() {
Map<String, String> 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
}
}

View File

@@ -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.PageResponseDto;
import com.kri.common.feature.web.page.Pageables; import com.kri.common.feature.web.page.Pageables;
import com.kri.contact.server.common.consts.ContactConstant; 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.common.external.shorturl.ShortUrlApiClient;
import com.kri.contact.server.dto.project.ProjectCreateRequestDto; import com.kri.contact.server.dto.project.ProjectCreateRequestDto;
import com.kri.contact.server.dto.project.ProjectInfoDto; import com.kri.contact.server.dto.project.ProjectInfoDto;
@@ -25,6 +27,7 @@ import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@@ -59,6 +62,7 @@ public class ProjectService {
private final ProjectRepository projectRepository; private final ProjectRepository projectRepository;
private final ProjectMainTemplateRepository projectMainTemplateRepository; private final ProjectMainTemplateRepository projectMainTemplateRepository;
private final ProjectSurveyRepository projectSurveyRepository; private final ProjectSurveyRepository projectSurveyRepository;
private final ContactSurveyApiClient contactSurveyApiClient;
private final ShortUrlApiClient shortUrlApiClient; private final ShortUrlApiClient shortUrlApiClient;
@Transactional @Transactional
@@ -211,10 +215,17 @@ public class ProjectService {
.with("prjctIdx", prjctIdx)); .with("prjctIdx", prjctIdx));
entity.updateFrom(req.getProjectInfo(), modUser, modDt); 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); assignService.upsertPrjctCmpnAssign(prjctIdx, req.getAssignCmpnIdList(), modUser, modDt);
resultCodeService.updateResultCode(prjctIdx, req.getResultCodeList(), modUser, modDt); resultCodeService.updateResultCode(prjctIdx, req.getResultCodeList(), modUser, modDt);
synchronizeSurveyMappings(surveyMappingSyncPlan);
} }
@Transactional @Transactional
@@ -286,7 +297,7 @@ public class ProjectService {
)); ));
} }
private void updateProjectSurveys( private SurveyMappingSyncPlan updateProjectSurveys(
Long prjctIdx, Long prjctIdx,
List<ProjectSurveyDto> surveys, List<ProjectSurveyDto> surveys,
String modUser, String modUser,
@@ -303,6 +314,13 @@ public class ProjectService {
(left, right) -> left, (left, right) -> left,
LinkedHashMap::new LinkedHashMap::new
)); ));
Map<Long, SurveyMapping> existingMappingMap = existingMap.values().stream()
.collect(Collectors.toMap(
TPrjctSurveyEntity::getPrjctSurveyIdx,
this::toSurveyMapping,
(left, right) -> left,
LinkedHashMap::new
));
Set<Long> requestedIds = requestSurveys.stream() Set<Long> requestedIds = requestSurveys.stream()
.map(ProjectSurveyDto::getPrjctSurveyIdx) .map(ProjectSurveyDto::getPrjctSurveyIdx)
@@ -331,11 +349,64 @@ public class ProjectService {
entity.updateFrom(survey, modUser, modDt); entity.updateFrom(survey, modUser, modDt);
saveTargets.add(entity); saveTargets.add(entity);
} }
List<TPrjctSurveyEntity> savedTargets = List.of();
if (!saveTargets.isEmpty()) { if (!saveTargets.isEmpty()) {
List<TPrjctSurveyEntity> savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets); savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets);
replacePrjctSurveyIdxToken(savedTargets); replacePrjctSurveyIdxToken(savedTargets);
resolveSurveyUrls(savedTargets, ctx); resolveSurveyUrls(savedTargets, ctx);
} }
return createSurveyMappingSyncPlan(existingMappingMap, savedTargets);
}
private SurveyMappingSyncPlan createSurveyMappingSyncPlan(
Map<Long, SurveyMapping> existingMappingMap,
List<TPrjctSurveyEntity> savedSurveys
) {
Map<Long, SurveyMapping> savedMappingMap = savedSurveys.stream()
.collect(Collectors.toMap(
TPrjctSurveyEntity::getPrjctSurveyIdx,
this::toSurveyMapping,
(left, right) -> right,
LinkedHashMap::new
));
Set<Long> mappingIds = new LinkedHashSet<>(existingMappingMap.keySet());
mappingIds.addAll(savedMappingMap.keySet());
List<SurveyMapping> deleteMappings = new ArrayList<>();
List<SurveyMapping> 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<TPrjctSurveyEntity> surveys) { private void replacePrjctSurveyIdxToken(List<TPrjctSurveyEntity> surveys) {
@@ -378,7 +449,7 @@ public class ProjectService {
String fullUrl = appendQueryString(baseUrl, queryString); String fullUrl = appendQueryString(baseUrl, queryString);
String finalUrl; String finalUrl;
if (isResolvedShortUrl(requestedUrl)) { if (isResolvedShortUrl(requestedUrl) && isSameSurveyTarget(survey.getSurveyFullUrl(), baseUrl)) {
// 재저장 시 이미 발급된 short URL은 재발급하지 않고 쿼리스트링만 새 요청 값으로 교체한다. // 재저장 시 이미 발급된 short URL은 재발급하지 않고 쿼리스트링만 새 요청 값으로 교체한다.
finalUrl = appendQueryString(stripQueryString(requestedUrl), queryString); finalUrl = appendQueryString(stripQueryString(requestedUrl), queryString);
} else { } else {
@@ -391,6 +462,11 @@ public class ProjectService {
return new ResolvedSurveyUrl(finalUrl, fullUrl); 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 미발급 상태이므로, // 토큰이 남아있으면 최초 저장, KON/KIWI full URL로 시작하면 short 미발급 상태이므로,
// 둘 다 아니면 이미 발급된 short URL(재저장)로 간주한다. // 둘 다 아니면 이미 발급된 short URL(재저장)로 간주한다.
private boolean isResolvedShortUrl(String requestedUrl) { private boolean isResolvedShortUrl(String requestedUrl) {
@@ -415,19 +491,13 @@ public class ProjectService {
return null; return null;
} }
// 최초 저장 시에는 surveyUrl의 토큰으로, 재저장 시에는 이미 확정된 surveyFullUrl prefix로 판별한다. // URL 문자열보다 요청 경계에서 검증된 설문 타입을 KON/KIWI 판별 기준으로 사용한다.
private boolean isKonSurvey(TPrjctSurveyEntity survey) { private boolean isKonSurvey(TPrjctSurveyEntity survey) {
String surveyUrl = survey.getSurveyUrl(); return Objects.equals(survey.getSurveyTy(), SurveyType.KON.getCode());
String surveyFullUrl = survey.getSurveyFullUrl();
return (surveyUrl != null && surveyUrl.contains(KON_URL_TOKEN))
|| (surveyFullUrl != null && surveyFullUrl.startsWith(KON_SURVEY_BASE_URL));
} }
private boolean isKiwiSurvey(TPrjctSurveyEntity survey) { private boolean isKiwiSurvey(TPrjctSurveyEntity survey) {
String surveyUrl = survey.getSurveyUrl(); return Objects.equals(survey.getSurveyTy(), SurveyType.KIWI.getCode());
String surveyFullUrl = survey.getSurveyFullUrl();
return (surveyUrl != null && surveyUrl.contains(KIWI_URL_TOKEN))
|| (surveyFullUrl != null && surveyFullUrl.startsWith(KIWI_SURVEY_BASE_URL));
} }
private String extractQueryString(String url) { private String extractQueryString(String url) {
@@ -453,6 +523,19 @@ public class ProjectService {
private record ResolvedSurveyUrl(String finalUrl, String fullUrl) { 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<SurveyMapping> deleteMappings,
List<SurveyMapping> insertMappings
) {
}
private boolean isTeamUserRole(Integer userRole) { private boolean isTeamUserRole(Integer userRole) {
return userRole != null return userRole != null
&& userRole >= ContactConstant.RESEARCHER_USER_ROLE && userRole >= ContactConstant.RESEARCHER_USER_ROLE

View File

@@ -3,6 +3,8 @@ kri:
intranet-extension: https://intranet-ext.kric.com/api/v1 intranet-extension: https://intranet-ext.kric.com/api/v1
noti-hub: https://noti-hub.kric.com/api/v1 noti-hub: https://noti-hub.kric.com/api/v1
short-url: https://short-url.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: spring:
datasource: datasource:

View File

@@ -5,6 +5,10 @@ kri:
#noti-hub: http://localhost:4011/api/v1 #noti-hub: http://localhost:4011/api/v1
noti-hub: https://noti-hub.kric.com/api/v1 noti-hub: https://noti-hub.kric.com/api/v1
short-url: https://short-url.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: spring:
datasource: datasource:

View File

@@ -3,6 +3,8 @@ kri:
intranet-extension: https://intranet-ext.kric.com/api/v1 intranet-extension: https://intranet-ext.kric.com/api/v1
noti-hub: https://noti-hub.kric.com/api/v1 noti-hub: https://noti-hub.kric.com/api/v1
short-url: https://short-url.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: spring:
datasource: datasource: