Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.devkor.ifive.nadab.domain.typereport.application;

import com.devkor.ifive.nadab.domain.typereport.core.content.TypeEmotionStatsContent;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeReportContentFormat;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeTextContent;
import com.devkor.ifive.nadab.domain.typereport.core.dto.TypeReportGenerationRequestedEventDto;
import com.devkor.ifive.nadab.domain.typereport.core.dto.TypeReserveResultDto;
Expand Down Expand Up @@ -114,6 +115,16 @@ public void confirmType(
String persona2Title,
String persona2Content
) {
validateContentFormat(
typeAnalysis,
typeAnalysisContent,
emotionSummaryContent,
persona1Title,
persona1Content,
persona2Title,
persona2Content
);

TypeTextContent normalizedTypeAnalysisContent = typeAnalysisContent.normalized();
TypeTextContent normalizedEmotionSummaryContent = emotionSummaryContent.normalized();
TypeEmotionStatsContent normalizedEmotionStats = emotionStats.normalized();
Expand Down Expand Up @@ -156,6 +167,29 @@ public void confirmType(
crystalLogRepository.markConfirmed(logId);
}

private void validateContentFormat(
String typeAnalysis,
TypeTextContent typeAnalysisContent,
TypeTextContent emotionSummaryContent,
String persona1Title,
String persona1Content,
String persona2Title,
String persona2Content
) {
if (TypeReportContentFormat.containsUnsupportedMarkup(typeAnalysis)
|| TypeReportContentFormat.containsUnsupportedMarkup(typeAnalysisContent)
|| TypeReportContentFormat.containsUnsupportedMarkup(emotionSummaryContent)) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_AI_SEGMENT_INVALID);
}

if (TypeReportContentFormat.containsUnsupportedMarkup(persona1Title)
|| TypeReportContentFormat.containsUnsupportedMarkup(persona1Content)
|| TypeReportContentFormat.containsUnsupportedMarkup(persona2Title)
|| TypeReportContentFormat.containsUnsupportedMarkup(persona2Content)) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_PERSONAS_INVALID);
}
}

public void failAndRefundType(Long userId, Long reportId, Long logId) {
typeReportRepository.markFailed(reportId, TypeReportStatus.FAILED);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.devkor.ifive.nadab.domain.typereport.application.mapper;

import com.devkor.ifive.nadab.domain.typereport.api.dto.response.TypeReportResponse;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeReportContentFormat;
import com.devkor.ifive.nadab.domain.typereport.core.entity.AnalysisType;
import com.devkor.ifive.nadab.domain.typereport.core.entity.TypeReport;

Expand All @@ -19,10 +20,10 @@ public static TypeReportResponse toResponse(TypeReport report, AnalysisType anal
report.getTypeAnalysisContent(),
report.getEmotionSummaryContent(),
report.getEmotionStats(),
report.getPersona1Title(),
report.getPersona1Content(),
report.getPersona2Title(),
report.getPersona2Content(),
TypeReportContentFormat.sanitizeLegacyMarkup(report.getPersona1Title()),
TypeReportContentFormat.sanitizeLegacyMarkup(report.getPersona1Content()),
TypeReportContentFormat.sanitizeLegacyMarkup(report.getPersona2Title()),
TypeReportContentFormat.sanitizeLegacyMarkup(report.getPersona2Content()),
typeImageUrl // 위에서 처리했으므로 그대로 전달 (nullable)
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.devkor.ifive.nadab.domain.typereport.core.content;

import com.devkor.ifive.nadab.global.shared.reportcontent.Segment;

import java.util.regex.Pattern;

public final class TypeReportContentFormat {

private static final Pattern UNSUPPORTED_MARKS_TAG =
Pattern.compile("<\\s*/?\\s*marks?\\b", Pattern.CASE_INSENSITIVE);
private static final Pattern LEGACY_MARKS_TAG = Pattern.compile(
"<\\s*marks?\\s+text=\"([^\"]*)\"\\s+marks=\\[[^\\]]*]\\s*/?>",
Pattern.CASE_INSENSITIVE
);

private TypeReportContentFormat() {}

public static boolean containsUnsupportedMarkup(String text) {
return text != null && UNSUPPORTED_MARKS_TAG.matcher(text).find();
}

public static String sanitizeLegacyMarkup(String text) {
return text == null ? null : LEGACY_MARKS_TAG.matcher(text).replaceAll("$1");
}

public static boolean containsUnsupportedMarkup(TypeTextContent content) {
if (content == null || content.styledText() == null || content.styledText().segments() == null) {
return false;
}

return content.styledText().segments().stream()
.filter(segment -> segment != null)
.map(Segment::text)
.anyMatch(TypeReportContentFormat::containsUnsupportedMarkup);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.devkor.ifive.nadab.domain.typereport.application.helper.TypeReportInputAssembler;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeContentFactory;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeReportContentFormat;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeEmotionStatsContent;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeTextContent;
import com.devkor.ifive.nadab.domain.typereport.core.dto.AnalysisTypeCandidateDto;
Expand Down Expand Up @@ -157,6 +158,12 @@ private void validate(TypeReportContentDto dto, String expectedAnalysisTypeCode)
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_JSON_MISSING_FIELDS);
}

if (TypeReportContentFormat.containsUnsupportedMarkup(dto.typeAnalysis())
|| TypeReportContentFormat.containsUnsupportedMarkup(dto.typeAnalysisContent())
|| TypeReportContentFormat.containsUnsupportedMarkup(dto.emotionSummaryContent())) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_AI_SEGMENT_INVALID);
}

List<TypeReportContentDto.PersonaDto> personas = dto.personas();
if (personas == null || personas.size() != PERSONA_COUNT) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_PERSONA_COUNT_INVALID);
Expand All @@ -172,6 +179,11 @@ private void validate(TypeReportContentDto dto, String expectedAnalysisTypeCode)
if (contentLen < PERSONA_CONTENT_MIN || contentLen > PERSONA_CONTENT_MAX) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_PERSONA_CONTENT_LENGTH_INVALID);
}

if (TypeReportContentFormat.containsUnsupportedMarkup(p.title())
|| TypeReportContentFormat.containsUnsupportedMarkup(p.content())) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_PERSONAS_INVALID);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.devkor.ifive.nadab.global.shared.reportcontent.Mark;
import com.devkor.ifive.nadab.global.shared.reportcontent.Segment;
import com.devkor.ifive.nadab.global.shared.reportcontent.StyledText;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeReportContentFormat;
import com.devkor.ifive.nadab.domain.typereport.core.content.TypeTextContent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonParseException;
Expand Down Expand Up @@ -140,10 +141,14 @@ private LlmGenerationResult<JsonNode> enforceLength(JsonNode raw) {

boolean badP1 = false, badP2 = false;
if (personasArr.size() >= 1) {
badP1 = isOutOfRange(getPersonaContent(personasArr.get(0)).length(), MIN_PERSONA_CONTENT, MAX_PERSONA_CONTENT);
String personaContent = getPersonaContent(personasArr.get(0));
badP1 = isOutOfRange(personaContent.length(), MIN_PERSONA_CONTENT, MAX_PERSONA_CONTENT)
|| TypeReportContentFormat.containsUnsupportedMarkup(personaContent);
}
if (personasArr.size() >= 2) {
badP2 = isOutOfRange(getPersonaContent(personasArr.get(1)).length(), MIN_PERSONA_CONTENT, MAX_PERSONA_CONTENT);
String personaContent = getPersonaContent(personasArr.get(1));
badP2 = isOutOfRange(personaContent.length(), MIN_PERSONA_CONTENT, MAX_PERSONA_CONTENT)
|| TypeReportContentFormat.containsUnsupportedMarkup(personaContent);
}

if (!badTA && !badP1 && !badP2) return new LlmGenerationResult<>(root, LlmTokenUsage.empty());
Expand Down Expand Up @@ -207,6 +212,9 @@ private LlmGenerationResult<JsonNode> enforceLength(JsonNode raw) {
: ErrorCode.TYPE_REPORT_REWRITE_PERSONA_2_LENGTH_INVALID
);
}
if (TypeReportContentFormat.containsUnsupportedMarkup(c)) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_PERSONAS_INVALID);
}
}

return new LlmGenerationResult<>(root, tokenUsage);
Expand Down Expand Up @@ -257,6 +265,10 @@ private void validateStyledText(StyledText styledText, boolean isTypeAnalysis) {

String text = segment.text();

if (TypeReportContentFormat.containsUnsupportedMarkup(text)) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_AI_SEGMENT_INVALID);
}

if (!isTypeAnalysis && text.contains("\n") || text.contains("\r")) {
throw new AiResponseParseException(ErrorCode.TYPE_REPORT_AI_SEGMENT_INVALID);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.devkor.ifive.nadab.domain.typereport.application;

import com.devkor.ifive.nadab.domain.typereport.core.content.TypeContentFactory;
import com.devkor.ifive.nadab.domain.typereport.core.repository.TypeReportRepository;
import com.devkor.ifive.nadab.domain.typereport.core.service.PendingTypeReportService;
import com.devkor.ifive.nadab.domain.wallet.core.repository.CrystalLogRepository;
import com.devkor.ifive.nadab.domain.wallet.core.repository.UserWalletRepository;
import com.devkor.ifive.nadab.global.core.response.ErrorCode;
import com.devkor.ifive.nadab.global.exception.ai.AiResponseParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationEventPublisher;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verifyNoInteractions;

@ExtendWith(MockitoExtension.class)
class TypeReportTxServiceTest {

@Mock
PendingTypeReportService pendingTypeReportService;

@Mock
TypeReportRepository typeReportRepository;

@Mock
UserWalletRepository userWalletRepository;

@Mock
CrystalLogRepository crystalLogRepository;

@Mock
ApplicationEventPublisher eventPublisher;

TypeReportTxService service;

@BeforeEach
void setUp() {
service = new TypeReportTxService(
pendingTypeReportService,
typeReportRepository,
userWalletRepository,
crystalLogRepository,
eventPublisher,
new ObjectMapper()
);
}

@Test
void confirmType_rejects_unsupported_marks_tag_before_updating_report() {
String malformedPersonaContent = "본문 <marks text=\"강조\" marks=[\"BOLD\",\"HIGHLIGHT\"]>";

assertThatThrownBy(() -> service.confirmType(
49L,
1L,
null,
"TYPE_A",
"유형 설명",
TypeContentFactory.fromPlainText("유형 설명"),
TypeContentFactory.emptyText(),
TypeContentFactory.emptyEmotionStats(),
"내면의 균형",
malformedPersonaContent,
"상황 적응 전략",
"정상 본문"
)).isInstanceOfSatisfying(AiResponseParseException.class, exception ->
assertThat(exception.getErrorCode()).isEqualTo(ErrorCode.TYPE_REPORT_PERSONAS_INVALID));

verifyNoInteractions(typeReportRepository, crystalLogRepository);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.devkor.ifive.nadab.domain.typereport.application.mapper;

import com.devkor.ifive.nadab.domain.typereport.api.dto.response.TypeReportResponse;
import com.devkor.ifive.nadab.domain.typereport.core.entity.TypeReport;
import com.devkor.ifive.nadab.domain.typereport.core.entity.TypeReportStatus;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class TypeReportMapperTest {

@Test
void toResponse_sanitizes_legacy_marks_tags_in_persona_content() {
TypeReport report = mock(TypeReport.class);
when(report.getStatus()).thenReturn(TypeReportStatus.COMPLETED);
when(report.getPersona1Content()).thenReturn(
"운동으로 자기 관리를 이어가며, "
+ "<marks text=\"내적 만족감을 높여요\" marks=[\"BOLD\",\"HIGHLIGHT\"]>."
);
when(report.getPersona2Content()).thenReturn(
"이는 <marks text=\"변화에 대한 긍정적 태도\" marks=[\"BOLD\",\"HIGHLIGHT\"]>를 바탕으로 해요."
);

TypeReportResponse response = TypeReportMapper.toResponse(report, null, null);

assertThat(response.personaContent1())
.isEqualTo("운동으로 자기 관리를 이어가며, 내적 만족감을 높여요.");
assertThat(response.personaContent2())
.isEqualTo("이는 변화에 대한 긍정적 태도를 바탕으로 해요.");
}
}
Loading
Loading