refactor: 回忆改用独立存储与请求响应 DTO,服务按域拆包
This commit is contained in:
+296
@@ -0,0 +1,296 @@
|
||||
package com.guo.learningprogresstracker.service.recall;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot;
|
||||
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSource;
|
||||
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceUnit;
|
||||
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeInput;
|
||||
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeSnapshot;
|
||||
import com.guo.learningprogresstracker.entity.BaseEntity;
|
||||
import com.guo.learningprogresstracker.entity.MarkerEntity;
|
||||
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
|
||||
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
|
||||
import com.guo.learningprogresstracker.entity.TaskEntity;
|
||||
import com.guo.learningprogresstracker.enums.TagCombineModeEnum;
|
||||
import com.guo.learningprogresstracker.exception.RecallBusinessException;
|
||||
import com.guo.learningprogresstracker.mapper.MarkerMapper;
|
||||
import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper;
|
||||
import com.guo.learningprogresstracker.mapper.StudyReportsMapper;
|
||||
import com.guo.learningprogresstracker.mapper.TaskApplicationMapper;
|
||||
import com.guo.learningprogresstracker.mapper.TasksMapper;
|
||||
import com.guo.learningprogresstracker.utils.TagScopeTool;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RecallReferenceLoader {
|
||||
private final TasksMapper tasks;
|
||||
private final StudyReportFragmentsMapper fragments;
|
||||
private final StudyReportsMapper reports;
|
||||
private final TaskApplicationMapper applications;
|
||||
private final MarkerMapper markers;
|
||||
|
||||
public ScopeSnapshot scope(ScopeInput input) {
|
||||
if (input == null || input.tags() == null) {
|
||||
invalid();
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
if ("TASK".equals(input.type())) {
|
||||
if (input.taskNum() == null
|
||||
|| input.taskNum().isBlank()
|
||||
|| !input.tags().isEmpty()
|
||||
|| input.combineMode() != null) {
|
||||
invalid();
|
||||
}
|
||||
TaskEntity task =
|
||||
tasks.selectOne(Wrappers.<TaskEntity>lambdaQuery().eq(TaskEntity::getTaskNum, input.taskNum()));
|
||||
if (task == null) {
|
||||
throw new RecallBusinessException("SCOPE_INVALID", "这个任务已不可用,请重新选择范围");
|
||||
}
|
||||
return new ScopeSnapshot(
|
||||
"TASK", input.taskNum(), List.of(), List.of(), null, input.taskNum(), task.getTaskName(), now);
|
||||
}
|
||||
if (!"TAG".equals(input.type()) || input.taskNum() != null) {
|
||||
invalid();
|
||||
}
|
||||
String scopeKey = tagScopeKey(input.tags(), input.combineMode());
|
||||
List<String> tags = TagScopeTool.canonicalTags(input.tags());
|
||||
List<String> normalized = TagScopeTool.normalizedTags(tags);
|
||||
ScopeSnapshot scope = new ScopeSnapshot(
|
||||
"TAG", null, tags, normalized, input.combineMode(), scopeKey, String.join(" / ", tags), now);
|
||||
if (!valid(scope)) {
|
||||
throw new RecallBusinessException("SCOPE_INVALID", "这些标签已没有可用碎片,请重新选择范围");
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
|
||||
/** Same input validation and normalization for creation and historical filtering; no current-source lookup. */
|
||||
public static String tagScopeKey(List<String> tags, String combineMode) {
|
||||
if (tags == null
|
||||
|| tags.isEmpty()
|
||||
|| tags.size() > 10
|
||||
|| !Set.of("UNION", "INTERSECT").contains(combineMode == null ? "" : combineMode)) {
|
||||
invalid();
|
||||
}
|
||||
for (String tag : tags) {
|
||||
if (tag == null
|
||||
|| tag.trim().isEmpty()
|
||||
|| tag.trim().length() > 255
|
||||
|| tag.chars().anyMatch(Character::isISOControl)) {
|
||||
invalid();
|
||||
}
|
||||
}
|
||||
return TagScopeTool.scopeKey(tags, TagCombineModeEnum.valueOf(combineMode));
|
||||
}
|
||||
|
||||
public boolean valid(ScopeSnapshot scope) {
|
||||
if ("TASK".equals(scope.type())) {
|
||||
return tasks.exists(Wrappers.<TaskEntity>lambdaQuery().eq(TaskEntity::getTaskNum, scope.taskNum()));
|
||||
}
|
||||
Set<String> actual = new HashSet<>();
|
||||
Set<String> accessible = new HashSet<>();
|
||||
for (StudyReportFragmentsEntity f : fragments.selectList(
|
||||
Wrappers.<StudyReportFragmentsEntity>lambdaQuery().select(StudyReportFragmentsEntity::getId))) {
|
||||
accessible.add(f.getId().toString());
|
||||
}
|
||||
for (MarkerEntity marker : actualMarkers()) {
|
||||
if (accessible.contains(marker.getObjectNum())) {
|
||||
actual.add(TagScopeTool.normalize(marker.getMarkerName()));
|
||||
}
|
||||
}
|
||||
return actual.containsAll(scope.normalizedTags());
|
||||
}
|
||||
|
||||
private List<MarkerEntity> actualMarkers() {
|
||||
return markers.selectList(Wrappers.<MarkerEntity>lambdaQuery()
|
||||
.eq(MarkerEntity::getObjectType, "FRAGMENT")
|
||||
.eq(MarkerEntity::getKind, "USER"));
|
||||
}
|
||||
|
||||
public List<StudyReportFragmentsEntity> selectedFragments(ScopeSnapshot scope) {
|
||||
if ("TASK".equals(scope.type())) {
|
||||
return fragments.selectList(Wrappers.<StudyReportFragmentsEntity>lambdaQuery()
|
||||
.eq(StudyReportFragmentsEntity::getOwnerTaskNum, scope.taskNum())
|
||||
.orderByAsc(StudyReportFragmentsEntity::getId));
|
||||
}
|
||||
Map<String, Set<String>> matches = new HashMap<>();
|
||||
for (MarkerEntity marker : actualMarkers()) {
|
||||
String key = TagScopeTool.normalize(marker.getMarkerName());
|
||||
if (scope.normalizedTags().contains(key)) {
|
||||
matches.computeIfAbsent(marker.getObjectNum(), k -> new HashSet<>())
|
||||
.add(key);
|
||||
}
|
||||
}
|
||||
List<Integer> ids = matches.entrySet().stream()
|
||||
.filter(e -> "UNION".equals(scope.combineMode())
|
||||
|| e.getValue().size() == scope.normalizedTags().size())
|
||||
.map(e -> parseId(e.getKey()))
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
return ids.isEmpty()
|
||||
? List.of()
|
||||
: fragments.selectList(Wrappers.<StudyReportFragmentsEntity>lambdaQuery()
|
||||
.in(StudyReportFragmentsEntity::getId, ids)
|
||||
.orderByAsc(StudyReportFragmentsEntity::getId));
|
||||
}
|
||||
|
||||
public ReferenceSnapshot snapshot(ScopeSnapshot scope) {
|
||||
List<ReferenceSource> sources = new ArrayList<>();
|
||||
for (StudyReportFragmentsEntity f : selectedFragments(scope)) {
|
||||
sources.add(source(
|
||||
"FRAGMENT",
|
||||
f.getId().toString(),
|
||||
"知识碎片",
|
||||
text(f.getContent()),
|
||||
f,
|
||||
new SourceContext("PRIMARY", f.getContextType(), f.getContextNum(), List.of())));
|
||||
}
|
||||
List<ReferenceUnit> units = new ArrayList<>();
|
||||
for (ReferenceSource s : sources) {
|
||||
units.addAll(units(s));
|
||||
}
|
||||
return new ReferenceSnapshot(
|
||||
units.isEmpty() ? "EMPTY" : "AVAILABLE", sources, units, List.of("资料可能有遗漏或相互冲突,不作为标准答案。"));
|
||||
}
|
||||
|
||||
/** 复习参考资料只取知识碎片;旧文档里冻结的学习报告与应用场景来源不计入摘要与分页。 */
|
||||
public static List<ReferenceSource> knowledgeSources(List<ReferenceSource> sources) {
|
||||
if (sources == null) {
|
||||
return List.of();
|
||||
}
|
||||
return sources.stream().filter(s -> "FRAGMENT".equals(s.type())).toList();
|
||||
}
|
||||
|
||||
public static String reportContent(StudyReportsEntity r) {
|
||||
return "会话摘要\n" + text(r.getSessionSummary()) + "\n预期达成判断\n" + text(r.getExpectationVerdict()) + "\n自由总结\n"
|
||||
+ text(r.getFreeSummary());
|
||||
}
|
||||
|
||||
private static String text(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
/** 来源在本次回忆里的位置:角色、上下文、以及相关的其他来源。 */
|
||||
public record SourceContext(String role, String contextType, String contextNum, List<String> related) {}
|
||||
|
||||
public static ReferenceSource source(
|
||||
String type, String id, String title, String content, BaseEntity entity, SourceContext context) {
|
||||
return new ReferenceSource(
|
||||
type.toLowerCase(Locale.ROOT) + ":" + id,
|
||||
type,
|
||||
id,
|
||||
title,
|
||||
content,
|
||||
context.role(),
|
||||
context.contextType(),
|
||||
context.contextNum(),
|
||||
context.related(),
|
||||
"AVAILABLE");
|
||||
}
|
||||
/** Java offsets are UTF16; paragraph windows never split a surrogate pair. */
|
||||
public static List<ReferenceUnit> units(ReferenceSource s) {
|
||||
List<ReferenceUnit> units = new ArrayList<>();
|
||||
String text = s.content();
|
||||
int start = 0;
|
||||
while (start < text.length()) {
|
||||
int newline = text.indexOf('\n', start);
|
||||
int paragraphEnd = newline < 0 ? text.length() : newline + 1;
|
||||
while (start < paragraphEnd) {
|
||||
int end = Math.min(start + 1000, paragraphEnd);
|
||||
if (end < text.length()
|
||||
&& Character.isHighSurrogate(text.charAt(end - 1))
|
||||
&& Character.isLowSurrogate(text.charAt(end))) {
|
||||
end--;
|
||||
}
|
||||
String part = text.substring(start, end);
|
||||
if (!part.isBlank()) {
|
||||
units.add(new ReferenceUnit(
|
||||
s.sourceId() + ":" + start, s.sourceId(), start, end, part, s.role(), "AVAILABLE"));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
return units;
|
||||
}
|
||||
|
||||
public boolean accessible(ReferenceSource source) {
|
||||
return accessible(source.type(), source.entityId());
|
||||
}
|
||||
|
||||
public boolean accessible(String type, String entityId) {
|
||||
Integer id = parseId(entityId);
|
||||
if (id == null) {
|
||||
return false;
|
||||
}
|
||||
return switch (type) {
|
||||
case "FRAGMENT" -> fragments.selectById(id) != null;
|
||||
case "REPORT" -> reports.selectById(id) != null;
|
||||
case "APPLICATION" -> applications.selectById(id) != null;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public ReferenceSource entry(String type, String id) {
|
||||
Integer key = parseId(id);
|
||||
if (key == null) {
|
||||
throw new RecallBusinessException("NOT_FOUND", "这份内容已不可用,请重新打开入口");
|
||||
}
|
||||
if ("FRAGMENT".equals(type)) {
|
||||
StudyReportFragmentsEntity f = fragments.selectById(key);
|
||||
if (f != null) {
|
||||
return source(
|
||||
type,
|
||||
id,
|
||||
"知识碎片",
|
||||
text(f.getContent()),
|
||||
f,
|
||||
new SourceContext("CONTEXT", f.getContextType(), f.getContextNum(), List.of()));
|
||||
}
|
||||
}
|
||||
if ("REPORT".equals(type)) {
|
||||
StudyReportsEntity r = reports.selectById(key);
|
||||
if (r != null) {
|
||||
return source(
|
||||
type,
|
||||
id,
|
||||
"学习报告",
|
||||
reportContent(r),
|
||||
r,
|
||||
new SourceContext("CONTEXT", "SESSION", r.getSessionNum(), List.of()));
|
||||
}
|
||||
}
|
||||
throw new RecallBusinessException("NOT_FOUND", "这份内容已不可用,请重新打开入口");
|
||||
}
|
||||
|
||||
public void touch(ReferenceSource s) {
|
||||
if ("FRAGMENT".equals(s.type())) {
|
||||
fragments.update(
|
||||
null,
|
||||
Wrappers.<StudyReportFragmentsEntity>lambdaUpdate()
|
||||
.eq(StudyReportFragmentsEntity::getId, parseId(s.entityId()))
|
||||
.set(StudyReportFragmentsEntity::getLastReviewedTime, java.time.LocalDateTime.now()));
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer parseId(String text) {
|
||||
try {
|
||||
return Integer.valueOf(text);
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void invalid() {
|
||||
throw new RecallBusinessException("INVALID_INPUT", "请检查所选任务或标签范围");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user