diff --git a/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java b/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java new file mode 100644 index 0000000..da7342e --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java @@ -0,0 +1,55 @@ +package com.guo.learningprogresstracker.controller; + +import com.guo.learningprogresstracker.dto.TagMindMapView; +import com.guo.learningprogresstracker.dto.TagScope; +import com.guo.learningprogresstracker.dto.request.TagScopeRequest; +import com.guo.learningprogresstracker.dto.request.UpdateTagMindMapRequest; +import com.guo.learningprogresstracker.entity.CommonResult; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import com.guo.learningprogresstracker.exception.ErrorParameterException; +import com.guo.learningprogresstracker.service.ReviewTagMindMapService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * 标签导图控制层(闭环-04)。 + * + *

按标签复习与按任务复习并存:任务导图仍走 {@code /review/standard-mind-map/{taskNum}}, + * 这里只负责以「标签集合 + 取数模式」为范围的那一半。

+ * + *

生成与回忆对比都不在请求线程里等 AI:由前端提交 {@code POST /ai/tasks} + * (type=TAG_MIND_MAP / TAG_RECALL_COMPARE)后轮询结果,与既有 AI 任务链路同一约定。

+ */ +@RequestMapping("/review/tag-mind-map") +@RestController +@Validated +@RequiredArgsConstructor +public class TagMindMapController { + + private final ReviewTagMindMapService reviewTagMindMapService; + + /** + * 读取该范围的状态:范围键、标签集合与已有导图。 + * + *

读取不触发生成:没有导图时 {@code map} 为 null,由前端提交生成任务。 + * 用请求体而不是查询参数,是因为标签名由用户自由输入、可能含逗号。

+ */ + @PostMapping("/query") + public CommonResult query(@Valid @RequestBody TagScopeRequest request) + throws ErrorParameterException { + TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode()); + return CommonResult.success(reviewTagMindMapService.query(scope)); + } + + /** + * 用户编辑标签导图(大纲文本形式);该范围还没有导图时保存即为新建。 + */ + @PutMapping + public CommonResult updateTagMindMap( + @Valid @RequestBody UpdateTagMindMapRequest request) throws ErrorParameterException { + TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode()); + return CommonResult.success(reviewTagMindMapService.updateByOutline(scope, request.getOutline())); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/FragmentTagMatch.java b/src/main/java/com/guo/learningprogresstracker/dto/FragmentTagMatch.java new file mode 100644 index 0000000..816c963 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/FragmentTagMatch.java @@ -0,0 +1,19 @@ +package com.guo.learningprogresstracker.dto; + +import lombok.Data; + +/** + * 一个碎片命中的标签数(闭环-04 标签导图取材)。 + * + *

由 Mapper 层的分组查询直接映射:并集取「命中任意一个」的行,交集取「命中数 == 范围标签数」的行。 + * 命中数按归一化标签名去重,所以重复打标不会让交集判定失真。

+ */ +@Data +public class FragmentTagMatch { + + /** 碎片 id(标记的 object_num) */ + private String objectNum; + + /** 命中的标签数(按归一化标签名去重) */ + private Integer matchedTagCount; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java b/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java new file mode 100644 index 0000000..d42b8cb --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java @@ -0,0 +1,30 @@ +package com.guo.learningprogresstracker.dto; + +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +/** + * 一个标签复习范围的当前状态(闭环-04)。 + * + *

范围键与标签集合总是返回(即使还没有导图),让前端能用同一组参数发起生成任务与回忆对比; + * {@code map} 为空表示该范围还没生成过导图——读取路径不触发生成,生成走 + * {@code POST /ai/tasks}(type=TAG_MIND_MAP)异步完成。

+ */ +@Data +public class TagMindMapView { + + @Schema(description = "范围键:标签集合与取数模式的稳定哈希,同时作为 AI 任务的 targetNum") + private String scopeKey; + + @Schema(description = "范围的标签集合(展示用,按归一化名排序)") + private List tags; + + @Schema(description = "取数模式:UNION=并集 / INTERSECT=交集") + private String mode; + + @Schema(description = "该范围已有的标签导图;没有时为 null") + private ReviewTagMindMapEntity map; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java b/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java new file mode 100644 index 0000000..ad6dc1e --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java @@ -0,0 +1,19 @@ +package com.guo.learningprogresstracker.dto; + +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; + +import java.util.List; + +/** + * 解析后的复习范围:标签集合 + 取数模式 + 规范键(闭环-04)。 + * + *

{@code tags} 是展示用标签集合(按归一化名排序、保留输入原样),{@code normalizedTags} 是规范化标签集合, + * {@code scopeKey} 是两者的稳定哈希——集合相同且模式相同即同一张标签导图。

+ */ +public record TagScope(String scopeKey, List tags, List normalizedTags, TagCombineModeEnum mode) { + + /** 范围的展示名:标签以「、」连接,也是标签导图的根节点标题来源 */ + public String displayName() { + return String.join("、", tags); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java new file mode 100644 index 0000000..8300b27 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java @@ -0,0 +1,22 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotEmpty; +import lombok.Data; + +import java.util.List; + +/** + * 标签复习范围(闭环-04):标签集合 + 取数模式。 + * + *

用于纯范围寻址的读接口(读取该范围的导图、读取该范围的回忆记录)。 + * 字段名与 {@code /ai/tasks} 的 params 保持一致,前端两处可以直接复用。

+ */ +@Data +public class TagScopeRequest { + + @NotEmpty(message = "请先选择标签") + private List tags; + + /** 取数模式:UNION=并集(默认)/ INTERSECT=交集 */ + private String mode; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java new file mode 100644 index 0000000..77149f0 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java @@ -0,0 +1,26 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import lombok.Data; + +import java.util.List; + +/** + * 用户编辑标签导图(大纲文本形式)请求(闭环-04)。 + * + *

范围绕「标签集合 + 取数模式」寻址,因此请求里带的是范围本身而不是导图 id; + * 该范围还没有导图时,保存即为新建。

+ */ +@Data +public class UpdateTagMindMapRequest { + + @NotEmpty(message = "请先选择标签") + private List tags; + + /** 取数模式:UNION=并集(默认)/ INTERSECT=交集 */ + private String mode; + + @NotBlank(message = "请填写思维导图大纲") + private String outline; +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java new file mode 100644 index 0000000..55a81fc --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java @@ -0,0 +1,74 @@ +package com.guo.learningprogresstracker.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * 标签思维导图(闭环-04):以一个「标签集合 + 取数模式」为范围的导图,与任务导图并存。 + * + *

范围键 {@code scopeKey} 是标签集合(归一化、排序后拼接)与取数模式的稳定哈希: + * 集合相同且模式相同即同一张导图,因此同一用户下范围键唯一。素材是带这些标签的知识碎片, + * 与任务导图共用「碎片 → 缩进大纲」的生成链路与内置规则降级路径。

+ */ +@TableName(value = "review_tag_mind_maps") +@Data +public class ReviewTagMindMapEntity extends BaseEntity implements Serializable { + + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + + /** 范围键,见 {@code utils.TagScopeTool#scopeKey} */ + @TableField(value = "scope_key") + private String scopeKey; + + /** 取数模式:UNION=并集 / INTERSECT=交集,取值见 {@code TagCombineModeEnum} */ + @TableField(value = "combine_mode") + private String combineMode; + + /** 范围的标签集合(JSON 数组,展示保留输入原样,按归一化名排序) */ + @TableField(value = "tag_names") + private String tagNames; + + @TableField(value = "title") + private String title; + + /** 统一树结构 JSON(根节点:{title, notes, children}) */ + @TableField(value = "content") + private String content; + + /** 缩进大纲文本,供前端展示与用户编辑 */ + @TableField(value = "outline") + private String outline; + + @TableField(value = "summary") + private String summary; + + /** 生成来源:BUILTIN/AI/USER/USER_MERGE */ + @TableField(value = "generator") + private String generator; + + @TableField(value = "generator_version") + private String generatorVersion; + + @TableField(value = "source_fragment_count") + private Integer sourceFragmentCount; + + @TableField(value = "generated_time") + private LocalDateTime generatedTime; + + /** 该范围下的素材(碎片标签)发生变化后置为 true,表示这张导图需要重建;重建由用户手动触发 */ + @TableField(value = "needs_update") + private Boolean needsUpdate; + + @TableField(value = "needs_update_time") + private LocalDateTime needsUpdateTime; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java index e42cb86..a1c99a2 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java @@ -16,6 +16,9 @@ public enum AiTaskTypeEnum { /** 标准思维导图生成:全量、增量或按需生成 */ MIND_MAP("思维导图生成"), + /** 标签思维导图生成:按「标签集合 + 取数模式」生成或重建(闭环-04) */ + TAG_MIND_MAP("标签思维导图生成"), + /** 学习报告草稿聚合 */ REPORT_DRAFT("学习报告草稿"), diff --git a/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java new file mode 100644 index 0000000..811eee7 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java @@ -0,0 +1,37 @@ +package com.guo.learningprogresstracker.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.Locale; + +/** + * 思维导图的生成模式(AI-02):同一条生成链路按需全量重建、增量合并或缺失时才生成。 + */ +@Getter +@AllArgsConstructor +public enum MindMapGenerateModeEnum { + + /** 全量重新生成 */ + FULL("全量生成"), + + /** 增量更新:保留用户编辑过的节点,合并新生成的节点 */ + INCREMENTAL("增量更新"), + + /** 仅在缺失时生成(读取页面按需触发) */ + ENSURE("按需生成"); + + private final String description; + + /** 宽松解析:空值与无法识别的值都按全量生成处理 */ + public static MindMapGenerateModeEnum parse(String value) { + if (value == null || value.isBlank()) { + return FULL; + } + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return FULL; + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java new file mode 100644 index 0000000..dd6b0db --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java @@ -0,0 +1,41 @@ +package com.guo.learningprogresstracker.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.Locale; + +/** + * 标签导图的取数模式(闭环-04)。 + * + *

多标签由用户在界面上选并集还是交集,默认并集;模式与标签集合一起构成导图的规范键。

+ */ +@Getter +@AllArgsConstructor +public enum TagCombineModeEnum { + + /** 并集:带任一标签的内容都取材 */ + UNION("并集"), + + /** 交集:同时带全部标签的内容才取材 */ + INTERSECT("交集"); + + private final String description; + + /** 默认取数模式:并集(维护者口径) */ + public static TagCombineModeEnum defaultMode() { + return UNION; + } + + /** 宽松解析:空值按默认并集处理,无法识别时返回 null(由调用方报参数错误) */ + public static TagCombineModeEnum parse(String value) { + if (value == null || value.isBlank()) { + return defaultMode(); + } + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return null; + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java index 257263e..c13b73c 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java @@ -1,12 +1,14 @@ package com.guo.learningprogresstracker.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.dto.FragmentTagMatch; import com.guo.learningprogresstracker.dto.MarkerUsage; import com.guo.learningprogresstracker.entity.MarkerEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; +import java.util.Collection; import java.util.List; @Mapper @@ -28,4 +30,28 @@ public interface MarkerMapper extends BaseMapper { ORDER BY marker_count DESC, marker_name ASC """) List selectUserTagUsage(@Param("createdBy") String createdBy); + + /** + * 按标签集合统计每个碎片命中的标签数(闭环-04 标签导图取材)。 + * + *

归一化口径与标签字典一致(去首尾空白 + 小写),所以标签大小写/空白不同也能命中同一组标签; + * 命中数按归一化名去重,并集取「≥1」,交集取「= 范围标签数」。 + * 租户条件 {@code created_by} 由 {@code TenantLineInnerInterceptor} 自动追加(有集成测试覆盖)。

+ * + * @param tagKeys 规范化标签名;为空时返回空列表 + */ + @Select(""" + + """) + List countUserTagsPerFragment(@Param("tagKeys") Collection tagKeys); } diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java new file mode 100644 index 0000000..50bfdf4 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java @@ -0,0 +1,13 @@ +package com.guo.learningprogresstracker.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 标签导图 Mapper(闭环-04)。 + *

查询条件都能用 Wrapper 表达(按范围键取一条、按是否待更新扫一遍),因此不额外下沉自定义 SQL。

+ */ +@Mapper +public interface ReviewTagMindMapMapper extends BaseMapper { +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java b/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java new file mode 100644 index 0000000..26cd9ad --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java @@ -0,0 +1,61 @@ +package com.guo.learningprogresstracker.service; + +import com.guo.learningprogresstracker.dto.TagMindMapView; +import com.guo.learningprogresstracker.dto.TagScope; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import com.guo.learningprogresstracker.exception.ErrorParameterException; +import com.guo.learningprogresstracker.exception.NotFindEntitiesException; +import com.guo.learningprogresstracker.exception.OperationFailedException; + +import java.util.Collection; +import java.util.List; + +/** + * 标签思维导图服务(闭环-04)。 + * + *

标签导图以一个「标签集合 + 取数模式」为范围,与任务导图并存、互不替代: + * 任务导图回答「这个任务学到了什么结构」,标签导图回答「这个概念在不同任务里呈现出什么结构」。 + * 范围用规范键({@code TagScope#scopeKey})寻址,集合相同且模式相同即同一张导图。

+ * + *

两条硬口径:

+ *
    + *
  • 读取不生成:读取路径只返回已有导图,生成走 {@code POST /ai/tasks}(type=TAG_MIND_MAP)异步完成;
  • + *
  • 重建手动触发:素材(碎片标签)变化只把导图置「待更新」,不自动重建。
  • + *
+ */ +public interface ReviewTagMindMapService { + + /** + * 解析复习范围:去空白、按归一化名去重排序、算范围键,并校验标签数量与取数模式。 + * + * @param mode UNION(默认,并集)/ INTERSECT(交集) + */ + TagScope resolveScope(List tags, String mode) throws ErrorParameterException; + + /** + * 读取该范围的状态:范围描述 + 已有导图;读取不触发生成。 + */ + TagMindMapView query(TagScope scope); + + /** + * 用户手动编辑标签导图(用缩进大纲文本替换);该范围还没有导图时保存即为新建。 + */ + ReviewTagMindMapEntity updateByOutline(TagScope scope, String outline); + + /** + * 重新生成该范围的标签导图(由 AI 任务执行器在请求线程之外调用)。 + */ + ReviewTagMindMapEntity regenerate(TagScope scope) throws OperationFailedException; + + /** + * 增量更新:保留用户编辑过的节点,合并最新生成的节点。 + */ + ReviewTagMindMapEntity incrementalGenerate(TagScope scope) throws NotFindEntitiesException, OperationFailedException; + + /** + * 素材发生变化时的置「待更新」(不重建)。 + * + *

由标签的增删改与碎片删除调用:只有标签集合与变化标签有交集的那几张导图会被置位。

+ */ + void markStaleForTags(Collection changedTagNames); +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/StandardMindMapService.java b/src/main/java/com/guo/learningprogresstracker/service/StandardMindMapService.java index 2e709cd..e0d2f0e 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/StandardMindMapService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/StandardMindMapService.java @@ -6,6 +6,8 @@ import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; +import com.guo.learningprogresstracker.utils.CompareResult; +import com.guo.learningprogresstracker.utils.MindMapNode; import java.util.List; import java.util.Map; @@ -50,6 +52,17 @@ public interface StandardMindMapService { RecallCompareOutcome recallCompare(String taskNum, String recallOutline, String focusPath, ReviewTiming timing) throws NotFindEntitiesException, OperationFailedException; + /** + * 用同一套对比口径比较一棵基准导图与用户回忆大纲:优先 AI 语义对比,AI 不可用或失败时降级为文本相似度匹配。 + * + *

任务导图与标签导图共用它,避免两种复习范围出现两套覆盖率口径。

+ * + * @param scopeName 范围名(任务名或标签集合),仅用于 AI 提示词与日志 + * @param standardRoot 作为对比基准的导图树(可能只是标准导图的一棵子树) + * @param recallOutline 用户回忆的缩进大纲文本 + */ + CompareResult compareWithRecall(String scopeName, MindMapNode standardRoot, String recallOutline); + /** * 根据内容文本在标准导图中查找最匹配的节点,返回节点路径。 * diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskParams.java b/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskParams.java new file mode 100644 index 0000000..87033ea --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskParams.java @@ -0,0 +1,77 @@ +package com.guo.learningprogresstracker.service.impl; + +import lombok.extern.slf4j.Slf4j; + +import java.time.LocalDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * AI 任务参数的宽松读取(AI-02)。 + * + *

参数的来源是前端提交的 JSON:数字与时间可能是字符串,缺字段与空值都按「未提供」处理, + * 各任务处理器共用同一套解析口径。

+ */ +@Slf4j +final class AiTaskParams { + + private AiTaskParams() { + } + + static String asString(Map params, String key) { + Object value = params == null ? null : params.get(key); + return value == null ? null : String.valueOf(value); + } + + static Integer asInteger(Map params, String key) { + Object value = params == null ? null : params.get(key); + if (value instanceof Number number) { + return number.intValue(); + } + if (value instanceof String text && !text.isBlank()) { + try { + return Integer.valueOf(text.trim()); + } catch (NumberFormatException e) { + return null; + } + } + return null; + } + + /** 前端上报的是无时区的本地时间字符串;解析失败按缺失处理,不影响主流程 */ + static LocalDateTime asLocalDateTime(Map params, String key) { + String text = asString(params, key); + if (text == null || text.isBlank()) { + return null; + } + try { + return LocalDateTime.parse(text.trim()); + } catch (DateTimeParseException e) { + log.warn("AI 任务参数[{}]时间格式无法解析,按缺失处理: {}", key, text); + return null; + } + } + + /** 字符串数组参数;非集合类型按单值处理,空元素与空白元素被丢弃 */ + static List asStringList(Map params, String key) { + Object value = params == null ? null : params.get(key); + if (value == null) { + return List.of(); + } + Collection raw = value instanceof Collection collection ? collection : List.of(value); + List result = new ArrayList<>(); + for (Object item : raw) { + if (item == null) { + continue; + } + String text = String.valueOf(item).trim(); + if (!text.isEmpty()) { + result.add(text); + } + } + return result; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/MarkerServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/MarkerServiceImpl.java index efd536a..ee09c8e 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/MarkerServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/MarkerServiceImpl.java @@ -16,6 +16,7 @@ import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.mapper.UserTagMapper; import com.guo.learningprogresstracker.service.MarkerService; +import com.guo.learningprogresstracker.service.ReviewTagMindMapService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -46,6 +47,7 @@ public class MarkerServiceImpl implements MarkerService { private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final TasksMapper tasksMapper; private final UserTagMapper userTagMapper; + private final ReviewTagMindMapService reviewTagMindMapService; @Override public List listByObject(MarkerObjectTypeEnum objectType, String objectNum) { @@ -104,6 +106,8 @@ public class MarkerServiceImpl implements MarkerService { markerMapper.insert(marker); // 打标签时输入的新名字自动补进字典(闭环-03) ensureDictionaryEntry(name); + // 碎片多了一个标签 → 相关标签导图置「待更新」(闭环-04,不自动重建) + markTagMindMapsStale(objectType, List.of(name)); return marker; } @@ -115,6 +119,8 @@ public class MarkerServiceImpl implements MarkerService { throw new ErrorParameterException("这是系统标记,不能删除"); } markerMapper.deleteById(existing.getId()); + // 碎片少了一个标签 → 相关标签导图置「待更新」(闭环-04,不自动重建) + markTagMindMapsStale(MarkerObjectTypeEnum.parse(existing.getObjectType()), List.of(existing.getMarkerName())); } @Override @@ -153,6 +159,8 @@ public class MarkerServiceImpl implements MarkerService { renamed++; } log.info("标签[{}]重命名为[{}],影响 {} 条标记", from, to, renamed); + // 两个名字的取材范围都变了 → 相关标签导图置「待更新」(闭环-04,不自动重建) + reviewTagMindMapService.markStaleForTags(List.of(from, to)); return renamed; } @@ -330,12 +338,33 @@ public class MarkerServiceImpl implements MarkerService { if (objectType == null || !StringUtils.hasText(objectNum)) { return; } + // 对象即将消失:先记下它的用户标签,才能把相关标签导图置「待更新」(闭环-04) + List removedTags = List.of(); + if (objectType == MarkerObjectTypeEnum.FRAGMENT) { + removedTags = markerMapper.selectList(Wrappers.lambdaQuery() + .eq(MarkerEntity::getObjectType, objectType.name()) + .eq(MarkerEntity::getObjectNum, objectNum.trim()) + .eq(MarkerEntity::getKind, MarkerKindEnum.USER.name()) + .select(MarkerEntity::getMarkerName)) + .stream() + .map(MarkerEntity::getMarkerName) + .toList(); + } int removed = markerMapper.delete(Wrappers.lambdaQuery() .eq(MarkerEntity::getObjectType, objectType.name()) .eq(MarkerEntity::getObjectNum, objectNum.trim())); if (removed > 0) { log.info("对象[{}/{}]的 {} 条标记已随对象删除", objectType, objectNum, removed); } + markTagMindMapsStale(objectType, removedTags); + } + + /** 碎片标签发生变化时的下游影响:相关标签导图置「待更新」,重建由用户手动触发(闭环-04) */ + private void markTagMindMapsStale(MarkerObjectTypeEnum objectType, Collection changedTags) { + if (objectType != MarkerObjectTypeEnum.FRAGMENT || changedTags == null || changedTags.isEmpty()) { + return; + } + reviewTagMindMapService.markStaleForTags(changedTags); } private MarkerEntity requireMarker(Integer id) throws NotFindEntitiesException { diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java index 3366efe..347f6a8 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java @@ -1,13 +1,14 @@ package com.guo.learningprogresstracker.service.impl; +import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; +import com.guo.learningprogresstracker.enums.MindMapGenerateModeEnum; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; import com.guo.learningprogresstracker.service.StandardMindMapService; import com.guo.learningprogresstracker.utils.MindMapTreeTool; -import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @@ -26,9 +27,6 @@ import java.util.Map; @RequiredArgsConstructor public class MindMapAiTaskHandler implements AiTaskHandler { - private static final String MODE_INCREMENTAL = "incremental"; - private static final String MODE_ENSURE = "ensure"; - private final StandardMindMapService standardMindMapService; private final ObjectMapper objectMapper; @@ -39,19 +37,19 @@ public class MindMapAiTaskHandler implements AiTaskHandler { @Override public Map execute(AiTaskEntity task, Map params) { - String mode = params.get("mode") == null ? "full" : String.valueOf(params.get("mode")); + MindMapGenerateModeEnum mode = MindMapGenerateModeEnum.parse(AiTaskParams.asString(params, "mode")); String taskNum = task.getTargetNum(); try { // ensure 模式下已有导图就直接返回,不做无意义的重新生成(也不重复计费) - if (MODE_ENSURE.equalsIgnoreCase(mode)) { + if (mode == MindMapGenerateModeEnum.ENSURE) { ReviewStandardMindMapEntity existing = standardMindMapService.getExisting(taskNum); if (existing != null) { return toPayload(existing, "已存在,跳过生成"); } return toPayload(standardMindMapService.regenerate(taskNum), "按需生成"); } - if (MODE_INCREMENTAL.equalsIgnoreCase(mode)) { + if (mode == MindMapGenerateModeEnum.INCREMENTAL) { return toPayload(standardMindMapService.incrementalGenerate(taskNum), "增量更新"); } return toPayload(standardMindMapService.regenerate(taskNum), "全量生成"); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGenerator.java b/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGenerator.java new file mode 100644 index 0000000..3c09295 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGenerator.java @@ -0,0 +1,72 @@ +package com.guo.learningprogresstracker.service.impl; + +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.TaskApplicationEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.exception.OperationFailedException; +import com.guo.learningprogresstracker.service.MindMapAiClient; +import com.guo.learningprogresstracker.utils.MindMapNode; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.Comparator; +import java.util.List; +import java.util.Optional; + +/** + * 「碎片 → 缩进大纲」生成链路:优先 AI 客户端,失败时降级到内置规则生成器。 + * + *

任务导图与标签导图共用它,避免两种取材范围出现两套客户端选择与降级口径。 + * 取材(按内容归属 / 按标签集合)由调用方决定,本类只回答「给定素材怎么产出树」。

+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class MindMapOutlineGenerator { + + private static final String GENERATOR_BUILTIN = "BUILTIN"; + + private final List aiClients; + + /** + * @param root 导图根节点 + * @param generatorName 生成来源标识({@code BUILTIN} / AI 客户端名);沿用首选客户端的标识, + * 与既有任务导图口径一致 + */ + public record GeneratedOutline(MindMapNode root, String generatorName) { + } + + /** + * 生成导图树;没有任何可用生成器或全部生成失败时抛出用户可见的业务异常。 + */ + public GeneratedOutline generate(TaskEntity scope, + List fragments, + List applications) throws OperationFailedException { + // 优先选 AI 客户端(非 BUILTIN),其次内置生成器:AI 提升结构质量,内置规则保证 AI 不可用时仍能生成 + MindMapAiClient client = aiClients.stream() + .filter(MindMapAiClient::isAvailable) + .min(Comparator.comparing(c -> GENERATOR_BUILTIN.equals(c.generatorName()) ? 1 : 0)) + .orElse(null); + if (client == null) { + log.warn("没有可用的思维导图生成器"); + throw new OperationFailedException("思维导图暂时生成不了,请稍后再试"); + } + + Optional optRoot = client.generate(scope, fragments, applications, null); + if (optRoot.isEmpty() && !GENERATOR_BUILTIN.equals(client.generatorName())) { + log.info("AI 思维导图生成失败,降级到内置生成器"); + MindMapAiClient fallback = aiClients.stream() + .filter(c -> GENERATOR_BUILTIN.equals(c.generatorName()) && c.isAvailable()) + .findFirst().orElse(null); + if (fallback != null) { + optRoot = fallback.generate(scope, fragments, applications, null); + } + } + if (optRoot.isEmpty()) { + log.warn("思维导图生成失败,已尝试全部生成器"); + throw new OperationFailedException("思维导图生成失败了,请稍后再试"); + } + return new GeneratedOutline(optRoot.get(), client.generatorName()); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java index 45184c8..c1d4c3e 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java @@ -12,8 +12,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import java.time.LocalDateTime; -import java.time.format.DateTimeParseException; import java.util.Map; /** @@ -36,15 +34,15 @@ public class RecallCompareAiTaskHandler implements AiTaskHandler { @Override public Map execute(AiTaskEntity task, Map params) { - String recallOutline = asString(params, "recallOutline"); + String recallOutline = AiTaskParams.asString(params, "recallOutline"); if (!StringUtils.hasText(recallOutline)) { throw new AiTaskFailedException("请先填写回忆大纲"); } - String focusPath = asString(params, "focusPath"); + String focusPath = AiTaskParams.asString(params, "focusPath"); ReviewTiming timing = new ReviewTiming( - asTime(params, "reviewStartedAt"), - asTime(params, "reviewLastInteractionAt"), - asInteger(params, "reviewDurationSeconds")); + AiTaskParams.asLocalDateTime(params, "reviewStartedAt"), + AiTaskParams.asLocalDateTime(params, "reviewLastInteractionAt"), + AiTaskParams.asInteger(params, "reviewDurationSeconds")); try { RecallCompareOutcome outcome = standardMindMapService.recallCompare( @@ -56,38 +54,4 @@ public class RecallCompareAiTaskHandler implements AiTaskHandler { throw new AiTaskFailedException(e.getMessage()); } } - - private static String asString(Map params, String key) { - Object value = params.get(key); - return value == null ? null : String.valueOf(value); - } - - private static Integer asInteger(Map params, String key) { - Object value = params.get(key); - if (value instanceof Number number) { - return number.intValue(); - } - if (value instanceof String text && !text.isBlank()) { - try { - return Integer.valueOf(text.trim()); - } catch (NumberFormatException e) { - return null; - } - } - return null; - } - - /** 前端上报的是无时区的本地时间字符串;解析失败按缺失处理,不影响对比本身 */ - private static LocalDateTime asTime(Map params, String key) { - String text = asString(params, key); - if (!StringUtils.hasText(text)) { - return null; - } - try { - return LocalDateTime.parse(text.trim()); - } catch (DateTimeParseException e) { - log.warn("AI 任务参数[{}]时间格式无法解析,按缺失处理: {}", key, text); - return null; - } - } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java new file mode 100644 index 0000000..ed78240 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java @@ -0,0 +1,307 @@ +package com.guo.learningprogresstracker.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.dto.FragmentTagMatch; +import com.guo.learningprogresstracker.dto.TagMindMapView; +import com.guo.learningprogresstracker.dto.TagScope; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; +import com.guo.learningprogresstracker.exception.ErrorParameterException; +import com.guo.learningprogresstracker.exception.NotFindEntitiesException; +import com.guo.learningprogresstracker.exception.OperationFailedException; +import com.guo.learningprogresstracker.mapper.MarkerMapper; +import com.guo.learningprogresstracker.mapper.ReviewTagMindMapMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.service.ReviewTagMindMapService; +import com.guo.learningprogresstracker.utils.MindMapNode; +import com.guo.learningprogresstracker.utils.MindMapTreeTool; +import com.guo.learningprogresstracker.utils.TagScopeTool; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +/** + * 标签思维导图服务实现(闭环-04)。 + * + *

取材与生成两条链路都刻意与任务导图共用口径:素材来自带这些标签的碎片(软删除的不取材), + * 生成走 {@link MindMapOutlineGenerator}(AI 优先、内置规则降级)。

+ */ +@Slf4j +@Service +@RequiredArgsConstructor +public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { + + private static final String GENERATOR_USER = "USER"; + private static final String GENERATOR_USER_MERGE = "USER_MERGE"; + private static final String GENERATOR_VERSION = "1.0"; + + /** 与标记、标签字典的列宽一致 */ + private static final int MAX_TAG_NAME_LENGTH = 100; + + private final ReviewTagMindMapMapper tagMindMapMapper; + private final MarkerMapper markerMapper; + private final StudyReportFragmentsMapper studyReportFragmentsMapper; + private final MindMapOutlineGenerator outlineGenerator; + private final ObjectMapper objectMapper; + + // ============ 范围解析 ============ + + @Override + public TagScope resolveScope(List tags, String mode) throws ErrorParameterException { + List cleaned = new ArrayList<>(); + if (tags != null) { + for (String tag : tags) { + if (!StringUtils.hasText(tag)) { + continue; + } + String name = tag.trim(); + if (name.length() > MAX_TAG_NAME_LENGTH) { + throw new ErrorParameterException("标签名太长了,请控制在 " + MAX_TAG_NAME_LENGTH + " 个字符以内"); + } + cleaned.add(name); + } + } + if (cleaned.isEmpty()) { + throw new ErrorParameterException("请先选择要复习的标签"); + } + TagCombineModeEnum combineMode = TagCombineModeEnum.parse(mode); + if (combineMode == null) { + throw new ErrorParameterException("取数方式只能是并集或交集"); + } + List canonicalTags = TagScopeTool.canonicalTags(cleaned); + if (canonicalTags.size() > TagScopeTool.MAX_RANGE_TAGS) { + throw new ErrorParameterException("一次最多按 " + TagScopeTool.MAX_RANGE_TAGS + " 个标签复习,请把范围缩小一些"); + } + return new TagScope(TagScopeTool.scopeKey(canonicalTags, combineMode), + canonicalTags, TagScopeTool.normalizedTags(canonicalTags), combineMode); + } + + // ============ 读取 ============ + + @Override + public TagMindMapView query(TagScope scope) { + TagMindMapView view = new TagMindMapView(); + view.setScopeKey(scope.scopeKey()); + view.setTags(scope.tags()); + view.setMode(scope.mode().name()); + view.setMap(queryByScopeKey(scope.scopeKey())); + return view; + } + + // ============ 用户编辑 ============ + + @Override + @Transactional + public ReviewTagMindMapEntity updateByOutline(TagScope scope, String outline) { + ReviewTagMindMapEntity existing = queryByScopeKey(scope.scopeKey()); + boolean create = existing == null; + if (create) { + existing = newEntity(scope); + } + + MindMapNode root = MindMapTreeTool.parseOutline(outline); + existing.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图"); + existing.setContent(MindMapTreeTool.toJson(root, objectMapper)); + existing.setOutline(outline); + existing.setGenerator(GENERATOR_USER); + existing.setGeneratorVersion(null); + existing.setSummary("用户编辑,共 " + MindMapTreeTool.countNodes(root) + " 个节点"); + existing.setGeneratedTime(LocalDateTime.now()); + + if (create) { + tagMindMapMapper.insert(existing); + } else { + tagMindMapMapper.updateById(existing); + } + return existing; + } + + // ============ 生成 ============ + + @Override + public ReviewTagMindMapEntity regenerate(TagScope scope) throws OperationFailedException { + // 并发生成由 ai_tasks 的进行中任务判定拦截(AI-04),不依赖 JVM 内存锁 + return doGenerate(scope); + } + + @Override + public ReviewTagMindMapEntity incrementalGenerate(TagScope scope) + throws NotFindEntitiesException, OperationFailedException { + ReviewTagMindMapEntity existing = queryByScopeKey(scope.scopeKey()); + if (existing == null) { + log.warn("标签范围[{}]的导图尚不存在,无法增量更新", scope.scopeKey()); + throw new NotFindEntitiesException("这些标签还没有生成过思维导图,请先完整生成一次哦"); + } + + // 生成(可能调用 AI)不放在事务里:等待 AI 期间不应占用数据库连接(AI-01) + ReviewTagMindMapEntity fresh = doGenerate(scope); + + // 合并新旧树:保留用户编辑过的节点,追加新节点 + MindMapNode oldRoot = MindMapTreeTool.fromJson(existing.getContent(), objectMapper); + MindMapNode newRoot = MindMapTreeTool.fromJson(fresh.getContent(), objectMapper); + MindMapNode merged = MindMapTreeTool.mergeTrees(oldRoot, newRoot); + + existing.setContent(MindMapTreeTool.toJson(merged, objectMapper)); + existing.setOutline(MindMapTreeTool.toFullOutline(merged)); + existing.setTitle(merged.getTitle() != null ? merged.getTitle() : "思维导图"); + existing.setGenerator(GENERATOR_USER_MERGE); + existing.setGeneratorVersion(fresh.getGeneratorVersion()); + existing.setSummary("增量更新,共 " + MindMapTreeTool.countNodes(merged) + " 个节点"); + existing.setSourceFragmentCount(fresh.getSourceFragmentCount()); + existing.setGeneratedTime(LocalDateTime.now()); + tagMindMapMapper.updateById(existing); + return existing; + } + + // ============ 素材变化 ============ + + @Override + @Transactional + public void markStaleForTags(Collection changedTagNames) { + Set changed = Set.copyOf(TagScopeTool.normalizedTags(changedTagNames)); + if (changed.isEmpty()) { + return; + } + List maps = tagMindMapMapper.selectList( + Wrappers.lambdaQuery() + .eq(ReviewTagMindMapEntity::getNeedsUpdate, false)); + int marked = 0; + for (ReviewTagMindMapEntity map : maps) { + Set mapTags = Set.copyOf( + TagScopeTool.normalizedTags(TagScopeTool.parseStoredTags(map.getTagNames()))); + if (Collections.disjoint(mapTags, changed)) { + continue; + } + ReviewTagMindMapEntity patch = new ReviewTagMindMapEntity(); + patch.setId(map.getId()); + patch.setNeedsUpdate(true); + patch.setNeedsUpdateTime(LocalDateTime.now()); + tagMindMapMapper.updateById(patch); + marked++; + } + if (marked > 0) { + log.info("标签[{}]的素材发生变化,{} 张标签导图已置为待更新(重建仍由用户手动触发)", + String.join("、", changed), marked); + } + } + + // ============ 内部方法 ============ + + private ReviewTagMindMapEntity doGenerate(TagScope scope) throws OperationFailedException { + List fragments = loadFragments(scope); + if (fragments.isEmpty()) { + log.warn("标签范围[{}]没有取材到知识碎片,无法生成导图", scope.scopeKey()); + throw new OperationFailedException("这些标签下还没有内容哦,先给内容打上标签再来吧"); + } + + // 标签范围没有任务实体:生成链路以「范围名 + 范围描述」作为素材头, + // 这里用一个不落库的临时 TaskEntity 承载它们,从而沿用既有的碎片 → 大纲生成链路 + TaskEntity scopeTask = new TaskEntity(); + scopeTask.setTaskName(scope.displayName()); + scopeTask.setTaskDescription("按标签复习:" + scope.displayName() + + "(" + scope.mode().getDescription() + "),共取材 " + fragments.size() + " 条知识碎片"); + + MindMapOutlineGenerator.GeneratedOutline generated = + outlineGenerator.generate(scopeTask, fragments, List.of()); + MindMapNode root = generated.root(); + + ReviewTagMindMapEntity entity = queryByScopeKey(scope.scopeKey()); + boolean create = entity == null; + if (create) { + entity = newEntity(scope); + } + + entity.setTitle(root.getTitle() != null ? root.getTitle() : scope.displayName()); + entity.setContent(MindMapTreeTool.toJson(root, objectMapper)); + entity.setOutline(MindMapTreeTool.toFullOutline(root)); + entity.setSummary("共 " + MindMapTreeTool.countNodes(root) + " 个节点,最大层级 " + + MindMapTreeTool.maxDepth(root) + ",取材 " + fragments.size() + " 条碎片"); + entity.setGenerator(generated.generatorName()); + entity.setGeneratorVersion(GENERATOR_VERSION); + entity.setSourceFragmentCount(fragments.size()); + entity.setGeneratedTime(LocalDateTime.now()); + // 重建完成后清除「待更新」标记 + entity.setNeedsUpdate(false); + entity.setNeedsUpdateTime(null); + + if (create) { + tagMindMapMapper.insert(entity); + } else { + tagMindMapMapper.updateById(entity); + } + return entity; + } + + private ReviewTagMindMapEntity newEntity(TagScope scope) { + ReviewTagMindMapEntity entity = new ReviewTagMindMapEntity(); + entity.setScopeKey(scope.scopeKey()); + entity.setCombineMode(scope.mode().name()); + entity.setTagNames(TagScopeTool.toStoredTags(scope.tags())); + return entity; + } + + private ReviewTagMindMapEntity queryByScopeKey(String scopeKey) { + return tagMindMapMapper.selectOne(Wrappers.lambdaQuery() + .eq(ReviewTagMindMapEntity::getScopeKey, scopeKey) + .last("LIMIT 1")); + } + + /** + * 取数:带这些标签的知识碎片。并集取「带任一标签」,交集取「同时带全部标签」; + * 软删除的碎片由 {@code @TableLogic} 自动排除。 + */ + private List loadFragments(TagScope scope) { + List matches = markerMapper.countUserTagsPerFragment(scope.normalizedTags()); + int requiredTagCount = scope.mode() == TagCombineModeEnum.INTERSECT + ? scope.normalizedTags().size() : 1; + + List fragmentIds = new ArrayList<>(); + for (FragmentTagMatch match : matches) { + if (match.getMatchedTagCount() == null || match.getMatchedTagCount() < requiredTagCount) { + continue; + } + Integer fragmentId = parseFragmentId(match.getObjectNum()); + if (fragmentId != null) { + fragmentIds.add(fragmentId); + } + } + if (fragmentIds.isEmpty()) { + return List.of(); + } + return studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() + .in(StudyReportFragmentsEntity::getId, fragmentIds) + .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); + } + + /** 碎片标记的 object_num 一定是数字 id;遇到脏数据只跳过该行,不让整条取材链路失败 */ + private static Integer parseFragmentId(String objectNum) { + if (objectNum == null || objectNum.isBlank()) { + return null; + } + String trimmed = objectNum.trim(); + for (int i = 0; i < trimmed.length(); i++) { + if (!Character.isDigit(trimmed.charAt(i))) { + log.warn("标记对象标识[{}]不是碎片 id,已跳过", objectNum); + return null; + } + } + try { + return Integer.valueOf(trimmed); + } catch (NumberFormatException e) { + log.warn("标记对象标识[{}]超出碎片 id 范围,已跳过", objectNum); + return null; + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImpl.java index 72e61d8..a322334 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImpl.java @@ -9,7 +9,6 @@ import com.guo.learningprogresstracker.entity.*; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; import com.guo.learningprogresstracker.mapper.*; -import com.guo.learningprogresstracker.service.MindMapAiClient; import com.guo.learningprogresstracker.service.StandardMindMapService; import com.guo.learningprogresstracker.utils.CompareResult; import com.guo.learningprogresstracker.utils.MindMapNode; @@ -39,7 +38,7 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { private final TaskApplicationMapper taskApplicationMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; - private final List aiClients; + private final MindMapOutlineGenerator outlineGenerator; private final ObjectMapper objectMapper; private final AiServiceClient aiServiceClient; @@ -136,9 +135,8 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { standard = doGenerate(taskNum); } - // 2. 解析标准树和用户回忆树 + // 2. 解析标准树(用户回忆大纲在对比入口里解析,两条复习范围共用同一段逻辑) MindMapNode standardRoot = MindMapTreeTool.fromJson(standard.getContent(), objectMapper); - MindMapNode recallRoot = MindMapTreeTool.parseOutline(recallOutline); // 2b. 若指定了起点节点路径,提取该子树作为对比基准 MindMapNode compareRoot = standardRoot; @@ -150,28 +148,8 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { } } - // 3. 执行对比(优先 AI 语义对比,失败时降级为内置算法) - CompareResult result; - if (aiServiceClient.isConfigured()) { - String taskName = tasksMapper.selectOne( - Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum).last("LIMIT 1")) - .getTaskName(); - var optJson = aiServiceClient.compareRecall( - taskName, - MindMapTreeTool.toFullOutline(compareRoot), - recallOutline - ); - if (optJson.isPresent()) { - result = buildCompareResultFromAI(optJson.get(), compareRoot); - log.info("AI 回忆对比: taskNum={}, recallRatio={}, evaluation={}", - taskNum, result.getRecallRatio(), - result.getEvaluation() != null ? result.getEvaluation().substring(0, Math.min(50, result.getEvaluation().length())) : ""); - } else { - result = compareTrees(compareRoot, recallRoot); - } - } else { - result = compareTrees(compareRoot, recallRoot); - } + // 3. 执行对比(优先 AI 语义对比,失败时降级为内置算法)——与标签导图共用同一套对比口径 + CompareResult result = compareWithRecall(resolveScopeName(taskNum), compareRoot, recallOutline); // 4. 序列化对比结果 String resultJson; @@ -239,6 +217,36 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { return result; } + @Override + public CompareResult compareWithRecall(String scopeName, MindMapNode standardRoot, String recallOutline) { + MindMapNode recallRoot = MindMapTreeTool.parseOutline(recallOutline); + + // 优先 AI 语义对比,AI 不可用或返回失败时降级为内置文本相似度匹配 + if (aiServiceClient.isConfigured()) { + var optJson = aiServiceClient.compareRecall( + scopeName, + MindMapTreeTool.toFullOutline(standardRoot), + recallOutline); + if (optJson.isPresent()) { + CompareResult result = buildCompareResultFromAI(optJson.get(), standardRoot); + log.info("AI 回忆对比: scope={}, recallRatio={}, evaluation={}", + scopeName, result.getRecallRatio(), + result.getEvaluation() != null + ? result.getEvaluation().substring(0, Math.min(50, result.getEvaluation().length())) + : ""); + return result; + } + } + return compareTrees(standardRoot, recallRoot); + } + + /** 对比口径里的范围名:默认用任务名(导图根节点也是它) */ + private String resolveScopeName(String taskNum) { + TaskEntity task = tasksMapper.selectOne(Wrappers.lambdaQuery() + .eq(TaskEntity::getTaskNum, taskNum).last("LIMIT 1")); + return task == null || !StringUtils.hasText(task.getTaskName()) ? taskNum : task.getTaskName(); + } + // ============ 对比算法核心 ============ /** @@ -428,34 +436,10 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { throw new OperationFailedException("这个任务还没开始学习哦,学习后产生知识碎片后再来吧"); } - // 优先选 AI 客户端(非 BUILTIN),其次内置生成器 - MindMapAiClient client = aiClients.stream() - .filter(MindMapAiClient::isAvailable) - .min(Comparator.comparing(c -> "BUILTIN".equals(c.generatorName()) ? 1 : 0)) - .orElse(null); + // 「碎片 → 缩进大纲」生成链路(AI 优先、内置规则降级)与标签导图共用同一套口径 + MindMapOutlineGenerator.GeneratedOutline generated = outlineGenerator.generate(task, fragments, applications); - if (client == null) { - log.warn("任务[{}]没有可用的思维导图生成器", taskNum); - throw new OperationFailedException("思维导图暂时生成不了,请稍后再试"); - } - - Optional optRoot = client.generate(task, fragments, applications, null); - // AI 生成失败时尝试降级到内置生成器 - if (optRoot.isEmpty() && !"BUILTIN".equals(client.generatorName())) { - log.info("AI 思维导图生成失败,降级到内置生成器"); - MindMapAiClient fallback = aiClients.stream() - .filter(c -> "BUILTIN".equals(c.generatorName()) && c.isAvailable()) - .findFirst().orElse(null); - if (fallback != null) { - optRoot = fallback.generate(task, fragments, applications, null); - } - } - if (optRoot.isEmpty()) { - log.warn("任务[{}]思维导图生成失败,已尝试全部生成器", taskNum); - throw new OperationFailedException("思维导图生成失败了,请稍后再试"); - } - - MindMapNode root = optRoot.get(); + MindMapNode root = generated.root(); String contentJson = MindMapTreeTool.toJson(root, objectMapper); String outline = MindMapTreeTool.toFullOutline(root); int nodeCount = MindMapTreeTool.countNodes(root); @@ -472,7 +456,7 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { entity.setContent(contentJson); entity.setOutline(outline); entity.setSummary("共 " + nodeCount + " 个节点,最大层级 " + depth); - entity.setGenerator(client.generatorName()); + entity.setGenerator(generated.generatorName()); entity.setGeneratorVersion("1.0"); entity.setSourceReportCount(0); entity.setSourceFragmentCount(fragments.size()); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/TagMindMapAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/impl/TagMindMapAiTaskHandler.java new file mode 100644 index 0000000..61d9ed5 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/TagMindMapAiTaskHandler.java @@ -0,0 +1,91 @@ +package com.guo.learningprogresstracker.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.dto.TagScope; +import com.guo.learningprogresstracker.entity.AiTaskEntity; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; +import com.guo.learningprogresstracker.enums.MindMapGenerateModeEnum; +import com.guo.learningprogresstracker.exception.ErrorParameterException; +import com.guo.learningprogresstracker.exception.NotFindEntitiesException; +import com.guo.learningprogresstracker.exception.OperationFailedException; +import com.guo.learningprogresstracker.service.ReviewTagMindMapService; +import com.guo.learningprogresstracker.utils.MindMapTreeTool; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 标签思维导图生成任务(闭环-04)。 + * + *

任务目标 {@code targetNum} 是标签范围的规范键({@code TagScope#scopeKey}), + * 范围本身由参数给出:{@code tags}(标签集合)、{@code combineMode}(UNION/INTERSECT)、 + * {@code mode}(full/incremental/ensure,与任务导图的同名参数同义)。 + * 目标与参数不一致说明前端拿了过期的范围,直接失败,避免把这张导图写到别的范围上。

+ * + *

生成模式与任务导图一致,但**不会**被素材变化自动触发:素材变化只把导图置「待更新」, + * 本任务由用户手动发起(与归属-01 的任务导图同口径)。

+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class TagMindMapAiTaskHandler implements AiTaskHandler { + + private final ReviewTagMindMapService reviewTagMindMapService; + private final ObjectMapper objectMapper; + + @Override + public AiTaskTypeEnum type() { + return AiTaskTypeEnum.TAG_MIND_MAP; + } + + @Override + public Map execute(AiTaskEntity task, Map params) { + MindMapGenerateModeEnum mode = MindMapGenerateModeEnum.parse(AiTaskParams.asString(params, "mode")); + + try { + TagScope scope = reviewTagMindMapService.resolveScope( + AiTaskParams.asStringList(params, "tags"), AiTaskParams.asString(params, "combineMode")); + requireScopeMatches(task, scope); + + // ensure 模式下已有导图就直接返回,不做无意义的重新生成(也不重复计费) + if (mode == MindMapGenerateModeEnum.ENSURE) { + ReviewTagMindMapEntity existing = reviewTagMindMapService.query(scope).getMap(); + if (existing != null) { + return toPayload(existing, scope, "已存在,跳过生成"); + } + return toPayload(reviewTagMindMapService.regenerate(scope), scope, "按需生成"); + } + if (mode == MindMapGenerateModeEnum.INCREMENTAL) { + return toPayload(reviewTagMindMapService.incrementalGenerate(scope), scope, "增量更新"); + } + return toPayload(reviewTagMindMapService.regenerate(scope), scope, "全量生成"); + } catch (ErrorParameterException | NotFindEntitiesException | OperationFailedException e) { + throw new AiTaskFailedException(e.getMessage()); + } + } + + /** 任务目标必须是这批参数算出来的范围键:不一致时宁可失败,也不要写错范围 */ + private void requireScopeMatches(AiTaskEntity task, TagScope scope) { + if (!scope.scopeKey().equals(task.getTargetNum())) { + log.warn("标签导图任务的参数与目标不一致: targetNum={}, 参数范围={}", task.getTargetNum(), scope.scopeKey()); + throw new AiTaskFailedException("标签范围和导图标识对不上,请刷新页面后重试"); + } + } + + private Map toPayload(ReviewTagMindMapEntity entity, TagScope scope, String summary) { + Map payload = new LinkedHashMap<>(); + payload.put("tagMapId", entity.getId()); + payload.put("scopeKey", scope.scopeKey()); + payload.put("tags", scope.tags()); + payload.put("mode", scope.mode().name()); + payload.put("generator", entity.getGenerator()); + payload.put("nodeCount", MindMapTreeTool.countNodes( + MindMapTreeTool.fromJson(entity.getContent(), objectMapper))); + payload.put("summary", summary); + return payload; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java b/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java new file mode 100644 index 0000000..14ab8e1 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java @@ -0,0 +1,125 @@ +package com.guo.learningprogresstracker.utils; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TreeSet; + +/** + * 复习范围(标签集合 + 取数模式)的规范化工具(闭环-04)。 + * + *

口径(2026-10-10 维护者确认,见 lpt-docs/docs/concepts/standard-mind-map.md「导图的范围」): + * 范围的规范键 = 「标签集合(排序、归一化后的稳定拼接)+ 取数模式」的稳定哈希,集合相同且模式相同即同一张导图。 + * 标签归一化口径与标签字典一致:去首尾空白 + 小写({@code user_tags.normalized_name} 同口径)。

+ */ +public final class TagScopeTool { + + /** 一次复习最多可选标签数:范围键要落库,标签多到十来个时界面上也已不可读 */ + public static final int MAX_RANGE_TAGS = 10; + + /** 存储用分隔符:标签名由用户输入,用不可能出现在标签里的控制字符拼接才不会有歧义 */ + private static final String TAG_SEPARATOR = "\u001F"; + private static final String MODE_SEPARATOR = "\u001E"; + + /** 标签集合列是 JSON 数组,只承载字符串,不涉及时间等需要配置的类型 */ + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private TagScopeTool() { + } + + /** 标签归一化:去首尾空白 + 小写 */ + public static String normalize(String tagName) { + return tagName == null ? "" : tagName.trim().toLowerCase(Locale.ROOT); + } + + /** 规范化标签集合:去空白、按归一化名去重、按归一化名排序 */ + public static List normalizedTags(Collection tagNames) { + TreeSet normalized = new TreeSet<>(); + if (tagNames != null) { + for (String tagName : tagNames) { + String key = normalize(tagName); + if (!key.isEmpty()) { + normalized.add(key); + } + } + } + return new ArrayList<>(normalized); + } + + /** + * 展示用标签集合:按归一化名去重与排序,保留输入的原样写法(同一归一化名重复出现时保留先出现的那一个)。 + */ + public static List canonicalTags(Collection tagNames) { + Map byKey = new LinkedHashMap<>(); + if (tagNames != null) { + for (String tagName : tagNames) { + String key = normalize(tagName); + if (!key.isEmpty()) { + byKey.putIfAbsent(key, tagName.trim()); + } + } + } + return byKey.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(Map.Entry::getValue) + .toList(); + } + + /** + * 范围的规范键:标签集合(归一化、排序后稳定拼接)与取数模式的 SHA-256。 + */ + public static String scopeKey(Collection tagNames, TagCombineModeEnum mode) { + String canonical = String.join(TAG_SEPARATOR, normalizedTags(tagNames)) + + MODE_SEPARATOR + (mode == null ? TagCombineModeEnum.defaultMode() : mode).name(); + return sha256Hex(canonical); + } + + /** 标签集合落库:JSON 数组(展示名,已按归一化名排序) */ + public static String toStoredTags(Collection tagNames) { + try { + return MAPPER.writeValueAsString(canonicalTags(tagNames)); + } catch (Exception e) { + // List 序列化不会失败;真出问题也不能让导图链路整体挂掉 + throw new IllegalStateException("标签集合序列化失败", e); + } + } + + /** 回读落库的标签集合;内容缺失或损坏时按空集合处理 */ + public static List parseStoredTags(String storedTags) { + if (storedTags == null || storedTags.isBlank()) { + return List.of(); + } + try { + List tags = MAPPER.readValue(storedTags, new TypeReference<>() { + }); + return tags == null ? List.of() : tags; + } catch (Exception e) { + return List.of(); + } + } + + private static String sha256Hex(String text) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(hash.length * 2); + for (byte b : hash) { + hex.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException e) { + // JDK 必然提供 SHA-256 + throw new IllegalStateException("SHA-256 不可用", e); + } + } +} diff --git a/src/main/resources/db/migration/V20261010_2__add_tag_mind_maps.sql b/src/main/resources/db/migration/V20261010_2__add_tag_mind_maps.sql new file mode 100644 index 0000000..b57afe2 --- /dev/null +++ b/src/main/resources/db/migration/V20261010_2__add_tag_mind_maps.sql @@ -0,0 +1,40 @@ +-- 闭环-04:标签导图(按标签集合复习时的对照基准)。 +-- +-- 口径来源(2026-10-10 维护者确认,结论见 lpt-docs/docs/concepts/standard-mind-map.md「导图的范围」): +-- 标签导图与任务导图并存:任务导图回答「这个任务学到了什么结构」, +-- 标签导图回答「这个概念在不同任务里呈现出什么结构」。 +-- 范围 = 规范化标签集合 + 取数模式(UNION 并集 / INTERSECT 交集),集合相同且模式相同即同一张导图, +-- 因此**独立成表**并以范围键寻址:不在 review_standard_mind_maps 上加维度列, +-- 也不动它的 task_num 唯一键。 +-- 素材 = 带这些标签的知识碎片(软删除的不取材);素材变化只把导图置 needs_update=1, +-- 重建由用户手动触发(与归属-01 的任务导图同口径)。 +create table review_tag_mind_maps +( + id int auto_increment comment 'id无业务含义' + primary key, + scope_key varchar(64) not null comment '范围键:标签集合(归一化、排序后拼接)与取数模式的稳定哈希', + combine_mode varchar(20) not null comment '取数模式:UNION=并集(默认)/ INTERSECT=交集', + tag_names varchar(1100) not null comment '范围的标签集合(JSON 数组,展示保留输入原样,按归一化名排序)', + title varchar(255) not null comment '标签导图标题(根节点标题)', + content mediumtext not null comment '导图统一树结构JSON(根节点:{title, notes, children})', + outline mediumtext null comment '导图缩进大纲文本(用于展示与编辑)', + summary text null comment '生成摘要', + generator varchar(30) not null default 'BUILTIN' comment '生成来源:BUILTIN/AI/USER/USER_MERGE', + generator_version varchar(64) null comment '生成器版本或AI模型名', + source_fragment_count int default 0 not null comment '生成时取材的碎片数', + generated_time datetime null comment '最近生成时间', + needs_update tinyint(1) default 0 not null comment '素材变化后置为1,表示需要重建;重建由用户手动触发', + needs_update_time datetime null comment '置为待更新的时间', + created_time datetime not null comment '创建时间', + created_by varchar(255) null, + last_modified_time datetime null, + last_modified_by varchar(255) null, + device_info varchar(50) null comment '操作者设备类型', + deleted int default 0 not null comment '逻辑删除符', + -- 同一用户下同一范围只有一行。键长:created_by(255×4) + scope_key(64×4) = 1276 字节, + -- 未越过 InnoDB 3072 字节上限;H2 不校验该上限,改动索引时务必用 MigrationIndexKeyLengthTest 复算。 + unique key uk_review_tag_mind_maps_scope (created_by, scope_key), + -- 素材变化时扫描「尚未待更新」的行来置位 + key idx_review_tag_mind_maps_needs_update (created_by, needs_update) +) + comment '复习模块:标签思维导图(按标签集合取材,与任务导图并存)'; diff --git a/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java new file mode 100644 index 0000000..61d93be --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java @@ -0,0 +1,89 @@ +package com.guo.learningprogresstracker.controller; + +import com.guo.learningprogresstracker.dto.TagMindMapView; +import com.guo.learningprogresstracker.dto.TagScope; +import com.guo.learningprogresstracker.dto.request.TagScopeRequest; +import com.guo.learningprogresstracker.dto.request.UpdateTagMindMapRequest; +import com.guo.learningprogresstracker.entity.CommonResult; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; +import com.guo.learningprogresstracker.service.ReviewTagMindMapService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * TagMindMapController 纯单元测试:直接 new 控制器并 mock 服务接口。 + */ +@ExtendWith(MockitoExtension.class) +class TagMindMapControllerUnitTest { + + @Mock + private ReviewTagMindMapService reviewTagMindMapService; + + @InjectMocks + private TagMindMapController controller; + + private static TagScope scope() { + return new TagScope("scope-key", List.of("Java", "并发"), List.of("java", "并发"), + TagCombineModeEnum.UNION); + } + + private static TagScopeRequest request(String mode) { + TagScopeRequest request = new TagScopeRequest(); + request.setTags(List.of("Java", "并发")); + request.setMode(mode); + return request; + } + + @Test + void query_resolvesScopeThenReadsRange() throws Exception { + TagMindMapView view = new TagMindMapView(); + when(reviewTagMindMapService.resolveScope(List.of("Java", "并发"), "UNION")).thenReturn(scope()); + when(reviewTagMindMapService.query(scope())).thenReturn(view); + + CommonResult result = controller.query(request("UNION")); + + assertEquals(200, result.getCode()); + assertSame(view, result.getData()); + } + + @Test + void query_doesNotGenerate() throws Exception { + when(reviewTagMindMapService.resolveScope(List.of("Java", "并发"), null)).thenReturn(scope()); + when(reviewTagMindMapService.query(scope())).thenReturn(new TagMindMapView()); + + controller.query(request(null)); + + // AI-02:读取路径不触发生成,生成走 /ai/tasks 的 TAG_MIND_MAP + verify(reviewTagMindMapService, org.mockito.Mockito.never()).regenerate(scope()); + } + + @Test + void updateTagMindMap_passesOutlineAndMode() throws Exception { + UpdateTagMindMapRequest request = new UpdateTagMindMapRequest(); + request.setTags(List.of("Java", "并发")); + request.setMode("INTERSECT"); + request.setOutline("- 根节点"); + ReviewTagMindMapEntity updated = new ReviewTagMindMapEntity(); + TagScope intersectScope = new TagScope("scope-key", List.of("Java", "并发"), List.of("java", "并发"), + TagCombineModeEnum.INTERSECT); + when(reviewTagMindMapService.resolveScope(List.of("Java", "并发"), "INTERSECT")).thenReturn(intersectScope); + when(reviewTagMindMapService.updateByOutline(intersectScope, "- 根节点")).thenReturn(updated); + + CommonResult result = controller.updateTagMindMap(request); + + assertEquals(200, result.getCode()); + assertSame(updated, result.getData()); + } + +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGeneratorTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGeneratorTest.java new file mode 100644 index 0000000..44a4615 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGeneratorTest.java @@ -0,0 +1,101 @@ +package com.guo.learningprogresstracker.service.impl; + +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.exception.OperationFailedException; +import com.guo.learningprogresstracker.service.MindMapAiClient; +import com.guo.learningprogresstracker.utils.MindMapNode; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * 「碎片 → 缩进大纲」生成链路的单元测试:AI 优先、失败降级内置规则、没有可用生成器时报错。 + * + *

任务导图与标签导图共用这条链路,因此这里守住的是两条取材范围共同的降级口径。

+ */ +class MindMapOutlineGeneratorTest { + + private static final TaskEntity SCOPE = new TaskEntity(); + + private static final List FRAGMENTS = List.of(new StudyReportFragmentsEntity()); + + private static MindMapAiClient client(String name, boolean available) { + MindMapAiClient client = mock(MindMapAiClient.class); + when(client.generatorName()).thenReturn(name); + when(client.isAvailable()).thenReturn(available); + return client; + } + + private static MindMapNode node(String title) { + return new MindMapNode(title); + } + + @Test + void prefersAiClientOverBuiltin() throws Exception { + MindMapAiClient builtin = client("BUILTIN", true); + MindMapAiClient ai = client("AI", true); + when(ai.generate(any(), any(), any(), isNull())).thenReturn(Optional.of(node("AI 导图"))); + MindMapOutlineGenerator generator = new MindMapOutlineGenerator(List.of(builtin, ai)); + + MindMapOutlineGenerator.GeneratedOutline outline = generator.generate(SCOPE, FRAGMENTS, List.of()); + + assertEquals("AI 导图", outline.root().getTitle()); + assertEquals("AI", outline.generatorName()); + verify(builtin, never()).generate(any(), any(), any(), any()); + } + + @Test + void fallsBackToBuiltinWhenAiReturnsNothing() throws Exception { + MindMapAiClient builtin = client("BUILTIN", true); + MindMapAiClient ai = client("AI", true); + when(ai.generate(any(), any(), any(), isNull())).thenReturn(Optional.empty()); + when(builtin.generate(any(), any(), any(), isNull())).thenReturn(Optional.of(node("内置导图"))); + MindMapOutlineGenerator generator = new MindMapOutlineGenerator(List.of(ai, builtin)); + + MindMapOutlineGenerator.GeneratedOutline outline = generator.generate(SCOPE, FRAGMENTS, List.of()); + + assertEquals("内置导图", outline.root().getTitle()); + } + + @Test + void skipsUnavailableAiAndUsesBuiltin() throws Exception { + MindMapAiClient builtin = client("BUILTIN", true); + MindMapAiClient ai = client("AI", false); + when(builtin.generate(any(), any(), any(), isNull())).thenReturn(Optional.of(node("内置导图"))); + MindMapOutlineGenerator generator = new MindMapOutlineGenerator(List.of(ai, builtin)); + + MindMapOutlineGenerator.GeneratedOutline outline = generator.generate(SCOPE, FRAGMENTS, List.of()); + + assertEquals("内置导图", outline.root().getTitle()); + assertEquals("BUILTIN", outline.generatorName()); + verify(ai, never()).generate(any(), any(), any(), any()); + } + + @Test + void failsWhenNoGeneratorAvailable() { + MindMapOutlineGenerator generator = + new MindMapOutlineGenerator(List.of(client("AI", false))); + + assertThrows(OperationFailedException.class, () -> generator.generate(SCOPE, FRAGMENTS, List.of())); + } + + @Test + void failsWhenAllGeneratorsReturnNothing() { + MindMapAiClient builtin = client("BUILTIN", true); + when(builtin.generate(any(), any(), any(), isNull())).thenReturn(Optional.empty()); + MindMapOutlineGenerator generator = new MindMapOutlineGenerator(List.of(builtin)); + + assertThrows(OperationFailedException.class, () -> generator.generate(SCOPE, FRAGMENTS, List.of())); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImplTest.java index 9dafbe8..76d10c9 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImplTest.java @@ -38,9 +38,7 @@ class StandardMindMapServiceImplTest { @Mock private StudyReportFragmentsMapper studyReportFragmentsMapper; @Mock - private List aiClients; - @Mock - private MindMapAiClient mockAiClient; + private MindMapOutlineGenerator outlineGenerator; @Mock private AiServiceClient aiServiceClient; @@ -186,7 +184,7 @@ class StandardMindMapServiceImplTest { StandardMindMapServiceImpl s = new StandardMindMapServiceImpl( standardMindMapMapper, recallRecordMapper, tasksMapper, taskApplicationMapper, studyReportFragmentsMapper, - List.of(mockAiClient), objectMapper, aiServiceClient); + outlineGenerator, objectMapper, aiServiceClient); return s; } } diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java new file mode 100644 index 0000000..6588603 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java @@ -0,0 +1,434 @@ +package com.guo.learningprogresstracker.service.impl; + +import cn.dev33.satoken.stp.StpUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.AiTaskResponse; +import com.guo.learningprogresstracker.dto.TagScope; +import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest; +import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.enums.AiTaskStatusEnum; +import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; +import com.guo.learningprogresstracker.exception.ErrorParameterException; +import com.guo.learningprogresstracker.exception.OperationFailedException; +import com.guo.learningprogresstracker.mapper.ReviewTagMindMapMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.service.AiTaskService; +import com.guo.learningprogresstracker.service.MarkerService; +import com.guo.learningprogresstracker.service.ReviewTagMindMapService; +import com.guo.learningprogresstracker.service.StudyReportFragmentsService; +import com.guo.learningprogresstracker.utils.GenerateNumTool; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 标签导图与标签范围回忆对比的落库集成测试(闭环-04)。 + * + *

覆盖口径:并集/交集取数正确、同一标签集合 + 模式命中同一张导图(范围键稳定)、 + * 不同模式/不同集合是不同导图、素材变化只置「待更新」不自动重建、软删除碎片不取材、 + * 标签范围回忆对比落记录并带范围列、任务范围的既有查询与统计不受影响、租户隔离, + * 以及 AI 任务链路(TAG_MIND_MAP / TAG_RECALL_COMPARE)的端到端可用。

+ * + *

本用例把 {@code AiServiceClient} 置为未配置:生成走内置规则生成器、对比走文本相似度匹配, + * 与任务导图的降级路径是同一套。

+ */ +@SpringBootTest +class TagMindMapIntegrationTest { + + private static final String USER = "标签导图集成测试用户"; + + private static final AtomicInteger SEQ = new AtomicInteger(); + + @Autowired + private ReviewTagMindMapService tagMindMapService; + + @Autowired + private ReviewTagMindMapMapper tagMindMapMapper; + + @Autowired + private MarkerService markerService; + + @Autowired + private StudyReportFragmentsService fragmentsService; + + @Autowired + private StudyReportFragmentsMapper fragmentsMapper; + + @Autowired + private StudySessionsMapper studySessionsMapper; + + @Autowired + private TasksMapper tasksMapper; + + @Autowired + private AiTaskService aiTaskService; + + /** AI 不可用:本用例覆盖的是内置规则降级路径 */ + @MockBean + private AiServiceClient aiServiceClient; + + @BeforeEach + void setUp() { + StpUtil.login(USER, "test_device"); + } + + /** 标签名按用例唯一:标签是按名取材的,共用固定名字会让用例之间互相污染 */ + private static String tag(String base) { + return base + "-" + SEQ.incrementAndGet(); + } + + private String saveTask(String taskName) { + String taskNum = "TAGMAP-IT-" + System.nanoTime() + "-" + SEQ.incrementAndGet(); + TaskEntity task = new TaskEntity(); + task.setTaskNum(taskNum); + task.setTaskName(taskName); + tasksMapper.insert(task); + return taskNum; + } + + /** 走创建链路建碎片:记录上下文取学习会话,并自动获得「任务名」标签 */ + private StudyReportFragmentsEntity createFragment(String taskNum, String content) throws Exception { + StudySessionsEntity session = new StudySessionsEntity(); + session.setSessionNum(GenerateNumTool.generateNum("SESSTAGMAP")); + session.setTaskNum(taskNum); + session.setStartTime(LocalDateTime.now()); + session.setLastStartTime(LocalDateTime.now()); + session.setSessionState("ENDED"); + studySessionsMapper.insert(session); + + CreateFragmentsRequest request = new CreateFragmentsRequest(); + request.setContextNum(session.getSessionNum()); + request.setContent(content); + fragmentsService.createFragments(request); + return fragmentsMapper.selectOne(Wrappers.lambdaQuery() + .eq(StudyReportFragmentsEntity::getContextNum, session.getSessionNum()) + .orderByDesc(StudyReportFragmentsEntity::getId) + .last("LIMIT 1")); + } + + private void addTag(StudyReportFragmentsEntity fragment, String tagName) throws Exception { + markerService.addUserTag(MarkerObjectTypeEnum.FRAGMENT, String.valueOf(fragment.getId()), tagName); + } + + private TagScope scope(String mode, String... tags) throws ErrorParameterException { + return tagMindMapService.resolveScope(List.of(tags), mode); + } + + /** 轮询到终态(等价于前端的轮询行为) */ + private AiTaskResponse awaitTerminal(String taskNum) throws Exception { + AiTaskResponse response = null; + for (int i = 0; i < 200; i++) { + response = aiTaskService.getByTaskNum(taskNum); + if (AiTaskStatusEnum.SUCCEEDED.name().equals(response.getStatus()) + || AiTaskStatusEnum.FAILED.name().equals(response.getStatus())) { + return response; + } + Thread.sleep(50); + } + throw new AssertionError("AI 任务未进入终态,最后状态: " + (response == null ? "null" : response.getStatus())); + } + + private static AiTaskSubmitRequest request(String type, String targetNum, Map params) { + AiTaskSubmitRequest request = new AiTaskSubmitRequest(); + request.setType(type); + request.setTargetNum(targetNum); + request.setParams(params); + return request; + } + + // ============ 取材:并集 / 交集 ============ + + @Test + void unionAndIntersect_pickDifferentFragments() throws Exception { + String taskNum = saveTask("标签取材任务-" + SEQ.incrementAndGet()); + String tagA = tag("并集A"); + String tagB = tag("并集B"); + + StudyReportFragmentsEntity onlyA = createFragment(taskNum, "只有标签A的碎片"); + addTag(onlyA, tagA); + StudyReportFragmentsEntity both = createFragment(taskNum, "同时带两标签的碎片"); + addTag(both, tagA); + addTag(both, tagB); + StudyReportFragmentsEntity onlyB = createFragment(taskNum, "只有标签B的碎片"); + addTag(onlyB, tagB); + + ReviewTagMindMapEntity union = tagMindMapService.regenerate(scope("UNION", tagA, tagB)); + assertEquals(3, union.getSourceFragmentCount().intValue(), "并集取带任一标签的碎片"); + assertTrue(union.getOutline().contains("只有标签A的碎片")); + assertTrue(union.getOutline().contains("同时带两标签的碎片")); + assertTrue(union.getOutline().contains("只有标签B的碎片")); + + ReviewTagMindMapEntity intersect = tagMindMapService.regenerate(scope("INTERSECT", tagA, tagB)); + assertEquals(1, intersect.getSourceFragmentCount().intValue(), "交集只取同时带全部标签的碎片"); + assertTrue(intersect.getOutline().contains("同时带两标签的碎片")); + assertFalse(intersect.getOutline().contains("只有标签A的碎片")); + assertEquals(TagCombineModeEnum.INTERSECT.name(), intersect.getCombineMode()); + } + + @Test + void singleTag_isItsOwnScope() throws Exception { + String taskNum = saveTask("单标签任务-" + SEQ.incrementAndGet()); + String tagA = tag("单标签"); + addTag(createFragment(taskNum, "单标签碎片"), tagA); + + ReviewTagMindMapEntity map = tagMindMapService.regenerate(scope("UNION", tagA)); + + assertEquals(1, map.getSourceFragmentCount().intValue()); + assertEquals(TagCombineModeEnum.UNION.name(), map.getCombineMode()); + } + + // ============ 范围键:同一集合 + 同一模式 = 同一张导图 ============ + + @Test + void sameTagSetAndMode_hitsSameMap() throws Exception { + String taskNum = saveTask("范围键任务-" + SEQ.incrementAndGet()); + String tagA = tag("范围键A"); + String tagB = tag("范围键B"); + addTag(createFragment(taskNum, "范围键碎片"), tagA); + + ReviewTagMindMapEntity first = tagMindMapService.regenerate(scope("UNION", tagA, tagB)); + // 顺序、大小写、空白不同,仍是同一个范围 + ReviewTagMindMapEntity second = tagMindMapService + .regenerate(scope("union", " " + tagB + " ", tagA.toUpperCase())); + + assertEquals(first.getId(), second.getId(), "集合相同且模式相同应命中同一张导图"); + + TagScope reordered = tagMindMapService.resolveScope(List.of(tagB, tagA.toUpperCase()), null); + assertEquals(first.getScopeKey(), reordered.scopeKey(), "范围键与顺序、大小写、空白无关"); + assertEquals(1, tagMindMapMapper.selectCount(Wrappers.lambdaQuery() + .eq(ReviewTagMindMapEntity::getScopeKey, first.getScopeKey())).intValue(), + "同一范围不会产生第二行"); + } + + @Test + void differentModeOrTagSet_isDifferentMap() throws Exception { + String taskNum = saveTask("范围区分任务-" + SEQ.incrementAndGet()); + String tagA = tag("范围区分A"); + String tagB = tag("范围区分B"); + StudyReportFragmentsEntity fragment = createFragment(taskNum, "范围区分碎片"); + addTag(fragment, tagA); + addTag(fragment, tagB); + + ReviewTagMindMapEntity union = tagMindMapService.regenerate(scope("UNION", tagA, tagB)); + ReviewTagMindMapEntity intersect = tagMindMapService.regenerate(scope("INTERSECT", tagA, tagB)); + ReviewTagMindMapEntity singleTag = tagMindMapService.regenerate(scope("UNION", tagA)); + + assertNotEquals(union.getId(), intersect.getId(), "不同取数模式是不同导图"); + assertNotEquals(union.getId(), singleTag.getId(), "不同标签集合是不同导图"); + } + + // ============ 素材变化:只置「待更新」,不自动重建 ============ + + @Test + void tagChanges_markMapNeedsUpdateWithoutRebuild() throws Exception { + String taskNum = saveTask("待更新任务-" + SEQ.incrementAndGet()); + String tagA = tag("待更新A"); + String tagB = tag("待更新B"); + String unrelatedTag = tag("待更新无关"); + StudyReportFragmentsEntity fragment = createFragment(taskNum, "待更新碎片"); + addTag(fragment, tagA); + + ReviewTagMindMapEntity map = tagMindMapService.regenerate(scope("UNION", tagA, tagB)); + assertFalse(map.getNeedsUpdate()); + String outlineBefore = map.getOutline(); + // 落库精度(微秒)后的值:待更新不应改动它 + LocalDateTime generatedBefore = tagMindMapMapper.selectById(map.getId()).getGeneratedTime(); + + // 范围外的标签变化不影响这张导图 + addTag(fragment, unrelatedTag); + assertFalse(tagMindMapMapper.selectById(map.getId()).getNeedsUpdate(), "范围外的标签不影响本导图"); + + // 范围内新增一个标签:置「待更新」,但内容原样保留(重建由用户手动触发) + addTag(fragment, tagB); + ReviewTagMindMapEntity reloaded = tagMindMapMapper.selectById(map.getId()); + assertTrue(reloaded.getNeedsUpdate(), "素材变化后导图应置为待更新"); + assertNotNull(reloaded.getNeedsUpdateTime()); + assertEquals(outlineBefore, reloaded.getOutline(), "待更新不等于重建:导图内容保持原样"); + assertEquals(generatedBefore, reloaded.getGeneratedTime()); + assertEquals(1, reloaded.getSourceFragmentCount().intValue()); + } + + @Test + void tagDeletedFromFragment_marksMapNeedsUpdate() throws Exception { + String taskNum = saveTask("摘标签任务-" + SEQ.incrementAndGet()); + String tagA = tag("摘标签A"); + StudyReportFragmentsEntity fragment = createFragment(taskNum, "摘标签碎片"); + addTag(fragment, tagA); + ReviewTagMindMapEntity map = tagMindMapService.regenerate(scope("UNION", tagA)); + assertFalse(map.getNeedsUpdate()); + + Integer markerId = markerService.listByObject(MarkerObjectTypeEnum.FRAGMENT, String.valueOf(fragment.getId())) + .stream().filter(m -> tagA.equals(m.getMarkerName())).findFirst().orElseThrow().getId(); + markerService.deleteMarker(markerId); + + ReviewTagMindMapEntity reloaded = tagMindMapMapper.selectById(map.getId()); + assertTrue(reloaded.getNeedsUpdate(), "标签被摘掉后导图应置为待更新"); + assertEquals(map.getOutline(), reloaded.getOutline(), "置「待更新」不会自动重建"); + } + + @Test + void fragmentDeleted_marksMapNeedsUpdate() throws Exception { + String taskNum = saveTask("删碎片任务-" + SEQ.incrementAndGet()); + String tagA = tag("删碎片A"); + StudyReportFragmentsEntity fragment = createFragment(taskNum, "删碎片"); + addTag(fragment, tagA); + ReviewTagMindMapEntity map = tagMindMapService.regenerate(scope("UNION", tagA)); + assertFalse(map.getNeedsUpdate()); + + fragmentsService.deleteFragment(fragment.getId()); + + assertTrue(tagMindMapMapper.selectById(map.getId()).getNeedsUpdate(), + "碎片被删除后导图应置为待更新"); + } + + @Test + void softDeletedFragment_isNotMaterial() throws Exception { + String taskNum = saveTask("软删除任务-" + SEQ.incrementAndGet()); + String tagA = tag("软删除A"); + StudyReportFragmentsEntity kept = createFragment(taskNum, "保留的碎片"); + StudyReportFragmentsEntity removed = createFragment(taskNum, "被软删除的碎片"); + addTag(kept, tagA); + addTag(removed, tagA); + + // 直接逻辑删除碎片(保留标记行),验证取材按 deleted=0 过滤 + fragmentsMapper.deleteById(removed.getId()); + + ReviewTagMindMapEntity map = tagMindMapService.regenerate(scope("UNION", tagA)); + + assertEquals(1, map.getSourceFragmentCount().intValue(), "软删除的碎片不取材"); + assertTrue(map.getOutline().contains("保留的碎片")); + assertFalse(map.getOutline().contains("被软删除的碎片")); + } + + // ============ 租户隔离 ============ + + @Test + void otherUsersFragments_areNotMaterial() throws Exception { + String sharedTag = tag("租户隔离"); + + StpUtil.login(USER + "-其他用户", "test_device"); + String otherTask = saveTask("其他用户任务-" + SEQ.incrementAndGet()); + addTag(createFragment(otherTask, "其他用户的碎片"), sharedTag); + + StpUtil.login(USER, "test_device"); + String myTask = saveTask("本用户任务-" + SEQ.incrementAndGet()); + addTag(createFragment(myTask, "本用户的碎片"), sharedTag); + + ReviewTagMindMapEntity map = tagMindMapService.regenerate(scope("UNION", sharedTag)); + + assertEquals(1, map.getSourceFragmentCount().intValue(), "取材只覆盖当前用户的数据"); + assertTrue(map.getOutline().contains("本用户的碎片")); + assertFalse(map.getOutline().contains("其他用户的碎片")); + } + + // ============ AI 任务链路(前端实际接线路径) ============ + + @Test + void tagMindMapTask_generatesMapAndIsQueryableAgain() throws Exception { + String taskNum = saveTask("标签任务任务-" + SEQ.incrementAndGet()); + String tagA = tag("标签任务A"); + addTag(createFragment(taskNum, "标签任务碎片"), tagA); + TagScope scope = scope("UNION", tagA); + + // 读取不生成 + assertNull(tagMindMapService.query(scope).getMap()); + + AiTaskResponse submitted = aiTaskService.submit(request("TAG_MIND_MAP", scope.scopeKey(), + Map.of("tags", scope.tags(), "combineMode", "UNION", "mode", "full"))); + AiTaskResponse done = awaitTerminal(submitted.getTaskNum()); + + assertEquals(AiTaskStatusEnum.SUCCEEDED.name(), done.getStatus(), done.getErrorMessage()); + assertNotNull(done.getResult().get("tagMapId")); + assertEquals(scope.scopeKey(), done.getResult().get("scopeKey")); + assertNotNull(tagMindMapService.query(scope).getMap()); + + // 已有导图时 ensure 模式不重复生成 + AiTaskResponse ensure = awaitTerminal(aiTaskService.submit(request("TAG_MIND_MAP", scope.scopeKey(), + Map.of("tags", scope.tags(), "combineMode", "UNION", "mode", "ensure"))).getTaskNum()); + assertEquals(AiTaskStatusEnum.SUCCEEDED.name(), ensure.getStatus(), ensure.getErrorMessage()); + assertEquals("已存在,跳过生成", ensure.getResult().get("summary")); + } + + @Test + void tagMindMapTask_withMismatchedTarget_fails() throws Exception { + String taskNum = saveTask("标签任务不匹配-" + SEQ.incrementAndGet()); + String tagA = tag("标签任务不匹配A"); + addTag(createFragment(taskNum, "标签任务不匹配碎片"), tagA); + + AiTaskResponse done = awaitTerminal(aiTaskService.submit(request("TAG_MIND_MAP", "不是范围键", + Map.of("tags", List.of(tagA), "combineMode", "UNION"))).getTaskNum()); + + assertEquals(AiTaskStatusEnum.FAILED.name(), done.getStatus()); + assertTrue(done.getErrorMessage().contains("对不上"), "失败原因应说明范围与目标不一致:" + done.getErrorMessage()); + } + + // ============ 用户编辑与参数校验 ============ + + @Test + void userEditsOutline_createsThenReplacesSameRangeMap() throws Exception { + String tagA = tag("用户编辑"); + TagScope scope = scope("UNION", tagA); + + assertNull(tagMindMapService.query(scope).getMap(), "读取不触发生成"); + + ReviewTagMindMapEntity created = tagMindMapService.updateByOutline(scope, + "我的标签导图\n - 分支一\n - 分支二"); + assertEquals("我的标签导图", created.getTitle()); + assertEquals("USER", created.getGenerator()); + + ReviewTagMindMapEntity updated = tagMindMapService.updateByOutline(scope, "改过的导图\n - 只剩一个分支"); + assertEquals(created.getId(), updated.getId(), "同一范围只有一张导图"); + assertEquals("改过的导图", tagMindMapService.query(scope).getMap().getTitle()); + } + + @Test + void resolveScope_rejectsEmptyInvalidOversizedAndTooLongRanges() { + assertThrows(ErrorParameterException.class, + () -> tagMindMapService.resolveScope(List.of(" "), "UNION")); + assertThrows(ErrorParameterException.class, + () -> tagMindMapService.resolveScope(List.of("A"), "XOR")); + assertThrows(ErrorParameterException.class, () -> tagMindMapService.resolveScope( + List.of("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), "UNION")); + assertThrows(ErrorParameterException.class, + () -> tagMindMapService.resolveScope(List.of("x".repeat(101)), "UNION")); + } + + @Test + void incrementalGenerateWithoutExistingMap_fails() throws Exception { + TagScope scope = scope("UNION", tag("增量无导图")); + + assertThrows(com.guo.learningprogresstracker.exception.NotFindEntitiesException.class, + () -> tagMindMapService.incrementalGenerate(scope)); + } + + @Test + void generateWithoutMaterial_failsWithReadableMessage() throws Exception { + TagScope scope = scope("UNION", tag("没有取材")); + + OperationFailedException failure = assertThrows(OperationFailedException.class, + () -> tagMindMapService.regenerate(scope)); + assertTrue(failure.getMessage().contains("标签"), "失败文案应说明这些标签下没有内容,实际:" + failure.getMessage()); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/utils/TagScopeToolTest.java b/src/test/java/com/guo/learningprogresstracker/utils/TagScopeToolTest.java new file mode 100644 index 0000000..9d3575d --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/utils/TagScopeToolTest.java @@ -0,0 +1,62 @@ +package com.guo.learningprogresstracker.utils; + +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 复习范围规范化(闭环-04)的单元测试。 + * + *

核心口径:集合相同(顺序、大小写、空白无关)且取数模式相同 → 同一个范围键;任一不同 → 不同范围键。

+ */ +class TagScopeToolTest { + + @Test + void normalize_stripsBlankAndLowercases() { + assertEquals("java", TagScopeTool.normalize(" Java ")); + assertEquals("并发", TagScopeTool.normalize("并发")); + assertEquals("", TagScopeTool.normalize(null)); + } + + @Test + void canonicalTags_dedupesByNormalizedNameAndKeepsInputSpelling() { + List canonical = TagScopeTool.canonicalTags(List.of("Java", " java ", "并发")); + + assertEquals(List.of("Java", "并发"), canonical, "按归一化名排序,展示保留输入原样"); + } + + @Test + void scopeKey_isStableAcrossOrderCaseAndBlank() { + String first = TagScopeTool.scopeKey(List.of("Java", "并发"), TagCombineModeEnum.UNION); + String reordered = TagScopeTool.scopeKey(List.of(" 并发 ", "JAVA"), TagCombineModeEnum.UNION); + + assertEquals(first, reordered, "集合相同且模式相同时范围键必须一致"); + assertEquals(64, first.length(), "范围键是 SHA-256 十六进制串"); + } + + @Test + void scopeKey_differsByModeOrTagSet() { + String union = TagScopeTool.scopeKey(List.of("Java", "并发"), TagCombineModeEnum.UNION); + String intersect = TagScopeTool.scopeKey(List.of("Java", "并发"), TagCombineModeEnum.INTERSECT); + String otherSet = TagScopeTool.scopeKey(List.of("Java"), TagCombineModeEnum.UNION); + + assertNotEquals(union, intersect, "不同取数模式是不同范围"); + assertNotEquals(union, otherSet, "不同标签集合是不同范围"); + } + + @Test + void storedTags_roundTrip() { + List tags = List.of("Java", "并发"); + + String stored = TagScopeTool.toStoredTags(tags); + + assertEquals(tags, TagScopeTool.parseStoredTags(stored)); + assertTrue(TagScopeTool.parseStoredTags(null).isEmpty(), "缺失时按空集合处理"); + assertTrue(TagScopeTool.parseStoredTags("不是 JSON").isEmpty(), "损坏时按空集合处理"); + } +}