feat: 回忆去掉结束状态,新增按标签查相关导图

- 删除 status/endedAt 与结束接口,回忆只能继续编辑,用时继续累计
- 新增 review_recall_scope_tags 索引表与回填迁移,按标签交集查询保存导图
- 新增 GET /review/recalls/related,分页在 SQL 完成;列表支持 excludeRecallNum
- 范围匹配不到知识碎片时拒绝开始回忆(SCOPE_EMPTY)
This commit is contained in:
2026-11-22 21:41:31 +08:00
parent cf3fa6418b
commit cf7518c320
23 changed files with 944 additions and 125 deletions
@@ -2,17 +2,18 @@ package com.guo.learningprogresstracker.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.CreateRecallRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.EndRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallPage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceContent;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferencePage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RelatedRecallPage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ResumeRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.SaveDraftRequest;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.service.ai.RecallJson;
import com.guo.learningprogresstracker.service.recall.ReviewRecallService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -39,14 +40,28 @@ public class ReviewRecallController {
public CommonResult<RecallPage> list(
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "20") int pageSize,
@RequestParam(required = false) String status,
@RequestParam(required = false) String scopeType,
@RequestParam(required = false) String taskNum,
@RequestParam org.springframework.util.MultiValueMap<String, String> query,
@RequestParam(required = false) String combineMode) {
@RequestParam MultiValueMap<String, String> query,
@RequestParam(required = false) String combineMode,
@RequestParam(required = false) String excludeRecallNum) {
// Read repeated values verbatim: a comma can be part of a single tag name.
return CommonResult.success(
service.list(pageNum, pageSize, status, scopeType, taskNum, query.get("tags"), combineMode));
return CommonResult.success(service.list(
pageNum, pageSize, scopeType, taskNum, query.get("tags"), combineMode, excludeRecallNum));
}
/**
* 总览「相关导图」:按所选标签查保存过的导图。
*
* <p>标签用重复参数传({@code ?tags=A&tags=B}),与列表一致:逗号可能是标签名的一部分。
* 路径写在 {@code /{recallNum}} 之前,避免被单条回忆的详情路由抢走。</p>
*/
@GetMapping("/related")
public CommonResult<RelatedRecallPage> related(
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam MultiValueMap<String, String> query) {
return CommonResult.success(service.related(pageNum, pageSize, query.get("tags")));
}
@GetMapping("/{recallNum}")
@@ -77,11 +92,6 @@ public class ReviewRecallController {
return CommonResult.success(service.source(recallNum, sourceId));
}
@PostMapping("/{recallNum}/end")
public CommonResult<RecallDetail> end(@PathVariable String recallNum, @RequestBody JsonNode body) {
return CommonResult.success(service.end(recallNum, json.readInput(body, EndRequest.class)));
}
@DeleteMapping("/{recallNum}")
public CommonResult<Void> delete(@PathVariable String recallNum) {
service.delete(recallNum);
@@ -53,9 +53,6 @@ public final class RecallDtos {
public record SaveDraftRequest(
String clientRequestId, String editorId, String writeToken, Expression expression, Timing timing) {}
public record EndRequest(
String clientRequestId, String editorId, String writeToken, Expression expression, Timing timing) {}
public record AiParams(int schemaVersion, String requestId, String editorId, String writeToken, String hintForm) {}
public record ReferenceSource(
@@ -159,19 +156,22 @@ public final class RecallDtos {
public record RecallPage(long current, long size, long total, List<RecallSummary> records) {}
/** 相关导图的一行:回忆摘要 + 它与所选标签的交集(归一化名)。 */
public record RelatedRecallSummary(RecallSummary recall, List<String> matchedTags) {}
public record RelatedRecallPage(int current, int size, long total, List<RelatedRecallSummary> records) {}
public record BusinessError(String reason) {}
@Data
public static class RecallSummary {
private String recallNum;
private String status;
private ScopeSnapshot scope;
private String scopeStatus;
private long activeDurationMs;
private Long actualDurationMs;
private Instant createdAt;
private Instant updatedAt;
private Instant endedAt;
}
@Data
@@ -0,0 +1,10 @@
package com.guo.learningprogresstracker.dto.recall;
import lombok.Data;
/** 「相关导图」分页查询的行:只带回忆号与命中标签数,排序与分页由 SQL 决定,Java 侧不再重排。 */
@Data
public class RelatedRecallRow {
private String recallNum;
private long matchedTagCount;
}
@@ -15,7 +15,6 @@ public class ReviewRecallEntity extends BaseEntity {
private String scopeType;
private String taskNum;
private String scopeKey;
private String status;
private Long activeDurationMs;
private String documentJson;
}
@@ -0,0 +1,17 @@
package com.guo.learningprogresstracker.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/** 复习总览「相关导图」的查询索引:一条回忆 × 一个归一化标签一行,随回忆的创建与删除同步维护。 */
@Data
@TableName("review_recall_scope_tags")
public class ReviewRecallScopeTagEntity extends BaseEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String recallNum;
private String normalizedTag;
}
@@ -0,0 +1,30 @@
package com.guo.learningprogresstracker.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.guo.learningprogresstracker.dto.recall.RelatedRecallRow;
import com.guo.learningprogresstracker.entity.ReviewRecallScopeTagEntity;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ReviewRecallScopeTagMapper extends BaseMapper<ReviewRecallScopeTagEntity> {
/**
* 「相关导图」的总数:与所选标签至少命中一个的标签范围回忆数(每行回忆只算一次)。
*
* <p>语句见 {@code resources/mapper/ReviewRecallScopeTagMapper.xml};租户条件由拦截器追加到外层回忆表。</p>
*
* @param tags 已归一化的标签,调用方保证 1–10 个且非空
*/
long countRelated(@Param("tags") List<String> tags);
/**
* 「相关导图」当前页:命中标签多的排前面,同分按更新时间从新到旧、id 兜底保证翻页稳定。
*
* <p>{@code LIMIT/OFFSET} 由分页拦截器生成,Java 侧不截取;总数另走 {@link #countRelated},
* 故传进来的 {@code page} 需要关掉自动 COUNT。</p>
*/
IPage<RelatedRecallRow> selectRelated(IPage<RelatedRecallRow> page, @Param("tags") List<String> tags);
}
@@ -0,0 +1,135 @@
package com.guo.learningprogresstracker.service.recall;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDocument;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RelatedRecallPage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RelatedRecallSummary;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeSnapshot;
import com.guo.learningprogresstracker.dto.recall.RelatedRecallRow;
import com.guo.learningprogresstracker.entity.ReviewRecallEntity;
import com.guo.learningprogresstracker.exception.RecallBusinessException;
import com.guo.learningprogresstracker.mapper.ReviewRecallMapper;
import com.guo.learningprogresstracker.mapper.ReviewRecallScopeTagMapper;
import com.guo.learningprogresstracker.mapstruct.RecallConvert;
import com.guo.learningprogresstracker.utils.TagScopeTool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 复习总览「相关导图」:按所选标签查保存过的导图。
*
* <p>候选、命中标签数、排序与分页全在 SQL 里({@link ReviewRecallScopeTagMapper}):
* 命中标签多的排前面,同分按更新时间从新到旧。这里只做参数校验、按页内顺序回表解析文档,
* 以及跳过旧版本读不出来的文档(并把它从总数里去掉,与回忆列表一致)。</p>
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class RecallRelatedQuery {
private final ReviewRecallScopeTagMapper scopeTags;
private final ReviewRecallMapper recalls;
private final ReviewRecallStore store;
private final RecallReferenceLoader loader;
private final RecallConvert convert;
/**
* @param tags 重复参数原样传入,大小写与首尾空白不限,此处统一归一化
*/
public RelatedRecallPage related(int pageNum, int pageSize, List<String> tags) {
List<String> normalized = relatedTags(pageNum, pageSize, tags);
store.lock();
long total = scopeTags.countRelated(normalized);
// LIMIT / OFFSET 由分页拦截器生成;总数已单独查过,关掉自动 COUNT 免得同一条件查两遍
IPage<RelatedRecallRow> page = scopeTags.selectRelated(new Page<>(pageNum, pageSize, false), normalized);
Map<String, ReviewRecallEntity> byNum = entities(page.getRecords());
Set<String> selected = new HashSet<>(normalized);
List<RecallDocument> readable = new ArrayList<>();
long skipped = 0;
for (RelatedRecallRow row : page.getRecords()) {
ReviewRecallEntity entity = byNum.get(row.getRecallNum());
if (entity == null) {
skipped++;
continue;
}
try {
readable.add(store.parse(entity));
} catch (RecallBusinessException e) {
if (!"STORED_DATA_INVALID".equals(e.getData().reason())) {
throw e;
}
skipped++;
log.warn("[回忆] 相关导图已删除旧版本或不兼容文档: recallNum={}", row.getRecallNum());
}
}
RecallReferenceLoader.SourceIndex index = loader.index(readable);
List<RelatedRecallSummary> items = new ArrayList<>();
for (RecallDocument doc : readable) {
store.reconcile(doc, index);
items.add(new RelatedRecallSummary(convert.toSummary(store.summary(doc)), matchedTags(doc, selected)));
}
return new RelatedRecallPage(pageNum, pageSize, Math.max(0, total - skipped), items);
}
/** 按 SQL 给出的行序一次取回当前页的回忆实体:不再逐行 selectOne。 */
private Map<String, ReviewRecallEntity> entities(List<RelatedRecallRow> rows) {
if (rows.isEmpty()) {
return Map.of();
}
List<String> nums = rows.stream().map(RelatedRecallRow::getRecallNum).toList();
List<ReviewRecallEntity> found = recalls.selectList(
Wrappers.<ReviewRecallEntity>lambdaQuery().in(ReviewRecallEntity::getRecallNum, nums));
Map<String, ReviewRecallEntity> byNum = new HashMap<>();
for (ReviewRecallEntity entity : found) {
byNum.put(entity.getRecallNum(), entity);
}
return byNum;
}
/**
* 一行命中了哪些标签:命中判定用归一化名(与查询同一口径),返回的是范围里保存的原样写法,
* 前端直接展示({@code MiXeD Tag} 不会变成 {@code mixed tag});范围里只剩归一化名时才返回归一化名。
*/
private static List<String> matchedTags(RecallDocument doc, Set<String> selected) {
ScopeSnapshot scope = doc.getDetail().getScope();
List<String> original = scope.tags() == null || scope.tags().isEmpty() ? null : scope.tags();
List<String> source = original != null ? original : scope.normalizedTags();
if (source == null) {
return List.of();
}
Set<String> matched = new LinkedHashSet<>();
for (String tag : source) {
String normalized = TagScopeTool.normalize(tag);
if (selected.contains(normalized)) {
matched.add(original != null ? tag.trim() : normalized);
}
}
return new ArrayList<>(matched);
}
/** 相关导图只接受 1–10 个标签:与一次复习可选的范围标签同一上限。 */
private static List<String> relatedTags(int pageNum, int pageSize, List<String> tags) {
if (pageNum < 1 || pageSize < 1 || pageSize > 100 || tags == null) {
RecallExpressionValidator.invalid();
}
for (String tag : tags) {
if (tag != null && (tag.trim().length() > 255 || tag.chars().anyMatch(Character::isISOControl))) {
RecallExpressionValidator.invalid();
}
}
List<String> normalized = TagScopeTool.normalizedTags(tags);
if (normalized.isEmpty() || normalized.size() > TagScopeTool.MAX_RANGE_TAGS) {
RecallExpressionValidator.invalid();
}
return normalized;
}
}
@@ -3,7 +3,6 @@ package com.guo.learningprogresstracker.service.recall;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.CreateRecallRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.EndRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.Entry;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.Expression;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ExpressionNode;
@@ -17,6 +16,7 @@ import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSource;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSourceSummary;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSummary;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.RelatedRecallPage;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ResumeRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.SaveDraftRequest;
import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeSnapshot;
@@ -33,7 +33,6 @@ import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -46,6 +45,7 @@ public class ReviewRecallService {
private final ReviewRecallStore store;
private final RecallReferenceLoader loader;
private final ReviewRecallMapper recalls;
private final RecallRelatedQuery relatedQuery;
private final RecallConvert convert;
private final RecallJson json;
private final RecallExpressionValidator validator;
@@ -62,12 +62,13 @@ public class ReviewRecallService {
throw new RecallBusinessException("INVALID_INPUT", "新复习请选择碎片上的标签范围");
}
ScopeSnapshot scope = loader.scope(r.scope());
Expression expression = previousExpression(scope);
ReferenceSnapshot reference = loader.snapshot(scope);
if (RecallReferenceLoader.knowledgeSources(reference.sources()).isEmpty()) {
throw new RecallBusinessException("SCOPE_EMPTY", "这个范围没有匹配到知识碎片,请调整标签或组合方式后再开始");
}
RecallDetail d = new RecallDetail();
Instant now = Instant.now();
d.setRecallNum("RECALL-" + UUID.randomUUID());
d.setStatus("ACTIVE");
d.setScope(scope);
d.setScopeStatus("VALID");
d.setActiveDurationMs(0);
@@ -76,7 +77,7 @@ public class ReviewRecallService {
d.setUpdatedAt(now);
d.setEditorId(r.editorId());
d.setWriteToken(UUID.randomUUID().toString());
d.setExpression(expression);
d.setExpression(emptyExpression());
d.setReference(referenceSummary(reference));
d.setRequests(new ArrayList<>());
if (r.entry() != null) {
@@ -93,46 +94,17 @@ public class ReviewRecallService {
return store.detail(doc);
}
private Expression previousExpression(ScopeSnapshot scope) {
ReviewRecallEntity previous = recalls.selectOne(Wrappers.<ReviewRecallEntity>lambdaQuery()
.eq(ReviewRecallEntity::getScopeType, "TAG")
.eq(ReviewRecallEntity::getScopeKey, scope.scopeKey())
.eq(ReviewRecallEntity::getStatus, "ENDED")
.orderByDesc(ReviewRecallEntity::getLastModifiedTime)
.orderByDesc(ReviewRecallEntity::getId)
.last("LIMIT 1"));
if (previous == null || previous.getDocumentJson() == null) {
return emptyExpression();
}
try {
return new Expression(
1,
carryContent(store.load(previous.getRecallNum())
.getDetail()
.getExpression()
.root()));
} catch (RecallBusinessException e) {
if (!"STORED_DATA_INVALID".equals(e.getData().reason())) {
throw e;
}
return emptyExpression();
}
}
/** Carried maps contain personal text, without an ever-growing chain of prior help identifiers. */
private static ExpressionNode carryContent(ExpressionNode node) {
return new ExpressionNode(
node.id(),
node.title(),
node.notes(),
List.of(),
node.style(),
node.children().stream().map(ReviewRecallService::carryContent).toList());
}
private static Expression emptyExpression() {
return new Expression(1, new ExpressionNode("root", "", "", List.of(), null, List.of()));
}
/** A recall without any matched fragment has no editor to enter; it can only stay as history. */
private static void requireKnowledge(RecallDocument doc) {
if (RecallReferenceLoader.knowledgeSources(doc.getReference().sources()).isEmpty()) {
throw new RecallBusinessException("SCOPE_EMPTY", "这个范围没有匹配到知识碎片,不能进入编辑;请重新选择范围");
}
}
private void entry(Entry entry) {
if (!Set.of("DIRECT", "FEED", "FRAGMENT", "REPORT", "LEGACY")
.contains(entry.type() == null ? "" : entry.type())) {
@@ -171,21 +143,25 @@ public class ReviewRecallService {
public RecallPage list(
int pageNum,
int pageSize,
String status,
String scopeType,
String taskNum,
List<String> tags,
String combineMode) {
String combineMode,
String excludeRecallNum) {
List<String> tagFilter = tags == null || tags.isEmpty() ? null : tags;
validateListQuery(pageNum, pageSize, status, scopeType, taskNum);
validateListQuery(pageNum, pageSize, scopeType, taskNum);
validateTagQuery(scopeType, tagFilter, combineMode);
if (excludeRecallNum != null && excludeRecallNum.length() > 64) {
RecallExpressionValidator.invalid();
}
String scopeKey = tagFilter == null ? null : RecallReferenceLoader.tagScopeKey(tagFilter, combineMode);
store.lock();
var query = Wrappers.<ReviewRecallEntity>lambdaQuery()
.eq(status != null, ReviewRecallEntity::getStatus, status)
.eq(scopeType != null, ReviewRecallEntity::getScopeType, scopeType)
.eq(taskNum != null, ReviewRecallEntity::getTaskNum, taskNum)
.eq(scopeKey != null, ReviewRecallEntity::getScopeKey, scopeKey);
.eq(scopeKey != null, ReviewRecallEntity::getScopeKey, scopeKey)
// 顶部「上次编辑」那张由 SQL 排除:前端要的是「往下数 5 条」,不能取 6 条再截
.ne(excludeRecallNum != null, ReviewRecallEntity::getRecallNum, excludeRecallNum);
// selectPage 自己会发 COUNT;再单独 selectCount 等于同一条件查两遍
Page<ReviewRecallEntity> page = recalls.selectPage(
new Page<>(pageNum, pageSize),
@@ -213,11 +189,18 @@ public class ReviewRecallService {
return new RecallPage(pageNum, pageSize, Math.max(0, page.getTotal() - removed), rows);
}
private static void validateListQuery(int pageNum, int pageSize, String status, String scopeType, String taskNum) {
/**
* 总览「相关导图」:按所选标签列出保存过的导图;查询与装配见 {@link RecallRelatedQuery}。
*/
@Transactional(rollbackFor = Exception.class)
public RelatedRecallPage related(int pageNum, int pageSize, List<String> tags) {
return relatedQuery.related(pageNum, pageSize, tags);
}
private static void validateListQuery(int pageNum, int pageSize, String scopeType, String taskNum) {
if (pageNum < 1
|| pageSize < 1
|| pageSize > 100
|| (status != null && !Set.of("ACTIVE", "ENDED").contains(status))
|| (scopeType != null && !Set.of("TASK", "TAG").contains(scopeType))
|| (taskNum != null && !"TASK".equals(scopeType))) {
RecallExpressionValidator.invalid();
@@ -238,15 +221,13 @@ public class ReviewRecallService {
store.lock();
RecallDocument doc = store.load(num);
RecallDetail d = doc.getDetail();
requireKnowledge(doc);
if (store.replay(num, "RESUME", r.clientRequestId(), r) != null) {
return store.detail(doc);
}
ReviewRecallStore.identifier(r.editorId());
if (!"ACTIVE".equals(d.getStatus())) {
RecallExpressionValidator.invalid();
}
if (!Objects.equals(d.getWriteToken(), r.writeToken())) {
ReviewRecallStore.conflict("REVISION_CONFLICT", "草稿已有更新,请保留本地输入并重新打开");
ReviewRecallStore.conflict("REVISION_CONFLICT", "这次导图已有更新,请保留本地输入并重新打开");
}
d.setEditorId(r.editorId());
doc.setEpochStartedAt(Instant.now());
@@ -262,6 +243,7 @@ public class ReviewRecallService {
public RecallDetail draft(String num, SaveDraftRequest r) {
store.lock();
RecallDocument doc = store.load(num);
requireKnowledge(doc);
ReviewRecallStore.identifier(r.clientRequestId());
String payloadHash = RecallJson.hash(json.write(r));
if (Objects.equals(doc.getLastDraftRequestId(), r.clientRequestId())) {
@@ -280,37 +262,6 @@ public class ReviewRecallService {
return store.detail(doc);
}
@Transactional(rollbackFor = Exception.class)
public RecallDetail end(String num, EndRequest r) {
return mutate(num, "END", r.clientRequestId(), r, r.editorId(), r.writeToken(), doc -> {
saveExpression(doc, r.expression());
timing(doc, r.timing());
doc.getDetail().setStatus("ENDED");
doc.getDetail().setEndedAt(Instant.now());
});
}
private RecallDetail mutate(
String num,
String op,
String id,
Object payload,
String editor,
String writeToken,
Consumer<RecallDocument> mutation) {
store.lock();
RecallDocument doc = store.load(num);
if (store.replay(num, op, id, payload) != null) {
return store.detail(doc);
}
store.guard(doc.getDetail(), editor, writeToken);
mutation.accept(doc);
store.rotateWriteToken(doc.getDetail());
store.persist(doc);
store.receipt(num, op, id, payload, null);
return store.detail(doc);
}
private void saveExpression(RecallDocument doc, Expression expression) {
validateExpression(doc, expression);
doc.getDetail().setExpression(expression);
@@ -13,13 +13,16 @@ import com.guo.learningprogresstracker.entity.AiTaskEntity;
import com.guo.learningprogresstracker.entity.ReviewRecallEntity;
import com.guo.learningprogresstracker.entity.ReviewRecallReceiptEntity;
import com.guo.learningprogresstracker.entity.ReviewRecallRequestEntity;
import com.guo.learningprogresstracker.entity.ReviewRecallScopeTagEntity;
import com.guo.learningprogresstracker.exception.RecallBusinessException;
import com.guo.learningprogresstracker.mapper.AiTaskMapper;
import com.guo.learningprogresstracker.mapper.ReviewRecallMapper;
import com.guo.learningprogresstracker.mapper.ReviewRecallReceiptMapper;
import com.guo.learningprogresstracker.mapper.ReviewRecallRequestMapper;
import com.guo.learningprogresstracker.mapper.ReviewRecallScopeTagMapper;
import com.guo.learningprogresstracker.service.ai.RecallAiClient;
import com.guo.learningprogresstracker.service.ai.RecallJson;
import com.guo.learningprogresstracker.utils.TagScopeTool;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
@@ -43,6 +46,7 @@ public class ReviewRecallStore {
private final ReviewRecallMapper recalls;
private final ReviewRecallReceiptMapper receipts;
private final ReviewRecallRequestMapper requests;
private final ReviewRecallScopeTagMapper scopeTags;
private final AiTaskMapper aiTasks;
private final RecallJson json;
private final RecallReferenceLoader references;
@@ -101,6 +105,7 @@ public class ReviewRecallStore {
.eq(ReviewRecallRequestEntity::getRecallNum, row.getRecallNum()));
receipts.delete(Wrappers.<ReviewRecallReceiptEntity>lambdaQuery()
.eq(ReviewRecallReceiptEntity::getRecallNum, row.getRecallNum()));
deleteScopeTags(row.getRecallNum());
recalls.update(
null,
Wrappers.<ReviewRecallEntity>lambdaUpdate()
@@ -113,6 +118,34 @@ public class ReviewRecallStore {
ReviewRecallEntity e = new ReviewRecallEntity();
setEntity(e, d);
recalls.insert(e);
indexScopeTags(d);
}
/**
* 相关导图索引与回忆同事务写入:唯一创建路径 {@link #insert} 维护它,绕开这条路径的写入会让总览漏图。
* 标签按归一化名去重(范围里保留的是原样写法,查询用的是归一化名)。
*/
private void indexScopeTags(RecallDocument d) {
RecallDetail v = d.getDetail();
if (!"TAG".equals(v.getScope().type())) {
return;
}
List<String> normalized = v.getScope().normalizedTags();
if (normalized == null || normalized.isEmpty()) {
normalized = TagScopeTool.normalizedTags(v.getScope().tags());
}
for (String tag : normalized) {
ReviewRecallScopeTagEntity row = new ReviewRecallScopeTagEntity();
row.setRecallNum(v.getRecallNum());
row.setNormalizedTag(tag);
scopeTags.insert(row);
}
}
/** 删除回忆时一并删索引行;@TableLogic 把它变成软删,历史行留在表里但不参与查询。 */
private void deleteScopeTags(String recallNum) {
scopeTags.delete(Wrappers.<ReviewRecallScopeTagEntity>lambdaQuery()
.eq(ReviewRecallScopeTagEntity::getRecallNum, recallNum));
}
public void persist(RecallDocument d) {
@@ -127,7 +160,6 @@ public class ReviewRecallStore {
e.setScopeType(v.getScope().type());
e.setTaskNum(v.getScope().taskNum());
e.setScopeKey(v.getScope().scopeKey());
e.setStatus(v.getStatus());
e.setActiveDurationMs(v.getActiveDurationMs());
e.setDocumentJson(json.write(d));
e.setLastModifiedTime(LocalDateTime.ofInstant(v.getUpdatedAt(), ZoneOffset.UTC));
@@ -151,15 +183,13 @@ public class ReviewRecallStore {
Wrappers.<ReviewRecallRequestEntity>lambdaQuery().eq(ReviewRecallRequestEntity::getTaskNum, taskNum));
}
/** 任意历史记录都能继续写:只校验编辑者与写令牌,记录本身没有「已结束」这种状态。 */
public void guard(RecallDetail d, String editorId, String writeToken) {
if (!"ACTIVE".equals(d.getStatus())) {
throw new RecallBusinessException("INVALID_INPUT", "这次回忆已经结束,只能回看;请开始新的回忆");
}
if (!Objects.equals(d.getEditorId(), editorId)) {
throw new RecallBusinessException("EDITOR_REPLACED", "另一页已接管编辑,请保留本地输入并重新恢复");
throw new RecallBusinessException("EDITOR_REPLACED", "另一页已接管编辑,请保留本地输入并重新进入编辑");
}
if (!Objects.equals(d.getWriteToken(), writeToken)) {
throw new RecallBusinessException("REVISION_CONFLICT", "草稿已有更新,请保留本地副本并重新打开");
throw new RecallBusinessException("REVISION_CONFLICT", "这次导图已有更新,请保留本机副本并重新打开");
}
}
@@ -335,6 +365,7 @@ public class ReviewRecallStore {
public void delete(RecallDocument doc) {
invalidateTasks(taskNums(doc));
deleteScopeTags(doc.getDetail().getRecallNum());
recalls.update(
null,
Wrappers.<ReviewRecallEntity>lambdaUpdate()