276 lines
11 KiB
Java
276 lines
11 KiB
Java
package com.kri.kart.server.service;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.kri.common.feature.json.JsonUtil;
|
|
import com.kri.common.feature.web.BusinessException;
|
|
import com.kri.common.feature.web.RequestUserContext;
|
|
import com.kri.kart.server.common.enums.ProjectType;
|
|
import com.kri.kart.server.dto.derived.DerivedCalculationDto;
|
|
import com.kri.kart.server.dto.derived.DerivedDefinitionDto;
|
|
import com.kri.kart.server.dto.derived.DerivedSaveRequestDto;
|
|
import com.kri.kart.server.dto.project.ProjectRefDto;
|
|
import com.kri.kart.server.persistence.repository.DerivedRepository;
|
|
import com.kri.kart.server.service.derived.DerivedComputationService;
|
|
import java.util.List;
|
|
import java.util.Objects;
|
|
import java.util.function.Supplier;
|
|
import org.springframework.beans.factory.annotation.Qualifier;
|
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.PlatformTransactionManager;
|
|
import org.springframework.transaction.support.TransactionTemplate;
|
|
|
|
@Service
|
|
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
|
|
public class DerivedManagementService {
|
|
private final DerivedRepository derivedRepository;
|
|
private final QuestionService questionService;
|
|
private final DerivedComputationService derivedComputationService;
|
|
private final LogService logService;
|
|
private final ObjectMapper objectMapper;
|
|
private final PlatformTransactionManager konTransactionManager;
|
|
private final PlatformTransactionManager konkiwiTransactionManager;
|
|
|
|
public DerivedManagementService(
|
|
DerivedRepository derivedRepository,
|
|
QuestionService questionService,
|
|
DerivedComputationService derivedComputationService,
|
|
LogService logService,
|
|
ObjectMapper objectMapper,
|
|
@Qualifier("konTransactionManager") PlatformTransactionManager konTransactionManager,
|
|
@Qualifier("konkiwiTransactionManager")
|
|
PlatformTransactionManager konkiwiTransactionManager) {
|
|
this.derivedRepository = derivedRepository;
|
|
this.questionService = questionService;
|
|
this.derivedComputationService = derivedComputationService;
|
|
this.logService = logService;
|
|
this.objectMapper = objectMapper;
|
|
this.konTransactionManager = konTransactionManager;
|
|
this.konkiwiTransactionManager = konkiwiTransactionManager;
|
|
}
|
|
|
|
public String save(
|
|
ProjectRefDto project,
|
|
String originId,
|
|
DerivedSaveRequestDto request,
|
|
RequestUserContext ctx) {
|
|
requireRole(ctx);
|
|
validateId(request.variableId());
|
|
if (originId != null) {
|
|
validateId(originId);
|
|
}
|
|
var definition = derivedComputationService.definition(request);
|
|
return transaction(
|
|
project,
|
|
() -> {
|
|
requireProject(project);
|
|
var original = originId == null ? null : requireDefinition(project, originId);
|
|
if (original != null) {
|
|
requireTeam(original, ctx);
|
|
}
|
|
// An update that keeps its ID cannot collide; raw DATA keys with that ID are ignored.
|
|
boolean sameId = originId != null && originId.equalsIgnoreCase(definition.getQid());
|
|
if (!sameId && derivedRepository.duplicate(project, definition.getQid(), originId)) {
|
|
throw BusinessException.conflict("DERIVED_ID_DUPLICATE", "이미 사용 중인 변수 ID입니다.");
|
|
}
|
|
if (derivedRepository.save(
|
|
project, definition, originId, ctx.getUserTeam(), ctx.getUserId())
|
|
!= 1) {
|
|
throw BusinessException.conflict("DERIVED_CHANGED", "파생변수 상태가 변경되었습니다.");
|
|
}
|
|
if (original != null && !original.getQid().equals(definition.getQid())) {
|
|
derivedRepository.clearData(project, original.getQid());
|
|
}
|
|
calculate(project, definition, null, derivedIds(derivedRepository.definitions(project)));
|
|
var content = objectMapper.createObjectNode();
|
|
content.set("NEW", objectMapper.valueToTree(definition));
|
|
if (original != null) {
|
|
content.set("ORIGIN", objectMapper.valueToTree(original));
|
|
}
|
|
logService.writeSiteLog(
|
|
project,
|
|
original == null ? "Insert Derived Variable" : "Update Derived Variable",
|
|
content,
|
|
ctx);
|
|
return definition.getQid();
|
|
});
|
|
}
|
|
|
|
public boolean delete(ProjectRefDto project, String qid, RequestUserContext ctx) {
|
|
requireRole(ctx);
|
|
validateId(qid);
|
|
return transaction(
|
|
project,
|
|
() -> {
|
|
requireProject(project);
|
|
var original = requireDefinition(project, qid);
|
|
requireTeam(original, ctx);
|
|
var content =
|
|
objectMapper.createObjectNode().set("ORIGIN", objectMapper.valueToTree(original));
|
|
logService.writeSiteLog(project, "Delete Derived Variable", content, ctx);
|
|
derivedRepository.shiftOrder(project, original.getQid());
|
|
if (derivedRepository.delete(project, original.getQid()) != 1) {
|
|
throw BusinessException.conflict("DERIVED_CHANGED", "파생변수 상태가 변경되었습니다.");
|
|
}
|
|
derivedRepository.clearData(project, original.getQid());
|
|
return true;
|
|
});
|
|
}
|
|
|
|
public DerivedCalculationDto recalculate(
|
|
ProjectRefDto project, String qid, RequestUserContext ctx) {
|
|
requireRole(ctx);
|
|
if (qid != null) {
|
|
validateId(qid);
|
|
}
|
|
return transaction(
|
|
project,
|
|
() -> {
|
|
requireProject(project);
|
|
List<DerivedDefinitionDto> definitions =
|
|
qid == null
|
|
? derivedRepository.definitions(project)
|
|
: List.of(requireDefinition(project, qid));
|
|
var derivedIds =
|
|
derivedIds(qid == null ? definitions : derivedRepository.definitions(project));
|
|
int matched = 0;
|
|
for (var definition : definitions) {
|
|
matched += calculate(project, definition, null, derivedIds);
|
|
}
|
|
if (qid == null) {
|
|
logService.writeSiteLog(
|
|
project,
|
|
"Update All Derived Variable",
|
|
objectMapper.createObjectNode().put("COUNT", Integer.toString(definitions.size())),
|
|
ctx);
|
|
}
|
|
return new DerivedCalculationDto(definitions.size(), matched);
|
|
});
|
|
}
|
|
|
|
public DerivedCalculationDto recalculateRespondent(ProjectRefDto project, String idkey) {
|
|
if (idkey == null || idkey.isBlank() || idkey.length() > 512) {
|
|
throw BusinessException.badRequest("응답자 ID를 확인해 주세요.");
|
|
}
|
|
return transaction(
|
|
project,
|
|
() -> {
|
|
requireProject(project);
|
|
// Legacy creates an empty DERIVED_DATA row even if there is no eligible
|
|
// response.
|
|
derivedRepository.ensureRespondent(project, idkey);
|
|
var definitions = derivedRepository.definitions(project);
|
|
var derivedIds = derivedIds(definitions);
|
|
int matched = 0;
|
|
for (var definition : definitions) {
|
|
matched += calculate(project, definition, idkey, derivedIds);
|
|
}
|
|
return new DerivedCalculationDto(definitions.size(), matched);
|
|
});
|
|
}
|
|
|
|
/** Stored derived variable IDs; uploaded response columns with these IDs are not imported. */
|
|
public List<String> derivedIds(ProjectRefDto project) {
|
|
return derivedIds(derivedRepository.definitions(project));
|
|
}
|
|
|
|
/**
|
|
* Recalculates every definition after a data upload. It joins the caller's KON/KONKIWI
|
|
* transaction, so a failure rolls back the upload; no role check or extra audit log applies.
|
|
*/
|
|
public DerivedCalculationDto recalculateAfterImport(ProjectRefDto project) {
|
|
return transaction(
|
|
project,
|
|
() -> {
|
|
var definitions = derivedRepository.definitions(project);
|
|
var derivedIds = derivedIds(definitions);
|
|
int matched = 0;
|
|
for (var definition : definitions) {
|
|
matched += calculate(project, definition, null, derivedIds);
|
|
}
|
|
return new DerivedCalculationDto(definitions.size(), matched);
|
|
});
|
|
}
|
|
|
|
private List<String> derivedIds(List<DerivedDefinitionDto> definitions) {
|
|
return definitions.stream().map(DerivedDefinitionDto::getQid).toList();
|
|
}
|
|
|
|
private int calculate(
|
|
ProjectRefDto project,
|
|
DerivedDefinitionDto definition,
|
|
String idkey,
|
|
List<String> derivedIds) {
|
|
validateId(definition.getQid());
|
|
if (idkey == null) {
|
|
derivedRepository.clearData(project, definition.getQid());
|
|
} else {
|
|
derivedRepository.clearRespondentData(project, definition.getQid(), idkey);
|
|
}
|
|
var data =
|
|
idkey == null
|
|
? derivedRepository.responses(project)
|
|
: derivedRepository.respondentResponses(project, idkey);
|
|
var results =
|
|
derivedComputationService.calculate(
|
|
definition, questionService.list(project, idkey == null ? 0 : 1001), data, derivedIds);
|
|
int matched = 0;
|
|
for (int i = 0; i < data.size(); i++) {
|
|
var group = results.get(i);
|
|
derivedRepository.saveData(
|
|
project,
|
|
definition.getQid(),
|
|
data.get(i).getIdkey(),
|
|
group.isEmpty() ? null : JsonUtil.toJson(objectMapper, group));
|
|
if (!group.isEmpty()) {
|
|
matched++;
|
|
}
|
|
}
|
|
return matched;
|
|
}
|
|
|
|
private void requireProject(ProjectRefDto project) {
|
|
if (derivedRepository.lockProject(project) == null) {
|
|
throw BusinessException.notFound("PROJECT_NOT_FOUND", "프로젝트를 찾을 수 없습니다.");
|
|
}
|
|
}
|
|
|
|
private DerivedDefinitionDto requireDefinition(ProjectRefDto project, String qid) {
|
|
var definition = derivedRepository.find(project, qid);
|
|
if (definition == null) {
|
|
throw BusinessException.notFound("DERIVED_NOT_FOUND", "파생변수를 찾을 수 없습니다.");
|
|
}
|
|
validateId(definition.getQid());
|
|
return definition;
|
|
}
|
|
|
|
private void requireRole(RequestUserContext ctx) {
|
|
if (ctx.getUserRole() == null || ctx.getUserRole() >= 9001) {
|
|
throw BusinessException.forbidden("DERIVED_ROLE_REQUIRED", "파생변수 관리 권한이 필요합니다.");
|
|
}
|
|
}
|
|
|
|
private void requireTeam(DerivedDefinitionDto definition, RequestUserContext ctx) {
|
|
if (!Integer.valueOf(1001).equals(ctx.getUserRole())
|
|
&& (ctx.getUserTeam() == null || ctx.getUserTeam().isBlank()
|
|
|| !ctx.getUserTeam().equals(definition.getGkey()))) {
|
|
throw BusinessException.forbidden("DERIVED_TEAM_REQUIRED", "본인 팀의 파생변수만 수정·삭제할 수 있습니다.");
|
|
}
|
|
}
|
|
|
|
private void validateId(String qid) {
|
|
if (qid == null || !qid.matches("[A-Za-z][A-Za-z0-9_]{0,127}")) {
|
|
throw BusinessException.badRequest("파생변수 ID 형식을 확인해 주세요.");
|
|
}
|
|
}
|
|
|
|
private <T> T transaction(ProjectRefDto project, Supplier<T> action) {
|
|
var transactionTemplate =
|
|
new TransactionTemplate(
|
|
project.projectType() == ProjectType.KON
|
|
? konTransactionManager
|
|
: konkiwiTransactionManager);
|
|
return Objects.requireNonNull(transactionTemplate.execute(status -> action.get()));
|
|
}
|
|
}
|