develop #25

Merged
gitadmin merged 3 commits from develop into master 2026-09-22 15:23:56 +09:00
5 changed files with 242 additions and 26 deletions

View File

@@ -0,0 +1,111 @@
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.contact-survey.enabled:false}")
private boolean enabled;
@Value("${kri.contact-survey.kon-url}")
private String konBaseUrl;
@Value("${kri.contact-survey.kiwi-url}")
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
) {
if (!enabled) {
return;
}
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.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;
@@ -23,8 +25,10 @@ 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.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -47,7 +51,6 @@ public class ProjectService {
private static final List<Short> STATUS_0_1 = List.of((short) 0, (short) 1);
private static final List<Short> 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/";
@@ -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<ProjectSurveyDto> surveys,
String modUser,
@@ -303,6 +314,13 @@ public class ProjectService {
(left, right) -> left,
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()
.map(ProjectSurveyDto::getPrjctSurveyIdx)
@@ -331,22 +349,63 @@ public class ProjectService {
entity.updateFrom(survey, modUser, modDt);
saveTargets.add(entity);
}
List<TPrjctSurveyEntity> savedTargets = List.of();
if (!saveTargets.isEmpty()) {
List<TPrjctSurveyEntity> savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets);
replacePrjctSurveyIdxToken(savedTargets);
savedTargets = projectSurveyRepository.saveAllAndFlush(saveTargets);
resolveSurveyUrls(savedTargets, ctx);
}
return createSurveyMappingSyncPlan(existingMappingMap, savedTargets);
}
private void replacePrjctSurveyIdxToken(List<TPrjctSurveyEntity> surveys) {
for (TPrjctSurveyEntity survey : surveys) {
String surveyUrl = survey.getSurveyUrl();
Long prjctSurveyIdx = survey.getPrjctSurveyIdx();
if (surveyUrl == null || prjctSurveyIdx == null || !surveyUrl.contains(PRJCT_SURVEY_IDX_TOKEN)) {
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;
}
survey.setSurveyUrl(surveyUrl.replace(PRJCT_SURVEY_IDX_TOKEN, prjctSurveyIdx.toString()));
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 resolveSurveyUrls(List<TPrjctSurveyEntity> surveys, RequestUserContext ctx) {
@@ -378,7 +437,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 +450,23 @@ public class ProjectService {
return new ResolvedSurveyUrl(finalUrl, fullUrl);
}
private boolean isSameSurveyTarget(String previousFullUrl, String baseUrl) {
return previousFullUrl != null
&& !containsPsidxParameter(previousFullUrl)
&& (previousFullUrl.equals(baseUrl)
|| previousFullUrl.startsWith(baseUrl + "?")
|| previousFullUrl.startsWith(baseUrl + "&"));
}
private boolean containsPsidxParameter(String url) {
int queryIndex = url.indexOf('?');
if (queryIndex < 0 || queryIndex + 1 >= url.length()) {
return false;
}
return Arrays.stream(url.substring(queryIndex + 1).split("&"))
.anyMatch(this::isPsidxParameter);
}
// 토큰이 남아있으면 최초 저장, KON/KIWI full URL로 시작하면 short 미발급 상태이므로,
// 둘 다 아니면 이미 발급된 short URL(재저장)로 간주한다.
private boolean isResolvedShortUrl(String requestedUrl) {
@@ -402,32 +478,25 @@ public class ProjectService {
private String resolveSurveyBaseUrl(TPrjctSurveyEntity survey) {
String surveyPrjctCd = survey.getSurveyPrjctCd();
Long prjctSurveyIdx = survey.getPrjctSurveyIdx();
if (surveyPrjctCd == null || surveyPrjctCd.isBlank() || prjctSurveyIdx == null) {
if (surveyPrjctCd == null || surveyPrjctCd.isBlank()) {
return null;
}
if (isKonSurvey(survey)) {
return KON_SURVEY_BASE_URL + surveyPrjctCd + "/INDEX.asp?psidx=" + prjctSurveyIdx;
return KON_SURVEY_BASE_URL + surveyPrjctCd + "/INDEX.asp";
}
if (isKiwiSurvey(survey)) {
return KIWI_SURVEY_BASE_URL + surveyPrjctCd + "/INDEX.asp?psidx=" + prjctSurveyIdx;
return KIWI_SURVEY_BASE_URL + surveyPrjctCd + "/INDEX.asp";
}
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) {
@@ -435,7 +504,15 @@ public class ProjectService {
if (queryIndex < 0 || queryIndex + 1 >= url.length()) {
return "";
}
return url.substring(queryIndex + 1);
return Arrays.stream(url.substring(queryIndex + 1).split("&"))
.filter(parameter -> !isPsidxParameter(parameter))
.collect(Collectors.joining("&"));
}
private boolean isPsidxParameter(String parameter) {
int equalsIndex = parameter.indexOf('=');
String name = equalsIndex < 0 ? parameter : parameter.substring(0, equalsIndex);
return name.equalsIgnoreCase("psidx");
}
private String stripQueryString(String url) {
@@ -453,6 +530,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<SurveyMapping> deleteMappings,
List<SurveyMapping> insertMappings
) {
}
private boolean isTeamUserRole(Integer userRole) {
return userRole != null
&& userRole >= ContactConstant.RESEARCHER_USER_ROLE

View File

@@ -4,6 +4,11 @@ kri:
noti-hub: https://noti-hub.kric.com/api/v1
short-url: https://short-url.kric.com/api/v1
contact-survey:
enabled: false
kon-url: https://kon.kric.com
kiwi-url: https://kon.kiwisurvey.kr
spring:
datasource:
#private 도메인

View File

@@ -6,6 +6,11 @@ kri:
noti-hub: https://noti-hub.kric.com/api/v1
short-url: https://short-url.kric.com/api/v1
contact-survey:
enabled: false
kon-url: http://localhost:8088
kiwi-url: http://localhost:8099
spring:
datasource:
#public 도메인

View File

@@ -4,6 +4,11 @@ kri:
noti-hub: https://noti-hub.kric.com/api/v1
short-url: https://short-url.kric.com/api/v1
contact-survey:
enabled: true
kon-url: https://kon.kric.com
kiwi-url: https://kon.kiwisurvey.kr
spring:
datasource:
#private 도메인