feat: 新增标签导图存储与生成
This commit is contained in:
@@ -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)。
|
||||
*
|
||||
* <p>按标签复习与按任务复习并存:任务导图仍走 {@code /review/standard-mind-map/{taskNum}},
|
||||
* 这里只负责以「标签集合 + 取数模式」为范围的那一半。</p>
|
||||
*
|
||||
* <p>生成与回忆对比都不在请求线程里等 AI:由前端提交 {@code POST /ai/tasks}
|
||||
* (type=TAG_MIND_MAP / TAG_RECALL_COMPARE)后轮询结果,与既有 AI 任务链路同一约定。</p>
|
||||
*/
|
||||
@RequestMapping("/review/tag-mind-map")
|
||||
@RestController
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
public class TagMindMapController {
|
||||
|
||||
private final ReviewTagMindMapService reviewTagMindMapService;
|
||||
|
||||
/**
|
||||
* 读取该范围的状态:范围键、标签集合与已有导图。
|
||||
*
|
||||
* <p>读取不触发生成:没有导图时 {@code map} 为 null,由前端提交生成任务。
|
||||
* 用请求体而不是查询参数,是因为标签名由用户自由输入、可能含逗号。</p>
|
||||
*/
|
||||
@PostMapping("/query")
|
||||
public CommonResult<TagMindMapView> query(@Valid @RequestBody TagScopeRequest request)
|
||||
throws ErrorParameterException {
|
||||
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
|
||||
return CommonResult.success(reviewTagMindMapService.query(scope));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户编辑标签导图(大纲文本形式);该范围还没有导图时保存即为新建。
|
||||
*/
|
||||
@PutMapping
|
||||
public CommonResult<ReviewTagMindMapEntity> updateTagMindMap(
|
||||
@Valid @RequestBody UpdateTagMindMapRequest request) throws ErrorParameterException {
|
||||
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
|
||||
return CommonResult.success(reviewTagMindMapService.updateByOutline(scope, request.getOutline()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.guo.learningprogresstracker.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 一个碎片命中的标签数(闭环-04 标签导图取材)。
|
||||
*
|
||||
* <p>由 Mapper 层的分组查询直接映射:并集取「命中任意一个」的行,交集取「命中数 == 范围标签数」的行。
|
||||
* 命中数按归一化标签名去重,所以重复打标不会让交集判定失真。</p>
|
||||
*/
|
||||
@Data
|
||||
public class FragmentTagMatch {
|
||||
|
||||
/** 碎片 id(标记的 object_num) */
|
||||
private String objectNum;
|
||||
|
||||
/** 命中的标签数(按归一化标签名去重) */
|
||||
private Integer matchedTagCount;
|
||||
}
|
||||
@@ -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)。
|
||||
*
|
||||
* <p>范围键与标签集合总是返回(即使还没有导图),让前端能用同一组参数发起生成任务与回忆对比;
|
||||
* {@code map} 为空表示该范围还没生成过导图——读取路径不触发生成,生成走
|
||||
* {@code POST /ai/tasks}(type=TAG_MIND_MAP)异步完成。</p>
|
||||
*/
|
||||
@Data
|
||||
public class TagMindMapView {
|
||||
|
||||
@Schema(description = "范围键:标签集合与取数模式的稳定哈希,同时作为 AI 任务的 targetNum")
|
||||
private String scopeKey;
|
||||
|
||||
@Schema(description = "范围的标签集合(展示用,按归一化名排序)")
|
||||
private List<String> tags;
|
||||
|
||||
@Schema(description = "取数模式:UNION=并集 / INTERSECT=交集")
|
||||
private String mode;
|
||||
|
||||
@Schema(description = "该范围已有的标签导图;没有时为 null")
|
||||
private ReviewTagMindMapEntity map;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.guo.learningprogresstracker.dto;
|
||||
|
||||
import com.guo.learningprogresstracker.enums.TagCombineModeEnum;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 解析后的复习范围:标签集合 + 取数模式 + 规范键(闭环-04)。
|
||||
*
|
||||
* <p>{@code tags} 是展示用标签集合(按归一化名排序、保留输入原样),{@code normalizedTags} 是规范化标签集合,
|
||||
* {@code scopeKey} 是两者的稳定哈希——集合相同且模式相同即同一张标签导图。</p>
|
||||
*/
|
||||
public record TagScope(String scopeKey, List<String> tags, List<String> normalizedTags, TagCombineModeEnum mode) {
|
||||
|
||||
/** 范围的展示名:标签以「、」连接,也是标签导图的根节点标题来源 */
|
||||
public String displayName() {
|
||||
return String.join("、", tags);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.guo.learningprogresstracker.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 标签复习范围(闭环-04):标签集合 + 取数模式。
|
||||
*
|
||||
* <p>用于纯范围寻址的读接口(读取该范围的导图、读取该范围的回忆记录)。
|
||||
* 字段名与 {@code /ai/tasks} 的 params 保持一致,前端两处可以直接复用。</p>
|
||||
*/
|
||||
@Data
|
||||
public class TagScopeRequest {
|
||||
|
||||
@NotEmpty(message = "请先选择标签")
|
||||
private List<String> tags;
|
||||
|
||||
/** 取数模式:UNION=并集(默认)/ INTERSECT=交集 */
|
||||
private String mode;
|
||||
}
|
||||
+26
@@ -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)。
|
||||
*
|
||||
* <p>范围绕「标签集合 + 取数模式」寻址,因此请求里带的是范围本身而不是导图 id;
|
||||
* 该范围还没有导图时,保存即为新建。</p>
|
||||
*/
|
||||
@Data
|
||||
public class UpdateTagMindMapRequest {
|
||||
|
||||
@NotEmpty(message = "请先选择标签")
|
||||
private List<String> tags;
|
||||
|
||||
/** 取数模式:UNION=并集(默认)/ INTERSECT=交集 */
|
||||
private String mode;
|
||||
|
||||
@NotBlank(message = "请填写思维导图大纲")
|
||||
private String outline;
|
||||
}
|
||||
@@ -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):以一个「标签集合 + 取数模式」为范围的导图,与任务导图并存。
|
||||
*
|
||||
* <p>范围键 {@code scopeKey} 是标签集合(归一化、排序后拼接)与取数模式的稳定哈希:
|
||||
* 集合相同且模式相同即同一张导图,因此同一用户下范围键唯一。素材是带这些标签的知识碎片,
|
||||
* 与任务导图共用「碎片 → 缩进大纲」的生成链路与内置规则降级路径。</p>
|
||||
*/
|
||||
@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;
|
||||
}
|
||||
@@ -16,6 +16,9 @@ public enum AiTaskTypeEnum {
|
||||
/** 标准思维导图生成:全量、增量或按需生成 */
|
||||
MIND_MAP("思维导图生成"),
|
||||
|
||||
/** 标签思维导图生成:按「标签集合 + 取数模式」生成或重建(闭环-04) */
|
||||
TAG_MIND_MAP("标签思维导图生成"),
|
||||
|
||||
/** 学习报告草稿聚合 */
|
||||
REPORT_DRAFT("学习报告草稿"),
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.guo.learningprogresstracker.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 标签导图的取数模式(闭环-04)。
|
||||
*
|
||||
* <p>多标签由用户在界面上选并集还是交集,默认并集;模式与标签集合一起构成导图的规范键。</p>
|
||||
*/
|
||||
@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<MarkerEntity> {
|
||||
ORDER BY marker_count DESC, marker_name ASC
|
||||
""")
|
||||
List<MarkerUsage> selectUserTagUsage(@Param("createdBy") String createdBy);
|
||||
|
||||
/**
|
||||
* 按标签集合统计每个碎片命中的标签数(闭环-04 标签导图取材)。
|
||||
*
|
||||
* <p>归一化口径与标签字典一致(去首尾空白 + 小写),所以标签大小写/空白不同也能命中同一组标签;
|
||||
* 命中数按归一化名去重,并集取「≥1」,交集取「= 范围标签数」。
|
||||
* 租户条件 {@code created_by} 由 {@code TenantLineInnerInterceptor} 自动追加(有集成测试覆盖)。</p>
|
||||
*
|
||||
* @param tagKeys 规范化标签名;为空时返回空列表
|
||||
*/
|
||||
@Select("""
|
||||
<script>
|
||||
SELECT object_num AS object_num,
|
||||
COUNT(DISTINCT LOWER(TRIM(marker_name))) AS matched_tag_count
|
||||
FROM markers
|
||||
WHERE deleted = 0
|
||||
AND object_type = 'FRAGMENT'
|
||||
AND kind = 'USER'
|
||||
AND LOWER(TRIM(marker_name)) IN
|
||||
<foreach collection="tagKeys" item="tagKey" open="(" separator="," close=")">#{tagKey}</foreach>
|
||||
GROUP BY object_num
|
||||
</script>
|
||||
""")
|
||||
List<FragmentTagMatch> countUserTagsPerFragment(@Param("tagKeys") Collection<String> tagKeys);
|
||||
}
|
||||
|
||||
@@ -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)。
|
||||
* <p>查询条件都能用 Wrapper 表达(按范围键取一条、按是否待更新扫一遍),因此不额外下沉自定义 SQL。</p>
|
||||
*/
|
||||
@Mapper
|
||||
public interface ReviewTagMindMapMapper extends BaseMapper<ReviewTagMindMapEntity> {
|
||||
}
|
||||
@@ -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)。
|
||||
*
|
||||
* <p>标签导图以一个「标签集合 + 取数模式」为范围,与任务导图并存、互不替代:
|
||||
* 任务导图回答「这个任务学到了什么结构」,标签导图回答「这个概念在不同任务里呈现出什么结构」。
|
||||
* 范围用规范键({@code TagScope#scopeKey})寻址,集合相同且模式相同即同一张导图。</p>
|
||||
*
|
||||
* <p>两条硬口径:</p>
|
||||
* <ul>
|
||||
* <li><b>读取不生成</b>:读取路径只返回已有导图,生成走 {@code POST /ai/tasks}(type=TAG_MIND_MAP)异步完成;</li>
|
||||
* <li><b>重建手动触发</b>:素材(碎片标签)变化只把导图置「待更新」,不自动重建。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public interface ReviewTagMindMapService {
|
||||
|
||||
/**
|
||||
* 解析复习范围:去空白、按归一化名去重排序、算范围键,并校验标签数量与取数模式。
|
||||
*
|
||||
* @param mode UNION(默认,并集)/ INTERSECT(交集)
|
||||
*/
|
||||
TagScope resolveScope(List<String> 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;
|
||||
|
||||
/**
|
||||
* 素材发生变化时的置「待更新」(不重建)。
|
||||
*
|
||||
* <p>由标签的增删改与碎片删除调用:只有标签集合与变化标签有交集的那几张导图会被置位。</p>
|
||||
*/
|
||||
void markStaleForTags(Collection<String> changedTagNames);
|
||||
}
|
||||
@@ -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 不可用或失败时降级为文本相似度匹配。
|
||||
*
|
||||
* <p>任务导图与标签导图共用它,避免两种复习范围出现两套覆盖率口径。</p>
|
||||
*
|
||||
* @param scopeName 范围名(任务名或标签集合),仅用于 AI 提示词与日志
|
||||
* @param standardRoot 作为对比基准的导图树(可能只是标准导图的一棵子树)
|
||||
* @param recallOutline 用户回忆的缩进大纲文本
|
||||
*/
|
||||
CompareResult compareWithRecall(String scopeName, MindMapNode standardRoot, String recallOutline);
|
||||
|
||||
/**
|
||||
* 根据内容文本在标准导图中查找最匹配的节点,返回节点路径。
|
||||
*
|
||||
|
||||
@@ -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)。
|
||||
*
|
||||
* <p>参数的来源是前端提交的 JSON:数字与时间可能是字符串,缺字段与空值都按「未提供」处理,
|
||||
* 各任务处理器共用同一套解析口径。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
final class AiTaskParams {
|
||||
|
||||
private AiTaskParams() {
|
||||
}
|
||||
|
||||
static String asString(Map<String, Object> params, String key) {
|
||||
Object value = params == null ? null : params.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
static Integer asInteger(Map<String, Object> 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<String, Object> 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<String> asStringList(Map<String, Object> 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<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<MarkerEntity> 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<String> removedTags = List.of();
|
||||
if (objectType == MarkerObjectTypeEnum.FRAGMENT) {
|
||||
removedTags = markerMapper.selectList(Wrappers.<MarkerEntity>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.<MarkerEntity>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<String> changedTags) {
|
||||
if (objectType != MarkerObjectTypeEnum.FRAGMENT || changedTags == null || changedTags.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
reviewTagMindMapService.markStaleForTags(changedTags);
|
||||
}
|
||||
|
||||
private MarkerEntity requireMarker(Integer id) throws NotFindEntitiesException {
|
||||
|
||||
+5
-7
@@ -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<String, Object> execute(AiTaskEntity task, Map<String, Object> 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), "全量生成");
|
||||
|
||||
+72
@@ -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 客户端,失败时降级到内置规则生成器。
|
||||
*
|
||||
* <p>任务导图与标签导图共用它,避免两种取材范围出现两套客户端选择与降级口径。
|
||||
* <b>取材</b>(按内容归属 / 按标签集合)由调用方决定,本类只回答「给定素材怎么产出树」。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MindMapOutlineGenerator {
|
||||
|
||||
private static final String GENERATOR_BUILTIN = "BUILTIN";
|
||||
|
||||
private final List<MindMapAiClient> aiClients;
|
||||
|
||||
/**
|
||||
* @param root 导图根节点
|
||||
* @param generatorName 生成来源标识({@code BUILTIN} / AI 客户端名);沿用首选客户端的标识,
|
||||
* 与既有任务导图口径一致
|
||||
*/
|
||||
public record GeneratedOutline(MindMapNode root, String generatorName) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成导图树;没有任何可用生成器或全部生成失败时抛出用户可见的业务异常。
|
||||
*/
|
||||
public GeneratedOutline generate(TaskEntity scope,
|
||||
List<StudyReportFragmentsEntity> fragments,
|
||||
List<TaskApplicationEntity> 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<MindMapNode> 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());
|
||||
}
|
||||
}
|
||||
+5
-41
@@ -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<String, Object> execute(AiTaskEntity task, Map<String, Object> 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<String, Object> params, String key) {
|
||||
Object value = params.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
private static Integer asInteger(Map<String, Object> 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<String, Object> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+307
@@ -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)。
|
||||
*
|
||||
* <p>取材与生成两条链路都刻意与任务导图共用口径:素材来自带这些标签的碎片(软删除的不取材),
|
||||
* 生成走 {@link MindMapOutlineGenerator}(AI 优先、内置规则降级)。</p>
|
||||
*/
|
||||
@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<String> tags, String mode) throws ErrorParameterException {
|
||||
List<String> 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<String> 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<String> changedTagNames) {
|
||||
Set<String> changed = Set.copyOf(TagScopeTool.normalizedTags(changedTagNames));
|
||||
if (changed.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<ReviewTagMindMapEntity> maps = tagMindMapMapper.selectList(
|
||||
Wrappers.<ReviewTagMindMapEntity>lambdaQuery()
|
||||
.eq(ReviewTagMindMapEntity::getNeedsUpdate, false));
|
||||
int marked = 0;
|
||||
for (ReviewTagMindMapEntity map : maps) {
|
||||
Set<String> 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<StudyReportFragmentsEntity> 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.<ReviewTagMindMapEntity>lambdaQuery()
|
||||
.eq(ReviewTagMindMapEntity::getScopeKey, scopeKey)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 取数:带这些标签的知识碎片。并集取「带任一标签」,交集取「同时带全部标签」;
|
||||
* 软删除的碎片由 {@code @TableLogic} 自动排除。
|
||||
*/
|
||||
private List<StudyReportFragmentsEntity> loadFragments(TagScope scope) {
|
||||
List<FragmentTagMatch> matches = markerMapper.countUserTagsPerFragment(scope.normalizedTags());
|
||||
int requiredTagCount = scope.mode() == TagCombineModeEnum.INTERSECT
|
||||
? scope.normalizedTags().size() : 1;
|
||||
|
||||
List<Integer> 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.<StudyReportFragmentsEntity>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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-54
@@ -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<MindMapAiClient> 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.<TaskEntity>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.<TaskEntity>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<MindMapNode> 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());
|
||||
|
||||
+91
@@ -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)。
|
||||
*
|
||||
* <p>任务目标 {@code targetNum} 是标签范围的规范键({@code TagScope#scopeKey}),
|
||||
* 范围本身由参数给出:{@code tags}(标签集合)、{@code combineMode}(UNION/INTERSECT)、
|
||||
* {@code mode}(full/incremental/ensure,与任务导图的同名参数同义)。
|
||||
* 目标与参数不一致说明前端拿了过期的范围,直接失败,避免把这张导图写到别的范围上。</p>
|
||||
*
|
||||
* <p>生成模式与任务导图一致,但**不会**被素材变化自动触发:素材变化只把导图置「待更新」,
|
||||
* 本任务由用户手动发起(与归属-01 的任务导图同口径)。</p>
|
||||
*/
|
||||
@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<String, Object> execute(AiTaskEntity task, Map<String, Object> 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<String, Object> toPayload(ReviewTagMindMapEntity entity, TagScope scope, String summary) {
|
||||
Map<String, Object> 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;
|
||||
}
|
||||
}
|
||||
@@ -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)。
|
||||
*
|
||||
* <p>口径(2026-10-10 维护者确认,见 lpt-docs/docs/concepts/standard-mind-map.md「导图的范围」):
|
||||
* 范围的规范键 = 「标签集合(排序、归一化后的稳定拼接)+ 取数模式」的稳定哈希,集合相同且模式相同即同一张导图。
|
||||
* 标签归一化口径与标签字典一致:去首尾空白 + 小写({@code user_tags.normalized_name} 同口径)。</p>
|
||||
*/
|
||||
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<String> normalizedTags(Collection<String> tagNames) {
|
||||
TreeSet<String> 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<String> canonicalTags(Collection<String> tagNames) {
|
||||
Map<String, String> 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<String> 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<String> tagNames) {
|
||||
try {
|
||||
return MAPPER.writeValueAsString(canonicalTags(tagNames));
|
||||
} catch (Exception e) {
|
||||
// List<String> 序列化不会失败;真出问题也不能让导图链路整体挂掉
|
||||
throw new IllegalStateException("标签集合序列化失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 回读落库的标签集合;内容缺失或损坏时按空集合处理 */
|
||||
public static List<String> parseStoredTags(String storedTags) {
|
||||
if (storedTags == null || storedTags.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
List<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user