diff --git a/.agents/notes/implemented/architecture/2026-11-16-current-recall-storage.md b/.agents/notes/implemented/architecture/2026-11-16-current-recall-storage.md index 08dc5b6..e692b84 100644 --- a/.agents/notes/implemented/architecture/2026-11-16-current-recall-storage.md +++ b/.agents/notes/implemented/architecture/2026-11-16-current-recall-storage.md @@ -34,6 +34,8 @@ AI 执行期间可以暂存一份提交输入,以便重启接手和结果引 本篇维护当前内容存储、范围匹配、写入保护、临时 AI 输入和删除迁移。[前端工作区决策](../../../../../lpt-fe/.agents/notes/implemented/feature/2026-11-16-current-recall-workspace.md)维护入口与交互,[AI 协议决策](../../../../../lpt-ai/.agents/notes/implemented/architecture/2026-11-16-recall-strict-protocol.md)维护严格输出和调用预算。三篇部分相关,分别保留;[租户隔离](2026-05-27-tenant-line-row-isolation.md)和[计费规则](2026-10-10-ai-usage-accounting-rules.md)继续维护各自决定。 +[2026-11-22 的决定](2026-11-22-recall-map-without-status.md)取代了本篇的两条内容:新建回忆不再自动带入同范围已结束导图,回忆记录也不再区分进行中/已结束(`status`、`endedAt` 与结束接口均已删除);其余当前内容存储规则仍以本篇为准。 + ## Alternatives considered - 只隐藏编号和历史入口:可以复用已有异步绑定,改动面较小;但后端仍保存编辑过程,与只保留当前内容的业务要求冲突,因此删除整个内容版本模型。 @@ -50,7 +52,7 @@ AI 执行期间可以暂存一份提交输入,以便重启接手和结果引 ## Verification -- `ReviewRecallServiceIntegrationTest` 校验多次覆盖后先前正文不再落盘、同范围自动带入、范围差异、租户隔离、资料分页,以及 AI 终态清除临时输入。 +- `ReviewRecallServiceIntegrationTest` 校验多次覆盖后先前正文不再落盘、同范围新建仍空白、范围差异、租户隔离、资料分页,以及 AI 终态清除临时输入。 - `ReviewRecallControllerIntegrationTest` 校验无版本 DTO、原文读取与旧请求拒绝;`RecallAiResultValidatorTest` 校验引用是否确实来自本次输入。异步结果不能覆盖后续编辑由服务集成测试验证。 - `RecallStorageMigrationTest` 验证重建存储并删除旧记录、保留任务标准导图和标签导图。迁移在 H2 的 MySQL 模式执行;`MigrationIndexKeyLengthTest` 额外复算 InnoDB 索引键长度,不能替代真实 MySQL 的 DDL 验证。 - 使用 JDK 17 运行 `./mvnw clean test`。 diff --git a/.agents/notes/implemented/architecture/2026-11-22-recall-map-without-status.md b/.agents/notes/implemented/architecture/2026-11-22-recall-map-without-status.md new file mode 100644 index 0000000..2909192 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-22-recall-map-without-status.md @@ -0,0 +1,66 @@ +# Agent Note: 自由回忆去掉状态与自动带入,任意历史记录都能继续编辑 + +Status: implemented + +## Problem + +自由回忆曾把一条记录分成「进行中(ACTIVE)」与「已结束(ENDED)」两种状态:`status` 既落库成列、又进 `RecallDetail`, +还带一个 `endedAt` 字段和 `POST /review/recalls/{num}/end` 端点。只有 `ENDED` 的记录才会被「同范围自动带入」选中, +只有 `ACTIVE` 的记录才允许恢复(`resume`)和保存草稿(`PUT /draft`)。 + +这套状态带来的是纯粹的摩擦,没有对应的业务收益: + +- **用户视角没有「结束」这个动作。** 想再改昨天的回忆,记录已经是 `ENDED`,只能开始新的一次; + 而新记录又把上次的导图整棵复制过来,于是旧记录变成一份再也碰不到的副本。 +- **自动带入把两条记录耦合成一条链。** 复制只发生在「同范围最近一条已结束」记录上,用户看到的新空白图取决于 + 是谁先点了结束,行为难以解释;资料、提示与耗时却按本次重新开始,复制过来的节点算不上同一次回忆。 +- **状态是第四个写入保护维度。** 编辑者(`editorId`)与写令牌(`writeToken`)已经解决多页面覆盖, + `status` 只是再多一条会在恢复与保存之间产生「已经结束,只能回看」这种前后矛盾的拒绝。 + +## Decision + +自由回忆不再有状态,任意历史记录都能继续编辑: + +- 新建回忆永远从空白根节点开始,不再查询「同范围最近已完成导图」;`previousExpression` / `carryContent` 删除。 +- `RecallDetail`(含列表 `RecallSummary`)不再有 `status` 与 `endedAt`;`EndRequest` 与 `POST /review/recalls/{num}/end` 删除; + 列表接口不再接受 `status` 查询参数。 +- 任意记录都能 `POST /resume` 接管编辑:恢复只重置计时编辑段并轮换 `writeToken`;`PUT /draft` 继续可用, + 有效时间与实际用时继续累计到同一条记录。 +- `ReviewRecallStore.guard` 只校验 `editorId` + `writeToken`,`setEntity` 不再写 `status`;`ReviewRecallEntity` 去掉该字段。 +- `V20261122_1__drop_recall_status.sql` 先删含 `status` 的索引 `idx_recall_user_scope_status`,再 `DROP COLUMN status`, + 最后按去掉 `status` 的列顺序重建 `idx_recall_user_scope (created_by, scope_type, scope_key, deleted, last_modified_time, id)`。 + 旧 `document_json` 里的 `detail.status` / `detail.endedAt` 由 `RecallJson.readStored` 的「忽略未知字段」自然丢弃, + 不做回填 JSON 的迁移。 +- 主动查漏的输入不变:仍是当前 `expression` + 本次 `reference.units`,历史导图从不发送给 AI。 + +## Alternatives considered + +- **保留 `status` 但允许 `ENDED` 记录继续编辑。** 改动最小,`resume` 里去掉一条校验即可;但 `status` 与 `endedAt` + 会继续出现在 API 契约和数据库里,用户和前端要一直维护一个不再影响行为的字段,等于把废弃字段当契约留着。 +- **把 `status` 换成「已完成/未完成」的展示派生值(例如「最后修改时间早于 N 天」)。** 可以让列表看起来有分组; + 但这是前端可以自己算的展示口径,落到后端只是把同一条状态的维护成本换了个名字,且没有任何写入规则依赖它。 +- **保留自动带入但改成「带入最近一条同范围记录」。** 能让用户接着上次的图;但复制来的节点与本次资料、本次提示不对应, + 且用户无法选择不复制(新回忆只能是复制品),因此直接取消带入,需要接着写时打开原记录继续编辑即可。 + +## Consequences + +收益是契约与数据库各少一列、少一个端点、少一次「同范围历史查询」,恢复与保存不再互相否定;展示与写入规则只剩 +`editorId` / `writeToken` 一层,与既有的多页面覆盖语义一致。 + +代价是: + +- **删除列不可逆。** 代码回退到带 `status` 的版本会因缺列直接报错,必须与迁移同批回退或补一次新增列的回填。 +- **旧记录的含义变宽。** 以前 `ENDED` 表示「不再修改」,现在任何记录都能被接手;拿到最新写令牌的页面可以覆盖,这是既有语义。 +- **列表索引重建。** `idx_recall_user_scope` 的列顺序只服务「按范围过滤 + 最近修改排序」,不能再按 `status` 过滤; + 未指定范围时列表仍走 `idx_recall_list (created_by, deleted, last_modified_time, id)`。 + +## Verification + +- `ReviewRecallServiceIntegrationTest`:`creatingRecallAlwaysStartsFromAnEmptyRootEvenWithHistoryInScope` 覆盖同范围有历史导图时新建仍空白; + `anyHistoricalRecallResumesAndKeepsAccumulatingOnTheSameRecord` 覆盖任意记录多次恢复 + 草稿后 `activeDurationMs` / `actualDurationMs` + 在同一条记录上继续累计;其余用例去掉了结束动作与状态断言。 +- `ReviewRecallControllerIntegrationTest`:详情断言不含 `status` / `endedAt`,`anyHistoricalRecallResumesAgainAndKeepsEditing` + 覆盖同一篇记录连续恢复与恢复后保存草稿;旧的未知字段(`carryFrom`)与过期写令牌仍按 400 拒绝。 +- `RecallStorageMigrationTest` 断言迁移后 `review_recalls` 不再有 `status` 列;`MigrationIndexKeyLengthTest` 解析全部迁移文件, + 会复算重建后的 `idx_recall_user_scope` 键长(564 字节,上限 3072)。 +- 使用 JDK 17 运行 `./mvnw test`(611 个测试)。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-22-empty-scope-cannot-open-recall.md b/.agents/notes/implemented/bug-fix/2026-11-22-empty-scope-cannot-open-recall.md new file mode 100644 index 0000000..2590c20 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-22-empty-scope-cannot-open-recall.md @@ -0,0 +1,36 @@ +# Agent Note: 空范围不能创建、恢复或保存回忆 + +Status: implemented + +## Problem + +自由回忆的范围只校验「所选标签在某个碎片上存在」,没有校验「本次范围实际匹配到至少一条碎片」。多标签交集没有同时命中的碎片时,`ReferenceSnapshot` 是 `EMPTY`,但记录仍被创建、仍能进入导图编辑,随后提示和查漏每次都以 `NO_REFERENCE` 失败。用户看到的是一个能画图、却不能使用任何资料辅助的回忆。 + +线上记录 `RECALL-814013dd-2ce5-4346-af3f-3b8d887bbbce` 就是这种情况:标签 `A` 与「【体验测试】数据库事务学习(2026-11-15)」各命中 2 条碎片,交集为 0,`detail.reference` 为 `EMPTY`。 + +## Decision + +- `ReviewRecallService.create` 在取得 `ReferenceSnapshot` 后检查 `RecallReferenceLoader.knowledgeSources(reference.sources())`;为空时抛 `SCOPE_EMPTY`,不写记录。 +- `resume` 与 `draft` 在加载文档后调用同一个 `requireKnowledge` 检查;空范围记录不能接管编辑,也不能继续保存。 +- `get`、`list`、删除保持可读/可删:历史里的空范围记录仍能出现在回忆列表并删除,只是不能继续编辑。 +- `SCOPE_EMPTY` 是业务错误码,前端据此显示「重新选择范围」,不把空范围伪装成网络失败。 + +## Alternatives considered + +- **只在下一步(提示/查漏)禁用按钮**:改动最小,但用户已经进入导图、画了内容,才发现这个范围没有任何资料;这不是「不进入编辑」,只是把失败推迟。放弃。 +- **自动把交集改成并集**:能让范围立刻有碎片,但会静默改变用户选择的复习范围,也无法解释历史快照。放弃。 +- **允许进入但只读展示**:用户仍会看到一张不能继续编辑的导图,和「进入导图编辑页面」的边界不清楚;不如直接停在范围选择。放弃。 +- **删除历史空范围记录**:等于替用户清理数据,且可能连带删除用户已画的内容;保留历史、禁止编辑即可。放弃。 + +## Consequences + +- 空范围不能再产生新的回忆记录;已存在的空范围记录留在历史中,打开时由前端显示范围错误与「重新选择范围」,后端也拒绝恢复/保存。 +- 用户要使用提示或查漏,必须先调整标签或组合方式,使范围至少命中一条知识碎片。 +- 新增 `SCOPE_EMPTY` 业务码;没有数据库迁移,也没有改写既有 `document_json`。 +- 匹配到碎片但碎片正文为空的情况仍然允许进入(有碎片,只是资料没有可用文本),由提示/查漏的禁用态处理。 + +## Verification + +- `ReviewRecallServiceIntegrationTest.zeroMatchingFragmentsCannotCreateResumeOrDraft`:交集 0 时创建抛 `SCOPE_EMPTY`;把已有记录的快照改为空后,`resume` 与 `draft` 都抛 `SCOPE_EMPTY`。 +- 既有创建、恢复、计时累计、资料分页与 AI 终态测试继续通过。 +- `./mvnw test` 全绿(新增用例后 612 个测试)。 diff --git a/AGENTS.md b/AGENTS.md index 2eb4eb2..e8dc201 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,14 +78,14 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/ - entity 使用 `@TableName`、`@TableField` 映射数据库字段。 - mapStruct 承载 DTO 转换。 -## API 端点总览(86 个) +## API 端点总览(87 个) | 模块 | 端点数 | 端点 | |------|--------|------| | 登录认证 | 2 | `POST /login`, `POST /logout` | | 学习会话 | 11 | `PUT /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}`, `POST /study-sessions/{sessionNum}/study-sessions/continue`, `POST /study-sessions/{sessionNum}/study-sessions/pause`, `POST /study-sessions/{sessionNum}/study-sessions/ended`, `POST /study-sessions/{sessionNum}/study-sessions/abort`, `GET /study-sessions/{sessionNum}/all-fragments`, `GET /study-sessions/tasks/{taskNum}/fragments`, `GET /study-sessions/tasks/{taskNum}/reports`, `GET /study-sessions/active` | | 任务管理 | 15 | `GET/POST /tasks`, `GET/PUT/DELETE /tasks/{taskId}`, `GET/PUT /tasks/priority-weights`, `GET /tasks/options`, `GET/POST /tasks/{taskNum}/applications`, `PUT/DELETE /tasks/applications/{id}`, `GET /tasks/{taskNum}/study-sessions/start-or-continue`, `GET /tasks/{taskNum}/not-ended-study-session`, `GET /tasks/{taskId}/deletion-preview` | -| 复习与导图 | 19 | `GET /review/feed`, `PUT /review/feed/{fragmentId}/feedback`, `POST /review/feed/{fragmentId}/touched`, `GET /review/sort-preference`, `PUT /review/sort-preference`, `GET /review/summary`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/report/{id}/structured`, `PUT /review/report/{id}`, `DELETE /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}` | +| 复习与导图 | 20 | `GET /review/feed`, `PUT /review/feed/{fragmentId}/feedback`, `POST /review/feed/{fragmentId}/touched`, `GET /review/sort-preference`, `PUT /review/sort-preference`, `GET /review/summary`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/report/{id}/structured`, `PUT /review/report/{id}`, `DELETE /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}`, `GET /review/recalls/related` | | 标签导图 | 4 | `POST /review/tag-mind-map/query`, `PUT /review/tag-mind-map`, `GET /review/tag-mind-map/list`, `POST /review/tag-mind-map/recall-records` | | 知识碎片 | 6 | `POST /report-fragments`, `PUT /report-fragments/{id}`, `PUT /report-fragments/{id}/ownership`, `DELETE /report-fragments/{id}`, `GET /report-fragments/session/{sessionNum}`, `GET /report-fragments/pending-ownership` | | 数据导出 | 2 | `GET /export/task/{taskNum}`, `GET /export/range` | @@ -100,6 +100,10 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/ > 让前端静默隐藏入口,其余 4 个接口直接拒绝。`POST /internal/ai-usage/records` 是 lpt-ai 的上报入口, > 没有登录态,在 `WebMvcConfig` 里排除了 Sa-Token,改用 `x-api-token` 与 `lpt.ai-usage.report-token` 比对。 +> 自由回忆的 `/review/recalls` 系列(创建、列表、详情、恢复、保存、来源、删除)未在本表逐条列出。 +> 其中 `GET /review/recalls` 支持可选 `excludeRecallNum`,由 SQL 排除指定的那条回忆(最近回忆首屏用它排除顶部「上次编辑的导图」)。 +> `GET /review/recalls/related` 按所选标签(重复 `tags` 参数,1–10 个)查保存过的导图,命中标签多的在前,分页在 SQL 里完成。 + ## 数据库(11 个核心表) `users`, `tasks`, `study_sessions`, `study_reports`, `study_report_fragments`, `study_expectations`, `task_applications`, `review_standard_mind_maps`, `review_recall_records`, `user_priority_weights`, `ai_usage_records` diff --git a/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java b/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java index 41da0c0..87b0822 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java @@ -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 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 query, - @RequestParam(required = false) String combineMode) { + @RequestParam MultiValueMap 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)); + } + + /** + * 总览「相关导图」:按所选标签查保存过的导图。 + * + *

标签用重复参数传({@code ?tags=A&tags=B}),与列表一致:逗号可能是标签名的一部分。 + * 路径写在 {@code /{recallNum}} 之前,避免被单条回忆的详情路由抢走。

+ */ + @GetMapping("/related") + public CommonResult related( + @RequestParam(defaultValue = "1") int pageNum, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam MultiValueMap 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 end(@PathVariable String recallNum, @RequestBody JsonNode body) { - return CommonResult.success(service.end(recallNum, json.readInput(body, EndRequest.class))); - } - @DeleteMapping("/{recallNum}") public CommonResult delete(@PathVariable String recallNum) { service.delete(recallNum); diff --git a/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java b/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java index ce9c522..754f373 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java @@ -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 records) {} + /** 相关导图的一行:回忆摘要 + 它与所选标签的交集(归一化名)。 */ + public record RelatedRecallSummary(RecallSummary recall, List matchedTags) {} + + public record RelatedRecallPage(int current, int size, long total, List 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 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/recall/RelatedRecallRow.java b/src/main/java/com/guo/learningprogresstracker/dto/recall/RelatedRecallRow.java new file mode 100644 index 0000000..3f35f73 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/recall/RelatedRecallRow.java @@ -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; +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java index 9d350ea..c6120a3 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java @@ -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; } diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallScopeTagEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallScopeTagEntity.java new file mode 100644 index 0000000..75e0ca6 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallScopeTagEntity.java @@ -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; +} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallScopeTagMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallScopeTagMapper.java new file mode 100644 index 0000000..0ebd4f9 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallScopeTagMapper.java @@ -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 { + + /** + * 「相关导图」的总数:与所选标签至少命中一个的标签范围回忆数(每行回忆只算一次)。 + * + *

语句见 {@code resources/mapper/ReviewRecallScopeTagMapper.xml};租户条件由拦截器追加到外层回忆表。

+ * + * @param tags 已归一化的标签,调用方保证 1–10 个且非空 + */ + long countRelated(@Param("tags") List tags); + + /** + * 「相关导图」当前页:命中标签多的排前面,同分按更新时间从新到旧、id 兜底保证翻页稳定。 + * + *

{@code LIMIT/OFFSET} 由分页拦截器生成,Java 侧不截取;总数另走 {@link #countRelated}, + * 故传进来的 {@code page} 需要关掉自动 COUNT。

+ */ + IPage selectRelated(IPage page, @Param("tags") List tags); +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/RecallRelatedQuery.java b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallRelatedQuery.java new file mode 100644 index 0000000..6fd7fad --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallRelatedQuery.java @@ -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; + +/** + * 复习总览「相关导图」:按所选标签查保存过的导图。 + * + *

候选、命中标签数、排序与分页全在 SQL 里({@link ReviewRecallScopeTagMapper}): + * 命中标签多的排前面,同分按更新时间从新到旧。这里只做参数校验、按页内顺序回表解析文档, + * 以及跳过旧版本读不出来的文档(并把它从总数里去掉,与回忆列表一致)。

+ */ +@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 tags) { + List normalized = relatedTags(pageNum, pageSize, tags); + store.lock(); + long total = scopeTags.countRelated(normalized); + // LIMIT / OFFSET 由分页拦截器生成;总数已单独查过,关掉自动 COUNT 免得同一条件查两遍 + IPage page = scopeTags.selectRelated(new Page<>(pageNum, pageSize, false), normalized); + Map byNum = entities(page.getRecords()); + Set selected = new HashSet<>(normalized); + List 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 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 entities(List rows) { + if (rows.isEmpty()) { + return Map.of(); + } + List nums = rows.stream().map(RelatedRecallRow::getRecallNum).toList(); + List found = recalls.selectList( + Wrappers.lambdaQuery().in(ReviewRecallEntity::getRecallNum, nums)); + Map byNum = new HashMap<>(); + for (ReviewRecallEntity entity : found) { + byNum.put(entity.getRecallNum(), entity); + } + return byNum; + } + + /** + * 一行命中了哪些标签:命中判定用归一化名(与查询同一口径),返回的是范围里保存的原样写法, + * 前端直接展示({@code MiXeD Tag} 不会变成 {@code mixed tag});范围里只剩归一化名时才返回归一化名。 + */ + private static List matchedTags(RecallDocument doc, Set selected) { + ScopeSnapshot scope = doc.getDetail().getScope(); + List original = scope.tags() == null || scope.tags().isEmpty() ? null : scope.tags(); + List source = original != null ? original : scope.normalizedTags(); + if (source == null) { + return List.of(); + } + Set 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 relatedTags(int pageNum, int pageSize, List 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 normalized = TagScopeTool.normalizedTags(tags); + if (normalized.isEmpty() || normalized.size() > TagScopeTool.MAX_RANGE_TAGS) { + RecallExpressionValidator.invalid(); + } + return normalized; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java index e411131..222af87 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java @@ -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.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 tags, - String combineMode) { + String combineMode, + String excludeRecallNum) { List 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.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 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 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 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); diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java index a91aa8f..2b3b54c 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java @@ -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.lambdaQuery() .eq(ReviewRecallReceiptEntity::getRecallNum, row.getRecallNum())); + deleteScopeTags(row.getRecallNum()); recalls.update( null, Wrappers.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 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.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.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.lambdaUpdate() diff --git a/src/main/java/db/migration/V20261122_3__backfill_recall_scope_tags.java b/src/main/java/db/migration/V20261122_3__backfill_recall_scope_tags.java new file mode 100644 index 0000000..c69e171 --- /dev/null +++ b/src/main/java/db/migration/V20261122_3__backfill_recall_scope_tags.java @@ -0,0 +1,90 @@ +package db.migration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import org.flywaydb.core.api.migration.BaseJavaMigration; +import org.flywaydb.core.api.migration.Context; + +/** + * 回填「相关导图」索引({@code review_recall_scope_tags})。 + * + *

只处理标签范围的活回忆:TASK 范围、已软删的行、没有文档的行都不进索引。 + * 标签取自 {@code detail.scope.normalizedTags};历史文档缺这一列时用 {@code detail.scope.tags} + * 按标签字典口径(去首尾空白 + {@link Locale#ROOT} 小写)兜底。 + * 文档不可解析就跳过这一行——迁移不猜内容,也不因为它让整次启动失败。

+ * + *

逐行 LIMIT 1 取数(同 {@code V20261115_2}),内存不随回忆总量增长; + * 写入用 {@code ON DUPLICATE KEY UPDATE} 空转,重复执行不会产生第二行。

+ */ +public class V20261122_3__backfill_recall_scope_tags extends BaseJavaMigration { + private static final ObjectMapper JSON = new ObjectMapper(); + + @Override + public void migrate(Context context) throws Exception { + try (PreparedStatement select = context.getConnection() + .prepareStatement("SELECT id, recall_num, created_by, document_json FROM review_recalls" + + " WHERE id > ? AND scope_type = 'TAG' AND deleted = 0 AND document_json IS NOT NULL" + + " ORDER BY id LIMIT 1"); + PreparedStatement insert = context.getConnection() + .prepareStatement("INSERT INTO review_recall_scope_tags" + + " (recall_num, normalized_tag, created_by, created_time, last_modified_time)" + + " VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" + + " ON DUPLICATE KEY UPDATE normalized_tag = normalized_tag")) { + long after = 0; + while (true) { + select.setLong(1, after); + String recallNum; + String owner; + String document; + try (ResultSet rows = select.executeQuery()) { + if (!rows.next()) { + break; + } + after = rows.getLong("id"); + recallNum = rows.getString("recall_num"); + owner = rows.getString("created_by"); + document = rows.getString("document_json"); + } + for (String tag : scopeTags(document)) { + insert.setString(1, recallNum); + insert.setString(2, tag); + insert.setString(3, owner); + insert.executeUpdate(); + } + } + } + } + + /** 一条回忆的归一化标签(去重);文档读不出来时返回空集合,由调用方跳过。 */ + private static List scopeTags(String document) { + try { + JsonNode scope = JSON.readTree(document).path("detail").path("scope"); + Set tags = normalized(scope.path("normalizedTags")); + if (tags.isEmpty()) { + tags = normalized(scope.path("tags")); + } + return new ArrayList<>(tags); + } catch (Exception ignored) { + // 旧版本、被截断的文档:跳过这一行。异常本身不带,避免把私有正文带进迁移日志。 + return List.of(); + } + } + + private static Set normalized(JsonNode tags) { + Set normalized = new LinkedHashSet<>(); + for (JsonNode tag : tags) { + String key = tag.asText("").trim().toLowerCase(Locale.ROOT); + if (!key.isEmpty()) { + normalized.add(key); + } + } + return normalized; + } +} diff --git a/src/main/resources/db/migration/V20261122_1__drop_recall_status.sql b/src/main/resources/db/migration/V20261122_1__drop_recall_status.sql new file mode 100644 index 0000000..29e6cd8 --- /dev/null +++ b/src/main/resources/db/migration/V20261122_1__drop_recall_status.sql @@ -0,0 +1,7 @@ +-- 自由回忆不再区分「进行中 / 已结束」(2026-11-22):任意记录都能恢复编辑,status 与 endedAt 一并下线。 +-- 先删含 status 的索引,再删列,最后按去掉 status 的列顺序重建范围索引。 +DROP INDEX idx_recall_user_scope_status ON review_recalls; + +ALTER TABLE review_recalls DROP COLUMN status; + +CREATE INDEX idx_recall_user_scope ON review_recalls (created_by, scope_type, scope_key, deleted, last_modified_time, id); diff --git a/src/main/resources/db/migration/V20261122_2__add_recall_scope_tags.sql b/src/main/resources/db/migration/V20261122_2__add_recall_scope_tags.sql new file mode 100644 index 0000000..050f5e7 --- /dev/null +++ b/src/main/resources/db/migration/V20261122_2__add_recall_scope_tags.sql @@ -0,0 +1,18 @@ +-- 复习总览「相关导图」的查询索引(2026-11-22):一条回忆 × 一个归一化标签一行。 +-- 回忆的标签范围是 document_json 里的数组,没有索引可走;拆成行之后才能「按标签反查回忆 + 在 SQL 里分页」。 +-- 索引键长按 utf8mb4 复算(InnoDB 上限 3072 字节): +-- uk_recall_scope_tag = 64*4 + 255*4 = 1276 字节 +-- idx_recall_scope_tag_match = 64*4 + 255*4 + 64*4 + 4 = 1536 字节 +CREATE TABLE review_recall_scope_tags ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + recall_num VARCHAR(64) NOT NULL, + normalized_tag VARCHAR(255) NOT NULL, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_scope_tag (recall_num, normalized_tag), + KEY idx_recall_scope_tag_match (created_by, normalized_tag, recall_num, deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/src/main/resources/mapper/ReviewRecallScopeTagMapper.xml b/src/main/resources/mapper/ReviewRecallScopeTagMapper.xml new file mode 100644 index 0000000..356111e --- /dev/null +++ b/src/main/resources/mapper/ReviewRecallScopeTagMapper.xml @@ -0,0 +1,46 @@ + + + + + + + FROM review_recalls r + WHERE r.deleted = 0 + AND r.scope_type = 'TAG' + AND EXISTS (SELECT 1 + FROM review_recall_scope_tags t + WHERE t.recall_num = r.recall_num + AND t.created_by = r.created_by + AND t.deleted = 0 + AND t.normalized_tag IN + #{tag}) + + + + + + + diff --git a/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java index afaf5de..28b502e 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java @@ -64,6 +64,8 @@ class ReviewRecallControllerIntegrationTest { JsonNode detail = create(); String num = detail.path("recallNum").asText(); assertTrue(detail.path("createdAt").asText().endsWith("Z")); assertTrue(detail.has("writeToken")); for (String field : List.of("expressionVersions", "expressionVersion", "referenceVersion", "revision", "notes")) assertFalse(detail.has(field)); + // 回忆不再区分进行中 / 已结束:详情不带状态,也没有结束时间 + assertFalse(detail.has("status")); assertFalse(detail.has("endedAt")); JsonNode page = mapper.readTree(mvc.perform(get("/review/recalls/" + num + "/references").header("satoken", token).param("pageSize", "10")) .andExpect(jsonPath("$.data.total").value(1)).andExpect(jsonPath("$.data.records[0].preview").value("中文🙂资料")) .andReturn().getResponse().getContentAsString()).path("data"); @@ -80,6 +82,23 @@ class ReviewRecallControllerIntegrationTest { .content(mapper.writeValueAsString(new ResumeRequest(id(), "second", "stale-token")))) .andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.data.reason").value("REVISION_CONFLICT")); } + @Test void anyHistoricalRecallResumesAgainAndKeepsEditing() throws Exception { + JsonNode detail = create(); String num = detail.path("recallNum").asText(); String firstToken = detail.path("writeToken").asText(); + JsonNode resumed = resume(num, firstToken); + assertNotEquals(firstToken, resumed.path("writeToken").asText()); + // 记录没有「已结束」这层状态:同一篇记录可以再次恢复,写令牌继续轮换 + JsonNode again = resume(num, resumed.path("writeToken").asText()); + assertNotEquals(resumed.path("writeToken").asText(), again.path("writeToken").asText()); + var expression = new Expression(1, new ExpressionNode("root", "恢复后继续", "", List.of(), null, List.of())); + mvc.perform(put("/review/recalls/" + num + "/draft").header("satoken", token).contentType(MediaType.APPLICATION_JSON) + .content(mapper.writeValueAsString(new SaveDraftRequest(id(), again.path("editorId").asText(), again.path("writeToken").asText(), expression, new Timing(0, null))))) + .andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.expression.root.title").value("恢复后继续")); + } + JsonNode resume(String num, String writeToken) throws Exception { + return mapper.readTree(mvc.perform(post("/review/recalls/" + num + "/resume").header("satoken", token).contentType(MediaType.APPLICATION_JSON) + .content(mapper.writeValueAsString(new ResumeRequest(id(), "editor", writeToken)))) + .andExpect(jsonPath("$.code").value(200)).andReturn().getResponse().getContentAsString()).path("data"); + } @Test void otherUserAndDeletedRecallAreNotFound() throws Exception { String num = create().path("recallNum").asText(); StpUtil.login("other-http-" + id()); String other = StpUtil.getTokenValue(); mvc.perform(get("/review/recalls/" + num).header("satoken", other)).andExpect(jsonPath("$.data.reason").value("NOT_FOUND")); @@ -140,4 +159,35 @@ class ReviewRecallControllerIntegrationTest { .andExpect(jsonPath("$.code").value(400)); } } + + /** 总览「相关导图」:/related 不能被 /{recallNum} 抢成「查一条号码为 related 的回忆」。 */ + @Test void relatedMapsAreNotSwallowedByTheRecallNumRoute() throws Exception { + String num = create().path("recallNum").asText(); + String body = mvc.perform(get("/review/recalls/related").header("satoken", token) + .param("tags", tag).param("pageNum", "1").param("pageSize", "5")) + .andExpect(jsonPath("$.code").value(200)) + .andExpect(jsonPath("$.data.current").value(1)) + .andExpect(jsonPath("$.data.total").value(1)) + .andExpect(jsonPath("$.data.records[0].recall.recallNum").value(num)) + .andExpect(jsonPath("$.data.records[0].matchedTags[0]").value(tag)) + .andReturn().getResponse().getContentAsString(); + assertFalse(body.contains("reason")); + mvc.perform(get("/review/recalls/related").header("satoken", token)) + .andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.data.reason").value("INVALID_INPUT")); + } + + /** 最近回忆首屏由 SQL 排除顶部那张:前端直接要 5 条,不再取 6 条再截。 */ + @Test void recentRecallListExcludesTheGivenRecallInSql() throws Exception { + String num = create().path("recallNum").asText(); + mvc.perform(get("/review/recalls").header("satoken", token).param("scopeType", "TAG") + .param("combineMode", "UNION").param("tags", tag).param("pageSize", "5")) + .andExpect(jsonPath("$.data.total").value(1)) + .andExpect(jsonPath("$.data.records[0].recallNum").value(num)); + mvc.perform(get("/review/recalls").header("satoken", token).param("scopeType", "TAG") + .param("combineMode", "UNION").param("tags", tag).param("pageSize", "5") + .param("excludeRecallNum", num)) + .andExpect(jsonPath("$.code").value(200)) + .andExpect(jsonPath("$.data.total").value(0)) + .andExpect(jsonPath("$.data.records").isEmpty()); + } } diff --git a/src/test/java/com/guo/learningprogresstracker/migration/RecallScopeTagBackfillMigrationTest.java b/src/test/java/com/guo/learningprogresstracker/migration/RecallScopeTagBackfillMigrationTest.java new file mode 100644 index 0000000..5d564c4 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/migration/RecallScopeTagBackfillMigrationTest.java @@ -0,0 +1,105 @@ +package com.guo.learningprogresstracker.migration; + +import db.migration.V20261122_3__backfill_recall_scope_tags; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.Configuration; +import org.flywaydb.core.api.migration.Context; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** 相关导图索引的历史回填:只认标签范围的活回忆,缺 normalizedTags 时用 tags 兜底,可重复执行。 */ +class RecallScopeTagBackfillMigrationTest { + + @Test void backfillsTagScopesOnlyAndStaysRepeatable() throws Exception { + String url = "jdbc:h2:mem:recall-scope-tags-" + UUID.randomUUID() + + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;NON_KEYWORDS=USER;DB_CLOSE_DELAY=-1"; + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261122.1").load().migrate(); + try (Connection connection = DriverManager.getConnection(url, "sa", "")) { + insert(connection, "RECALL-TAG", "TAG", 0, document("{\"normalizedTags\":[\"a\",\"b\"]}")); + // 缺 normalizedTags:用 tags 做 trim + 小写兜底 + insert(connection, "RECALL-LEGACY", "TAG", 0, document("{\"tags\":[\"MiXeD\",\" B \"]}")); + // 归一化后重复:只留一行 + insert(connection, "RECALL-DUP", "TAG", 0, document("{\"normalizedTags\":[\"a\",\"A\",\"\"]}")); + insert(connection, "RECALL-TASK", "TASK", 0, document("{\"normalizedTags\":[\"a\"]}")); + insert(connection, "RECALL-DELETED", "TAG", 1, document("{\"normalizedTags\":[\"a\"]}")); + insert(connection, "RECALL-NO-DOC", "TAG", 0, null); + insert(connection, "RECALL-BROKEN", "TAG", 0, "{not json"); + } + + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261122.3").load().migrate(); + try (Connection connection = DriverManager.getConnection(url, "sa", "")) { + Map> indexed = indexedTags(connection); + assertEquals(List.of("a", "b"), indexed.get("RECALL-TAG")); + assertEquals(List.of("b", "mixed"), indexed.get("RECALL-LEGACY")); + assertEquals(List.of("a"), indexed.get("RECALL-DUP")); + assertEquals(3, indexed.size(), "TASK / 已删除 / 无文档 / 不可解析都应跳过:" + indexed); + + // 再跑一次 Java 迁移:ON DUPLICATE KEY UPDATE 空转,不会多出第二行 + new V20261122_3__backfill_recall_scope_tags().migrate(context(connection)); + assertEquals(indexed, indexedTags(connection)); + } + } + + /** Flyway 9 的 Context 只有连接与配置两项;回填只用连接。 */ + private static Context context(Connection connection) { + return new Context() { + @Override public Configuration getConfiguration() { + return null; + } + + @Override public Connection getConnection() { + return connection; + } + }; + } + + private static String document(String scope) { + return "{\"detail\":{\"scope\":" + scope + "}}"; + } + + private static void insert(Connection connection, String recallNum, String type, int deleted, String document) + throws SQLException { + try (PreparedStatement insert = connection.prepareStatement("INSERT INTO review_recalls" + + " (recall_num, scope_type, task_num, scope_key, active_duration_ms, document_json," + + " created_by, created_time, last_modified_time, deleted)" + + " VALUES (?, ?, ?, ?, 0, ?, 'owner', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)")) { + insert.setString(1, recallNum); + insert.setString(2, type); + insert.setString(3, "TASK".equals(type) ? "task-1" : null); + insert.setString(4, "TASK".equals(type) ? "task-1" : "a".repeat(64)); + insert.setString(5, document); + insert.setInt(6, deleted); + insert.executeUpdate(); + } + } + + /** 按回忆号聚合已回填的标签;软删的索引行不参与。 */ + private static Map> indexedTags(Connection connection) throws SQLException { + Map> indexed = new LinkedHashMap<>(); + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery( + "SELECT recall_num, normalized_tag, created_by FROM review_recall_scope_tags" + + " WHERE deleted = 0 ORDER BY recall_num, normalized_tag")) { + while (rows.next()) { + assertEquals("owner", rows.getString("created_by"), "created_by 取回忆行的归属"); + indexed.computeIfAbsent(rows.getString("recall_num"), key -> new java.util.ArrayList<>()) + .add(rows.getString("normalized_tag")); + } + } + assertTrue(indexed.values().stream().noneMatch(tags -> tags.isEmpty())); + return indexed; + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java b/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java index 5ff43a0..e038173 100644 --- a/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java @@ -44,6 +44,7 @@ class RecallStorageMigrationTest { Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").load().migrate(); try (Connection connection = DriverManager.getConnection(url, "sa", ""); Statement statement = connection.createStatement()) { assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recalls")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM information_schema.columns WHERE table_name='review_recalls' AND column_name='status'")); assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recall_requests")); assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recall_receipts")); assertEquals(0, count(statement, "SELECT COUNT(*) FROM ai_tasks WHERE ai_type IN ('RECALL_HINT','RECALL_CHECK')")); diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java b/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java index 6090291..2c1be8c 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java @@ -16,7 +16,7 @@ public final class HistoricalRecallFixture { ScopeSnapshot scope = loader.scope(new ScopeInput("TASK", taskNum, List.of(), null)); ReferenceSnapshot reference = loader.snapshot(scope); RecallDetail detail = new RecallDetail(); - detail.setRecallNum("RECALL-" + UUID.randomUUID()); detail.setStatus("ACTIVE"); detail.setScope(scope); detail.setScopeStatus("VALID"); + detail.setRecallNum("RECALL-" + UUID.randomUUID()); detail.setScope(scope); detail.setScopeStatus("VALID"); detail.setActiveDurationMs(0); detail.setCreatedAt(now); detail.setUpdatedAt(now); detail.setEditorId("editor"); detail.setWriteToken(UUID.randomUUID().toString()); detail.setExpression(new Expression(1, new ExpressionNode("root", "", "", List.of(), null, List.of()))); diff --git a/src/test/java/com/guo/learningprogresstracker/service/recall/RelatedRecallIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/recall/RelatedRecallIntegrationTest.java new file mode 100644 index 0000000..30d8415 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/recall/RelatedRecallIntegrationTest.java @@ -0,0 +1,179 @@ +package com.guo.learningprogresstracker.service.recall; + +import cn.dev33.satoken.stp.StpUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.CreateRecallRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RelatedRecallPage; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeInput; +import com.guo.learningprogresstracker.entity.ReviewRecallEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallScopeTagEntity; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import com.guo.learningprogresstracker.mapper.ReviewRecallMapper; +import com.guo.learningprogresstracker.mapper.ReviewRecallScopeTagMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.service.MarkerService; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; +import com.guo.learningprogresstracker.service.ai.RecallAiClient; +import java.util.List; +import java.util.UUID; +import java.util.stream.IntStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** 总览「相关导图」:按标签反查保存过的导图,命中数排序与分页都落在 SQL 里。 */ +@SpringBootTest +class RelatedRecallIntegrationTest { + @Autowired ReviewRecallService service; + @Autowired ReviewRecallMapper recalls; + @Autowired ReviewRecallScopeTagMapper scopeTags; + @Autowired StudyReportFragmentsMapper fragments; + @Autowired MarkerService markers; + @MockBean AiTaskRunner runner; + @MockBean RecallAiClient client; + + @BeforeEach void login() { + StpUtil.login("related-recall-test-" + UUID.randomUUID()); + } + + String id() { + return UUID.randomUUID().toString(); + } + + void fragment(String text, String... tags) throws Exception { + StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity(); + fragment.setContent(text); + fragment.setContextType("REVIEW"); + fragment.setContextNum(id()); + fragments.insert(fragment); + for (String tag : tags) { + markers.addUserTag(MarkerObjectTypeEnum.FRAGMENT, fragment.getId().toString(), tag); + } + } + + RecallDetail create(String... tags) { + ScopeInput scope = new ScopeInput("TAG", null, List.of(tags), "UNION"); + return service.create(new CreateRecallRequest(id(), "editor", scope, null)); + } + + List nums(RelatedRecallPage page) { + return page.records().stream().map(row -> row.recall().getRecallNum()).toList(); + } + + String reason(Executable call) { + return assertThrows(RecallBusinessException.class, call).getData().reason(); + } + + @Test void mostMatchedTagsFirstThenNewestAndSecondPageContinues() throws Exception { + fragment("资料", "A", "B", "C"); + // 创建顺序决定 id:先 C 后 B,命中数相同时(更新时间同秒)按 id 倒序,B 在 C 之前 + String c = create("B").getRecallNum(); + String b = create("A").getRecallNum(); + String d = create("C").getRecallNum(); + RecallDetail twoTags = create("A", "B"); + String a = twoTags.getRecallNum(); + + // 索引行随回忆创建写入:A+B 的图有 2 行 + assertEquals(2, scopeTags.selectCount(Wrappers.lambdaQuery() + .eq(ReviewRecallScopeTagEntity::getRecallNum, a)).intValue()); + + RelatedRecallPage first = service.related(1, 2, List.of("a", "b")); + assertEquals(3, first.total()); + assertEquals(2, first.size()); + assertEquals(List.of(a, b), nums(first)); + // 命中判定用归一化名,回给前端的是范围里保存的原样写法 + assertEquals(List.of("A", "B"), first.records().get(0).matchedTags()); + assertEquals(List.of("A"), first.records().get(1).matchedTags()); + + RelatedRecallPage second = service.related(2, 2, List.of("A", "B")); + assertEquals(3, second.total()); + assertEquals(List.of(c), nums(second)); + assertEquals(List.of("B"), second.records().get(0).matchedTags()); + + // 不命中任何所选标签的 D 不出现 + List all = nums(service.related(1, 10, List.of("A", "B"))); + assertEquals(List.of(a, b, c), all); + assertFalse(all.contains(d)); + assertTrue(service.related(3, 2, List.of("A", "B")).records().isEmpty()); + } + + @Test void tagsMatchByNormalizedNameNotByCaseOrSpacing() throws Exception { + fragment("资料", "MiXeD Tag"); + String num = create(" MiXeD Tag ").getRecallNum(); + RelatedRecallPage page = service.related(1, 10, List.of("mixed tag")); + assertEquals(1, page.total()); + assertEquals(List.of(num), nums(page)); + // 查询用小写也能命中,展示仍是范围里保存的原样写法 + assertEquals(List.of("MiXeD Tag"), page.records().get(0).matchedTags()); + // 查询参数带空白/大写:仍命中,展示照样是范围里的原样写法 + RelatedRecallPage spaced = service.related(1, 10, List.of(" MIXED TAG ")); + assertEquals(List.of("MiXeD Tag"), spaced.records().get(0).matchedTags()); + assertEquals(0, service.related(1, 10, List.of("other")).total()); + } + + @Test void anotherAccountsAndTaskScopedMapsNeverAppear() throws Exception { + fragment("资料", "A", "B"); + String mine = create("A", "B").getRecallNum(); + // 手工造一条 TASK 范围回忆 + 索引行:SQL 的 scope_type 过滤必须把它挡在外面 + ReviewRecallEntity task = new ReviewRecallEntity(); + task.setRecallNum("RECALL-TASK-" + UUID.randomUUID()); + task.setScopeType("TASK"); + task.setTaskNum("TASK-" + UUID.randomUUID()); + task.setScopeKey(task.getTaskNum()); + task.setActiveDurationMs(0L); + recalls.insert(task); + ReviewRecallScopeTagEntity taskIndex = new ReviewRecallScopeTagEntity(); + taskIndex.setRecallNum(task.getRecallNum()); + taskIndex.setNormalizedTag("a"); + scopeTags.insert(taskIndex); + + RelatedRecallPage own = service.related(1, 10, List.of("A")); + assertEquals(1, own.total()); + assertEquals(List.of(mine), nums(own)); + + StpUtil.login("related-recall-other-" + UUID.randomUUID()); + assertEquals(0, service.related(1, 10, List.of("A")).total()); + fragment("另一个账号的资料", "A"); + String theirs = create("A").getRecallNum(); + assertEquals(List.of(theirs), nums(service.related(1, 10, List.of("A")))); + } + + @Test void deletingARecallRemovesItsIndexRows() throws Exception { + fragment("资料", "A", "B"); + String num = create("A", "B").getRecallNum(); + assertEquals(1, service.related(1, 10, List.of("A")).total()); + service.delete(num); + RelatedRecallPage after = service.related(1, 10, List.of("A", "B")); + assertEquals(0, after.total()); + assertTrue(after.records().isEmpty()); + assertEquals(0, scopeTags.selectCount(Wrappers.lambdaQuery() + .eq(ReviewRecallScopeTagEntity::getRecallNum, num)).intValue()); + } + + @Test void relatedRejectsEmptyOrTooManyTagsAndOutOfRangePaging() throws Exception { + List eleven = IntStream.rangeClosed(1, 11).mapToObj(index -> "tag" + index).toList(); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 10, null))); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 10, List.of()))); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 10, List.of(" ", "")))); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 10, eleven))); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 101, List.of("A")))); + assertEquals("INVALID_INPUT", reason(() -> service.related(0, 10, List.of("A")))); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 10, List.of("a".repeat(256))))); + assertEquals("INVALID_INPUT", reason(() -> service.related(1, 10, List.of("A\u0001B")))); + // 重复标签归一化后只剩一个:查询照常可用,不会因去重后不足 1 个而被拒 + fragment("资料", "A"); + String num = create("A").getRecallNum(); + assertEquals(List.of(num), nums(service.related(1, 10, List.of("A", "a")))); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java index 48659d2..5e32461 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java @@ -29,6 +29,7 @@ import com.guo.learningprogresstracker.service.ai.RecallJson; @SpringBootTest class ReviewRecallServiceIntegrationTest { @Autowired ReviewRecallService service; + @Autowired ReviewRecallStore store; @Autowired RecallAiService ai; @Autowired AiTaskService aiTasks; @Autowired ReviewRecallMapper recalls; @@ -54,7 +55,6 @@ class ReviewRecallServiceIntegrationTest { Expression expression(String title) { return new Expression(1, new ExpressionNode("root", title, "", List.of(), null, List.of())); } SaveDraftRequest draft(RecallDetail detail, String title) { return new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), expression(title), new Timing(0, null)); } RecallDetail save(RecallDetail detail, String title) { return service.draft(detail.getRecallNum(), draft(detail, title)); } - RecallDetail end(RecallDetail detail) { return service.end(detail.getRecallNum(), new EndRequest(id(), detail.getEditorId(), detail.getWriteToken(), detail.getExpression(), new Timing(0, null))); } AiTaskResponse submit(RecallDetail detail, String type) { var request = new AiTaskSubmitRequest(); request.setType(type); request.setTargetNum(detail.getRecallNum()); request.setParams(mapper.convertValue(new AiParams(1, id(), detail.getEditorId(), detail.getWriteToken(), "RECALL_HINT".equals(type) ? "KEYWORD" : null), new TypeReference>() {})); @@ -83,12 +83,44 @@ class ReviewRecallServiceIntegrationTest { assertFalse(stored.has("references")); assertFalse(stored.path("reference").has("version")); assertEquals("最终内容", service.get(detail.getRecallNum()).getExpression().root().title()); } - @Test void createAutomaticallyCarriesMostRecentCompletedMapOnlyForExactScope() throws Exception { - fragment("资料", "A", "B"); var previous = save(create(scope("A", "B")), "上次导图"); end(previous); - var next = create(scope(" b ", "a")); assertEquals("上次导图", next.getExpression().root().title()); - assertTrue(next.getRequests().isEmpty()); assertEquals(0, next.getActiveDurationMs()); + @Test void creatingRecallAlwaysStartsFromAnEmptyRootEvenWithHistoryInScope() throws Exception { + fragment("资料", "A", "B"); save(create(scope("A", "B")), "同范围的历史导图"); + assertEquals("", create(scope("A", "B")).getExpression().root().title()); assertEquals("", create(scope("A")).getExpression().root().title()); - var intersection = create(new ScopeInput("TAG", null, List.of("A", "B"), "INTERSECT")); assertEquals("", intersection.getExpression().root().title()); + var intersection = create(new ScopeInput("TAG", null, List.of("A", "B"), "INTERSECT")); + assertEquals("", intersection.getExpression().root().title()); + } + @Test void zeroMatchingFragmentsCannotCreateResumeOrDraft() throws Exception { + fragment("A 资料", "A"); + fragment("B 资料", "B"); + var createFailure = assertThrows(RecallBusinessException.class, + () -> create(new ScopeInput("TAG", null, List.of("A", "B"), "INTERSECT"))); + assertEquals("SCOPE_EMPTY", createFailure.getData().reason()); + + var detail = create(scope("A")); + var doc = store.load(detail.getRecallNum()); + doc.setReference(new ReferenceSnapshot("EMPTY", List.of(), List.of(), List.of())); + store.persist(doc); + var resumeFailure = assertThrows(RecallBusinessException.class, + () -> service.resume(detail.getRecallNum(), new ResumeRequest(id(), "editor", detail.getWriteToken()))); + assertEquals("SCOPE_EMPTY", resumeFailure.getData().reason()); + var draftFailure = assertThrows(RecallBusinessException.class, () -> service.draft( + detail.getRecallNum(), + new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), detail.getExpression(), new Timing(0, null)))); + assertEquals("SCOPE_EMPTY", draftFailure.getData().reason()); + } + @Test void anyHistoricalRecallResumesAndKeepsAccumulatingOnTheSameRecord() throws Exception { + fragment("资料", "A"); var detail = create(scope("A")); + detail = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), expression("第一次"), new Timing(1000, 1200L, Instant.now()))); + detail = service.resume(detail.getRecallNum(), new ResumeRequest(id(), "another-editor", detail.getWriteToken())); + assertEquals("another-editor", detail.getEditorId()); + detail = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), expression("第二次"), new Timing(500, 700L, Instant.now()))); + // 记录没有「已结束」这层状态:再恢复一次仍然能继续写,耗时继续累加到同一条记录 + detail = service.resume(detail.getRecallNum(), new ResumeRequest(id(), "third-editor", detail.getWriteToken())); + detail = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), expression("第三次"), new Timing(300, 400L, Instant.now()))); + assertEquals(1800L, detail.getActiveDurationMs()); assertEquals(2300L, detail.getActualDurationMs().longValue()); + assertEquals(1, recalls.selectCount(Wrappers.lambdaQuery()).intValue()); + assertEquals("第三次", service.get(detail.getRecallNum()).getExpression().root().title()); } @Test void actualDurationAccumulatesAcrossSegmentsAndNeverDropsBelowActive() throws Exception { fragment("资料", "A"); var detail = create(scope("A")); @@ -127,8 +159,8 @@ class ReviewRecallServiceIntegrationTest { } @Test void legacyDocumentsAreDeletedInsteadOfSkippedAndNewRecallStartsEmpty() throws Exception { fragment("资料", "A"); - var detail = end(save(create(scope("A")), "旧版内容")); - var other = end(save(create(scope("A")), "另一旧版")); + var detail = save(create(scope("A")), "旧版内容"); + var other = save(create(scope("A")), "另一旧版"); for (String num : List.of(detail.getRecallNum(), other.getRecallNum())) { var row = recalls.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallEntity::getRecallNum, num)); row.setDocumentJson("{not valid json"); @@ -136,7 +168,7 @@ class ReviewRecallServiceIntegrationTest { } var failure = assertThrows(RecallBusinessException.class, () -> service.get(detail.getRecallNum())); assertEquals("STORED_DATA_INVALID", failure.getData().reason()); - var page = service.list(1, 20, null, "TAG", null, List.of("A"), "UNION"); + var page = service.list(1, 20, "TAG", null, List.of("A"), "UNION", null); assertEquals(0, page.total()); assertTrue(page.records().isEmpty()); assertEquals("", create(scope("A")).getExpression().root().title()); @@ -198,8 +230,8 @@ class ReviewRecallServiceIntegrationTest { assertNull(service.source(detail.getRecallNum(), "fragment:" + fragment.getId()).content()); assertEquals("SOURCE_REDACTED", read.getRequests().get(0).errorCode()); assertNull(read.getRequests().get(0).result()); } - @Test void tenantIsolationPreventsReadingOrAutoCarryAcrossAccounts() throws Exception { - fragment("私有资料", "A"); var previous = save(create(scope("A")), "私有图"); end(previous); + @Test void tenantIsolationPreventsReadingAnotherAccountsRecall() throws Exception { + fragment("私有资料", "A"); var previous = save(create(scope("A")), "私有图"); StpUtil.login("other-" + id()); fragment("另一个账号的资料", "A"); assertEquals("", create(scope("A")).getExpression().root().title()); assertThrows(RecallBusinessException.class, () -> service.get(previous.getRecallNum())); @@ -225,10 +257,10 @@ class ReviewRecallServiceIntegrationTest { + "\"limits\":{\"maxHintItems\":3,\"maxHintNodes\":5,\"maxFindings\":12},\"limitations\":[]}", RecallAiParams.class); assertEquals(1, legacyInput.schemaVersion()); assertTrue(legacyInput.units().isEmpty()); } - @Test void emptyMapCanCompleteWithoutAiOrNotes() throws Exception { - fragment("", "A"); var detail = create(scope("A")); var done = end(detail); - assertEquals("ENDED", done.getStatus()); assertEquals("", done.getExpression().root().title()); - assertNotNull(done.getEndedAt()); + @Test void emptyMapCanBeSavedWithoutAiOrNotes() throws Exception { + fragment("", "A"); var detail = create(scope("A")); var saved = save(detail, ""); + assertEquals("", saved.getExpression().root().title()); assertEquals(0L, saved.getActiveDurationMs()); + assertEquals(0L, saved.getActualDurationMs().longValue()); assertTrue(saved.getRequests().isEmpty()); } @Test void legacyReportAndApplicationSourcesLeaveSummaryAndPaging() throws Exception { fragment("资料", "A"); var detail = create(scope("A"));