diff --git a/src/main/java/com/guo/learningprogresstracker/LearningProgressTrackerApplication.java b/src/main/java/com/guo/learningprogresstracker/LearningProgressTrackerApplication.java index b98d49b..cfba5d2 100644 --- a/src/main/java/com/guo/learningprogresstracker/LearningProgressTrackerApplication.java +++ b/src/main/java/com/guo/learningprogresstracker/LearningProgressTrackerApplication.java @@ -1,6 +1,7 @@ package com.guo.learningprogresstracker; import cn.dev33.satoken.SaManager; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -8,12 +9,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * @author guo * 应用程序启动类 */ +@Slf4j @SpringBootApplication public class LearningProgressTrackerApplication { public static void main(String[] args) { SpringApplication.run(LearningProgressTrackerApplication.class, args); - System.out.println("启动成功,Sa-Token 配置如下:" + SaManager.getConfig()); + log.info("启动成功,Sa-Token 配置如下:{}", SaManager.getConfig()); } - } diff --git a/src/main/java/com/guo/learningprogresstracker/common/GlobalExceptionHandler.java b/src/main/java/com/guo/learningprogresstracker/common/GlobalExceptionHandler.java index 2914a63..4d78d73 100644 --- a/src/main/java/com/guo/learningprogresstracker/common/GlobalExceptionHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/common/GlobalExceptionHandler.java @@ -15,51 +15,55 @@ import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; - @RestControllerAdvice @Slf4j public class GlobalExceptionHandler { + @ExceptionHandler(com.guo.learningprogresstracker.exception.RecallBusinessException.class) + public CommonResult recallBusinessException( + com.guo.learningprogresstracker.exception.RecallBusinessException ex) { + return new CommonResult<>(400, ex.getMessage(), ex.getData()); + } + @ExceptionHandler({ErrorParameterException.class}) - public CommonResult errorParameterException(ErrorParameterException ex) { + public CommonResult errorParameterException(ErrorParameterException ex) { log.warn("参数异常: {}", ex.getMessage(), ex); return CommonResult.error(ex.getMessage()); } @ExceptionHandler({NotFindEntitiesException.class}) - public CommonResult notFindEntitiesException(NotFindEntitiesException ex) { + public CommonResult notFindEntitiesException(NotFindEntitiesException ex) { log.warn("数据不存在: {}", ex.getMessage(), ex); return CommonResult.error(ex.getMessage()); } @ExceptionHandler({OperationFailedException.class}) - public CommonResult operationFailedException(OperationFailedException ex) { + public CommonResult operationFailedException(OperationFailedException ex) { log.warn("操作失败: {}", ex.getMessage(), ex); return CommonResult.error(ex.getMessage()); } @ExceptionHandler({AppException.class}) - public CommonResult AppException(AppException ex) { + public CommonResult handleAppException(AppException ex) { log.error("业务异常: {}", ex.getMessage(), ex); return CommonResult.serverError(ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) - public CommonResult MyMethodArgumentNotValidException(MethodArgumentNotValidException ex) { + public CommonResult handleArgumentNotValid(MethodArgumentNotValidException ex) { BindingResult bindingResult = ex.getBindingResult(); return CommonResult.error(bindingResult.getFieldError().getDefaultMessage()); } @ExceptionHandler(NotLoginException.class) - public CommonResult handleNotLogin(NotLoginException e, HttpServletRequest req, HttpServletResponse res) { + public CommonResult handleNotLogin(NotLoginException e, HttpServletRequest req, HttpServletResponse res) { res.setStatus(HttpStatus.UNAUTHORIZED.value()); return new CommonResult<>(HttpStatus.UNAUTHORIZED.value(), "未登录,请重新登录", null); } @ExceptionHandler(Exception.class) - public CommonResult Exception(Exception ex) { + public CommonResult handleUnexpected(Exception ex) { log.error("系统异常", ex); - return CommonResult.error("操作没有成功,请稍后再试"); + return CommonResult.serverError("操作没有成功,请稍后再试"); } - } diff --git a/src/main/java/com/guo/learningprogresstracker/common/Ops.java b/src/main/java/com/guo/learningprogresstracker/common/Ops.java index 4a288d1..f91bf31 100644 --- a/src/main/java/com/guo/learningprogresstracker/common/Ops.java +++ b/src/main/java/com/guo/learningprogresstracker/common/Ops.java @@ -7,10 +7,8 @@ import jakarta.validation.groups.Default; */ public interface Ops { // 创建组 - interface CreateG extends Default { - } + interface CreateG extends Default {} // 更新组 - interface UpdateG { - } + interface UpdateG {} } diff --git a/src/main/java/com/guo/learningprogresstracker/common/StudyTimePolicy.java b/src/main/java/com/guo/learningprogresstracker/common/StudyTimePolicy.java index fd5db91..daacecb 100644 --- a/src/main/java/com/guo/learningprogresstracker/common/StudyTimePolicy.java +++ b/src/main/java/com/guo/learningprogresstracker/common/StudyTimePolicy.java @@ -35,8 +35,8 @@ public class StudyTimePolicy { */ private final long minEffectiveTimeSeconds; - public StudyTimePolicy(int workDurationMinutes, int forgetThresholdMinutes, - int forcePauseMinutes, long minEffectiveTimeSeconds) { + public StudyTimePolicy( + int workDurationMinutes, int forgetThresholdMinutes, int forcePauseMinutes, long minEffectiveTimeSeconds) { if (workDurationMinutes <= 0) { throw new IllegalArgumentException("番茄钟长度必须大于 0 分钟"); } diff --git a/src/main/java/com/guo/learningprogresstracker/common/TenantContext.java b/src/main/java/com/guo/learningprogresstracker/common/TenantContext.java index 32ba690..3ecf7e7 100644 --- a/src/main/java/com/guo/learningprogresstracker/common/TenantContext.java +++ b/src/main/java/com/guo/learningprogresstracker/common/TenantContext.java @@ -18,13 +18,11 @@ public final class TenantContext { * @param loginId 登录用户 * @param device 设备类型,可为 null(后台任务通常没有设备信息) */ - public record Identity(String loginId, String device) { - } + public record Identity(String loginId, String device) {} private static final ThreadLocal CURRENT = new ThreadLocal<>(); - private TenantContext() { - } + private TenantContext() {} /** 取当前执行身份;未设置时返回 null(表示应回落到 StpUtil) */ public static Identity get() { diff --git a/src/main/java/com/guo/learningprogresstracker/config/AiUsageProperties.java b/src/main/java/com/guo/learningprogresstracker/config/AiUsageProperties.java index dca0533..76db1bf 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/AiUsageProperties.java +++ b/src/main/java/com/guo/learningprogresstracker/config/AiUsageProperties.java @@ -1,11 +1,10 @@ package com.guo.learningprogresstracker.config; -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - import java.math.BigDecimal; import java.util.List; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; /** * AI 用量统计配置。 diff --git a/src/main/java/com/guo/learningprogresstracker/config/AutoTableField.java b/src/main/java/com/guo/learningprogresstracker/config/AutoTableField.java index 9d78cef..355a12b 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/AutoTableField.java +++ b/src/main/java/com/guo/learningprogresstracker/config/AutoTableField.java @@ -3,12 +3,11 @@ package com.guo.learningprogresstracker.config; import cn.dev33.satoken.stp.StpUtil; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import com.guo.learningprogresstracker.common.TenantContext; +import java.time.LocalDateTime; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.context.annotation.Configuration; -import java.time.LocalDateTime; - /** * 用于公共字段的自动填充 * @@ -18,7 +17,6 @@ import java.time.LocalDateTime; @Slf4j public class AutoTableField implements MetaObjectHandler { - @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createdBy", AutoTableField::currentLoginId, String.class); @@ -28,7 +26,6 @@ public class AutoTableField implements MetaObjectHandler { this.strictInsertFill(metaObject, "deviceInfo", AutoTableField::currentDevice, String.class); } - @Override public void updateFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "lastModifiedBy", AutoTableField::currentLoginId, String.class); @@ -51,5 +48,4 @@ public class AutoTableField implements MetaObjectHandler { TenantContext.Identity identity = TenantContext.get(); return identity != null ? identity.device() : StpUtil.getLoginDevice(); } - } diff --git a/src/main/java/com/guo/learningprogresstracker/config/CorsProperties.java b/src/main/java/com/guo/learningprogresstracker/config/CorsProperties.java index 91dacad..cde37c0 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/CorsProperties.java +++ b/src/main/java/com/guo/learningprogresstracker/config/CorsProperties.java @@ -10,5 +10,4 @@ import org.springframework.context.annotation.Configuration; public class CorsProperties { private String[] allowedOrigins; private Boolean allowCredentials; - } diff --git a/src/main/java/com/guo/learningprogresstracker/config/JacksonConfig.java b/src/main/java/com/guo/learningprogresstracker/config/JacksonConfig.java index db416ac..001dfe1 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/JacksonConfig.java +++ b/src/main/java/com/guo/learningprogresstracker/config/JacksonConfig.java @@ -4,12 +4,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.guo.learningprogresstracker.config.serializer.LocalDateTimeSerializer; +import java.time.LocalDateTime; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import java.time.LocalDateTime; - @Configuration public class JacksonConfig { @Bean diff --git a/src/main/java/com/guo/learningprogresstracker/config/MybatisPlusConfig.java b/src/main/java/com/guo/learningprogresstracker/config/MybatisPlusConfig.java index 342c8bb..958d60a 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/MybatisPlusConfig.java +++ b/src/main/java/com/guo/learningprogresstracker/config/MybatisPlusConfig.java @@ -1,18 +1,17 @@ package com.guo.learningprogresstracker.config; import cn.dev33.satoken.stp.StpUtil; -import com.guo.learningprogresstracker.common.TenantContext; -import net.sf.jsqlparser.expression.StringValue; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor; -import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler; -import net.sf.jsqlparser.expression.Expression; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - +import com.guo.learningprogresstracker.common.TenantContext; import java.util.Arrays; import java.util.List; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.StringValue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; /** * MyBatis-Plus 多租户配置 @@ -30,12 +29,7 @@ public class MybatisPlusConfig { * 若按 created_by 过滤,每个人只能看到自己触发的那几次调用,面板等于永远空的。

*/ private static final List EXCLUDE_TABLES = Arrays.asList( - "user", - "flyway_schema_history", - "databasechangelog", - "databasechangeloglock", - "ai_usage_records" - ); + "user", "flyway_schema_history", "databasechangelog", "databasechangeloglock", "ai_usage_records"); @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { diff --git a/src/main/java/com/guo/learningprogresstracker/config/WebMvcConfig.java b/src/main/java/com/guo/learningprogresstracker/config/WebMvcConfig.java index f90cff8..e69978b 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/WebMvcConfig.java +++ b/src/main/java/com/guo/learningprogresstracker/config/WebMvcConfig.java @@ -3,6 +3,7 @@ package com.guo.learningprogresstracker.config; import cn.dev33.satoken.context.SaHolder; import cn.dev33.satoken.interceptor.SaInterceptor; import cn.dev33.satoken.stp.StpUtil; +import java.util.Arrays; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; @@ -10,8 +11,6 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import java.util.Arrays; - @Configuration @RequiredArgsConstructor @Slf4j @@ -49,7 +48,8 @@ public class WebMvcConfig implements WebMvcConfigurer { .allowedOrigins(origins) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") - .allowCredentials(corsProperties.getAllowCredentials() == null || corsProperties.getAllowCredentials()); + .allowCredentials( + corsProperties.getAllowCredentials() == null || corsProperties.getAllowCredentials()); } } } diff --git a/src/main/java/com/guo/learningprogresstracker/config/serializer/LocalDateTimeSerializer.java b/src/main/java/com/guo/learningprogresstracker/config/serializer/LocalDateTimeSerializer.java index 15932f3..c6ee0c8 100644 --- a/src/main/java/com/guo/learningprogresstracker/config/serializer/LocalDateTimeSerializer.java +++ b/src/main/java/com/guo/learningprogresstracker/config/serializer/LocalDateTimeSerializer.java @@ -3,13 +3,12 @@ package com.guo.learningprogresstracker.config.serializer; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; - import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeSerializer extends StdSerializer { - private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); public LocalDateTimeSerializer() { super(LocalDateTime.class); @@ -20,7 +19,7 @@ public class LocalDateTimeSerializer extends StdSerializer { if (value == null) { gen.writeNull(); } else { - String formattedDate = value.format(formatter); + String formattedDate = value.format(FORMATTER); gen.writeString(formattedDate); } } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/AiTaskController.java b/src/main/java/com/guo/learningprogresstracker/controller/AiTaskController.java index a44c630..2102255 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/AiTaskController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/AiTaskController.java @@ -9,7 +9,13 @@ import com.guo.learningprogresstracker.service.AiTaskService; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * AI 异步任务控制层(AI-02)。 @@ -49,8 +55,7 @@ public class AiTaskController { * @return 无任务时 data 为 null */ @GetMapping("/latest") - public CommonResult getLatestTask(@RequestParam String type, - @RequestParam String targetNum) { + public CommonResult getLatestTask(@RequestParam String type, @RequestParam String targetNum) { return CommonResult.success(aiTaskService.findLatest(type, targetNum)); } } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/AiUsageController.java b/src/main/java/com/guo/learningprogresstracker/controller/AiUsageController.java index 322b5bb..63e9711 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/AiUsageController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/AiUsageController.java @@ -9,13 +9,12 @@ import com.guo.learningprogresstracker.dto.request.AiUsageQuery; import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.service.AiUsageService; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - /** * 「AI 用量统计」面板查询接口(契约 2)。 * diff --git a/src/main/java/com/guo/learningprogresstracker/controller/AiUsageInternalController.java b/src/main/java/com/guo/learningprogresstracker/controller/AiUsageInternalController.java index 5840268..e188198 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/AiUsageInternalController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/AiUsageInternalController.java @@ -8,6 +8,7 @@ import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.service.AiUsageService; import jakarta.validation.Valid; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -15,8 +16,6 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - /** * lpt-ai 用量上报(契约 1)。 * @@ -43,7 +42,8 @@ public class AiUsageInternalController { @PostMapping("/records") public CommonResult report( @RequestHeader(name = "x-api-token", required = false) String apiToken, - @Valid @RequestBody AiUsageReportRequest request) throws ErrorParameterException { + @Valid @RequestBody AiUsageReportRequest request) + throws ErrorParameterException { if (!isTokenAccepted(apiToken)) { return CommonResult.error("上报令牌不正确"); } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/ExportController.java b/src/main/java/com/guo/learningprogresstracker/controller/ExportController.java index 3025ee6..a3a0d29 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/ExportController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/ExportController.java @@ -5,12 +5,15 @@ import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; import com.guo.learningprogresstracker.service.ExportService; +import java.time.LocalDate; import lombok.RequiredArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.time.LocalDate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * 数据导出控制层(导出-01):把学习报告、知识碎片与任务统计导出为 Markdown / JSON。 @@ -29,8 +32,7 @@ public class ExportController { */ @GetMapping("/task/{taskNum}") public CommonResult exportTask( - @PathVariable String taskNum, - @RequestParam(defaultValue = "markdown") String format) + @PathVariable String taskNum, @RequestParam(defaultValue = "markdown") String format) throws NotFindEntitiesException, OperationFailedException { return CommonResult.success(exportService.exportTask(taskNum, format)); } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/GuidanceController.java b/src/main/java/com/guo/learningprogresstracker/controller/GuidanceController.java index 13af6d0..ecfb6da 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/GuidanceController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/GuidanceController.java @@ -1,24 +1,34 @@ package com.guo.learningprogresstracker.controller; +import com.guo.learningprogresstracker.dto.AiTaskResponse; import com.guo.learningprogresstracker.dto.ReviewTiming; import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest; +import com.guo.learningprogresstracker.dto.request.ConfirmGuidanceFragmentRequest; +import com.guo.learningprogresstracker.dto.request.GuidanceStartRequest; +import com.guo.learningprogresstracker.dto.request.GuidanceTurnRequest; +import com.guo.learningprogresstracker.dto.response.GuidanceConversationResponse; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.entity.ReviewGuidanceConversationEntity; -import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.service.AiTaskService; import com.guo.learningprogresstracker.service.GuidanceService; -import com.guo.learningprogresstracker.dto.AiTaskResponse; import io.swagger.v3.oas.annotations.Operation; -import lombok.RequiredArgsConstructor; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - +import jakarta.validation.Valid; import java.time.LocalDateTime; import java.time.format.DateTimeParseException; import java.util.LinkedHashMap; import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * 学习引导控制层(复习-06)。 @@ -42,11 +52,10 @@ public class GuidanceController { */ @PostMapping @Operation(summary = "开启学习引导:返回引导编号与首个 AI 任务编号") - public CommonResult> start(@RequestBody Map body) + public CommonResult> start(@Valid @RequestBody GuidanceStartRequest request) throws NotFindEntitiesException, ErrorParameterException { - String taskNum = body == null ? null : body.get("taskNum"); - String concept = body == null ? null : body.get("concept"); - ReviewGuidanceConversationEntity conversation = guidanceService.start(taskNum, concept); + ReviewGuidanceConversationEntity conversation = + guidanceService.start(request.getTaskNum(), request.getConcept()); Map result = new LinkedHashMap<>(); result.put("guidanceNum", conversation.getGuidanceNum()); @@ -60,10 +69,10 @@ public class GuidanceController { * 继续一轮:提交用户的回答/追问,返回本轮 AI 任务编号 */ @PostMapping("/{guidanceNum}/turns") - public CommonResult continueTurn(@PathVariable String guidanceNum, - @RequestBody Map body) + public CommonResult continueTurn( + @PathVariable String guidanceNum, @Valid @RequestBody GuidanceTurnRequest request) throws NotFindEntitiesException, ErrorParameterException { - guidanceService.appendUserTurn(guidanceNum, body == null ? null : body.get("message")); + guidanceService.appendUserTurn(guidanceNum, request.getMessage()); return CommonResult.success(submitTurn(guidanceNum)); } @@ -71,9 +80,9 @@ public class GuidanceController { * 读取这次引导的当前状态(含对话轮次),用于离开页面后回来继续 */ @GetMapping("/{guidanceNum}") - public CommonResult getConversation(@PathVariable String guidanceNum) + public CommonResult getConversation(@PathVariable String guidanceNum) throws NotFindEntitiesException { - return CommonResult.success(guidanceService.getByGuidanceNum(guidanceNum)); + return CommonResult.success(GuidanceConversationResponse.of(guidanceService.getByGuidanceNum(guidanceNum))); } /** @@ -81,16 +90,16 @@ public class GuidanceController { *

不确认就不产生任何数据。

*/ @PostMapping("/{guidanceNum}/fragments") - public CommonResult confirmFragment(@PathVariable String guidanceNum, - @RequestBody Map body) + public CommonResult confirmFragment( + @PathVariable String guidanceNum, @RequestBody ConfirmGuidanceFragmentRequest request) throws ErrorParameterException, NotFindEntitiesException { - String content = body == null ? null : (String) body.get("content"); ReviewTiming timing = new ReviewTiming( - parseTime(body == null ? null : body.get("reviewStartedAt")), - parseTime(body == null ? null : body.get("reviewLastInteractionAt")), - body != null && body.get("reviewDurationSeconds") instanceof Number number - ? number.intValue() : null); - return CommonResult.success(guidanceService.confirmFragment(guidanceNum, content, timing)); + parseTime(request.getReviewStartedAt()), + parseTime(request.getReviewLastInteractionAt()), + request.getReviewDurationSeconds()); + String content = request.getContent(); + return CommonResult.success( + ReportFragmentResponse.of(guidanceService.confirmFragment(guidanceNum, content, timing))); } /** diff --git a/src/main/java/com/guo/learningprogresstracker/controller/LoginController.java b/src/main/java/com/guo/learningprogresstracker/controller/LoginController.java index 7ac72c1..452fd4e 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/LoginController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/LoginController.java @@ -1,8 +1,8 @@ package com.guo.learningprogresstracker.controller; import com.guo.learningprogresstracker.dto.LoginResult; -import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.dto.request.LoginBody; +import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.exception.AppException; import com.guo.learningprogresstracker.service.AiUsageService; import com.guo.learningprogresstracker.service.LoginService; @@ -14,7 +14,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; - @CrossOrigin @RestController @RequiredArgsConstructor @@ -31,8 +30,8 @@ public class LoginController { String token = loginService.login(userId); // 用量面板的入口是否显示由服务端白名单决定,前端只读这个布尔值 boolean aiAdmin = aiUsageService.isAdmin(); - //todo 参数传递未加密 - return CommonResult.success("登录成功!", new LoginResult(token, aiAdmin)); + // todo 参数传递未加密 + return CommonResult.success("登录成功!", new LoginResult(token, aiAdmin, userId)); } @Operation(summary = "退出登录API") diff --git a/src/main/java/com/guo/learningprogresstracker/controller/MarkerController.java b/src/main/java/com/guo/learningprogresstracker/controller/MarkerController.java index 63338fc..4087e26 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/MarkerController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/MarkerController.java @@ -1,21 +1,34 @@ package com.guo.learningprogresstracker.controller; import com.guo.learningprogresstracker.dto.MarkerUsage; +import com.guo.learningprogresstracker.dto.request.AddUserTagRequest; +import com.guo.learningprogresstracker.dto.request.CreateDictionaryTagRequest; +import com.guo.learningprogresstracker.dto.request.RenameDictionaryTagRequest; +import com.guo.learningprogresstracker.dto.request.RenameUserTagRequest; +import com.guo.learningprogresstracker.dto.response.MarkerResponse; +import com.guo.learningprogresstracker.dto.response.UserTagResponse; import com.guo.learningprogresstracker.entity.CommonResult; -import com.guo.learningprogresstracker.entity.MarkerEntity; -import com.guo.learningprogresstracker.entity.UserTagEntity; import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.service.MarkerService; import io.swagger.v3.oas.annotations.Operation; -import lombok.RequiredArgsConstructor; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - +import jakarta.validation.Valid; import java.util.Collection; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * 统一标记控制层(标记-01)。 @@ -35,20 +48,26 @@ public class MarkerController { * 列出某个对象上的全部标记(系统标记与用户标签一起返回,前端按 kind 区分展示) */ @GetMapping - public CommonResult> listByObject(@RequestParam String objectType, - @RequestParam String objectNum) { - return CommonResult.success(markerService.listByObject(MarkerObjectTypeEnum.parse(objectType), objectNum)); + public CommonResult> listByObject( + @RequestParam String objectType, @RequestParam String objectNum) { + return CommonResult.success( + markerService.listByObject(MarkerObjectTypeEnum.parse(objectType), objectNum).stream() + .map(MarkerResponse::of) + .toList()); } /** * 批量列出多个对象的标记(列表页一次取回一页,避免逐个请求) */ @PostMapping("/batch") - public CommonResult>> listByObjects( - @RequestParam String objectType, - @RequestBody Collection objectNums) { - return CommonResult.success( - markerService.listByObjects(MarkerObjectTypeEnum.parse(objectType), objectNums)); + public CommonResult>> listByObjects( + @RequestParam String objectType, @RequestBody Collection objectNums) { + Map> result = new LinkedHashMap<>(); + markerService + .listByObjects(MarkerObjectTypeEnum.parse(objectType), objectNums) + .forEach((key, value) -> + result.put(key, value.stream().map(MarkerResponse::of).toList())); + return CommonResult.success(result); } /** @@ -56,13 +75,10 @@ public class MarkerController { */ @PostMapping @Operation(summary = "打用户标签;系统标记只能由系统写入,不开放此接口") - public CommonResult addUserTag(@RequestBody Map body) + public CommonResult addUserTag(@Valid @RequestBody AddUserTagRequest request) throws ErrorParameterException, NotFindEntitiesException { - String objectType = body == null ? null : body.get("objectType"); - String objectNum = body == null ? null : body.get("objectNum"); - String markerName = body == null ? null : body.get("markerName"); - return CommonResult.success( - markerService.addUserTag(MarkerObjectTypeEnum.parse(objectType), objectNum, markerName)); + return CommonResult.success(MarkerResponse.of(markerService.addUserTag( + MarkerObjectTypeEnum.parse(request.getObjectType()), request.getObjectNum(), request.getMarkerName()))); } /** @@ -79,21 +95,20 @@ public class MarkerController { * 重命名一个用户标签(影响所有带该标签的对象) */ @PutMapping("/rename") - public CommonResult renameUserTag(@RequestBody Map body) + public CommonResult renameUserTag(@Valid @RequestBody RenameUserTagRequest request) throws ErrorParameterException { - String from = body == null ? null : body.get("oldName"); - String to = body == null ? null : body.get("newName"); - return CommonResult.success(markerService.renameUserTag(from, to)); + return CommonResult.success(markerService.renameUserTag(request.getOldName(), request.getNewName())); } /** * 按标记筛选对象(点标签即筛选):返回带该标记的对象标识列表 */ @GetMapping("/filter") - public CommonResult> filterByMarker(@RequestParam String objectType, - @RequestParam String markerName, - @RequestParam(required = false) String markerValue, - @RequestParam(required = false) String kind) { + public CommonResult> filterByMarker( + @RequestParam String objectType, + @RequestParam String markerName, + @RequestParam(required = false) String markerValue, + @RequestParam(required = false) String kind) { return CommonResult.success(markerService.findObjectNumsByMarker( MarkerObjectTypeEnum.parse(objectType), markerName, markerValue, kind)); } @@ -102,37 +117,38 @@ public class MarkerController { * 当前用户用过的标签及使用情况(标签管理入口) */ @GetMapping("/tags") - public CommonResult> listUserTagUsage() { - return CommonResult.success(markerService.listUserTagUsage()); + public CommonResult> listUserTagUsage(@RequestParam(required = false) String objectType) { + return CommonResult.success( + markerService.listUserTagUsage(objectType == null ? null : MarkerObjectTypeEnum.parse(objectType))); } /** * 标签字典:打标签的候选标签(尚未挂在任何对象上的也算) */ @GetMapping("/tags/dictionary") - public CommonResult> listDictionaryTags() { - return CommonResult.success(markerService.listDictionaryTags()); + public CommonResult> listDictionaryTags() { + return CommonResult.success(markerService.listDictionaryTags().stream() + .map(UserTagResponse::of) + .toList()); } /** * 往字典里新建一个(空)标签;同名(按去空格、大小写不敏感)已存在时幂等返回既有项 */ @PostMapping("/tags/dictionary") - public CommonResult createDictionaryTag(@RequestBody Map body) + public CommonResult createDictionaryTag(@Valid @RequestBody CreateDictionaryTagRequest request) throws ErrorParameterException { - String tagName = body == null ? null : body.get("tagName"); - return CommonResult.success(markerService.createDictionaryTag(tagName)); + return CommonResult.success(UserTagResponse.of(markerService.createDictionaryTag(request.getTagName()))); } /** * 字典标签改名:只影响候选,不改动任何对象上已经打好的标记 */ @PutMapping("/tags/dictionary/{id}") - public CommonResult renameDictionaryTag(@PathVariable Integer id, - @RequestBody Map body) + public CommonResult renameDictionaryTag( + @PathVariable Integer id, @Valid @RequestBody RenameDictionaryTagRequest request) throws ErrorParameterException, NotFindEntitiesException { - String newName = body == null ? null : body.get("newName"); - return CommonResult.success(markerService.renameDictionaryTag(id, newName)); + return CommonResult.success(UserTagResponse.of(markerService.renameDictionaryTag(id, request.getNewName()))); } /** diff --git a/src/main/java/com/guo/learningprogresstracker/controller/reportFragmentsController.java b/src/main/java/com/guo/learningprogresstracker/controller/ReportFragmentsController.java similarity index 58% rename from src/main/java/com/guo/learningprogresstracker/controller/reportFragmentsController.java rename to src/main/java/com/guo/learningprogresstracker/controller/ReportFragmentsController.java index 8fb4378..6a3d189 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/reportFragmentsController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/ReportFragmentsController.java @@ -1,18 +1,24 @@ package com.guo.learningprogresstracker.controller; +import com.guo.learningprogresstracker.dto.request.AssignOwnershipRequest; import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; import com.guo.learningprogresstracker.dto.request.UpdateFragmentsRequest; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; import com.guo.learningprogresstracker.entity.CommonResult; -import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.service.impl.StudyReportFragmentsServiceImpl; import jakarta.validation.Valid; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; /** * 知识碎片控制层(归属-01 起同时承载「内容归属」的调整动作)。 @@ -21,14 +27,15 @@ import java.util.Map; @RestController @Validated @RequiredArgsConstructor -public class reportFragmentsController { +public class ReportFragmentsController { private final StudyReportFragmentsServiceImpl studyReportFragmentsServiceImpl; /** * 创建知识碎片(记录上下文为当前学习会话,内容归属默认取该会话所属任务) */ @PostMapping - public CommonResult createFragments(@Valid @RequestBody CreateFragmentsRequest request) throws NotFindEntitiesException { + public CommonResult createFragments(@Valid @RequestBody CreateFragmentsRequest request) + throws NotFindEntitiesException { studyReportFragmentsServiceImpl.createFragments(request); return CommonResult.success(); } @@ -37,8 +44,8 @@ public class reportFragmentsController { * 修改知识碎片正文与内容归属(记录上下文不可变) */ @PutMapping("/{id}") - public CommonResult updateFragments(@PathVariable Integer id, - @RequestBody UpdateFragmentsRequest request) throws NotFindEntitiesException { + public CommonResult updateFragments(@PathVariable Integer id, @RequestBody UpdateFragmentsRequest request) + throws NotFindEntitiesException { studyReportFragmentsServiceImpl.updateFragments(id, request); return CommonResult.success(); } @@ -47,10 +54,10 @@ public class reportFragmentsController { * 调整内容归属;body 传 {"ownerTaskNum": "TASK-xxx"},传空字符串表示清空归属(回到待归类) */ @PutMapping("/{id}/ownership") - public CommonResult assignOwnership(@PathVariable Integer id, - @RequestBody Map body) throws NotFindEntitiesException { - String ownerTaskNum = body == null ? null : body.get("ownerTaskNum"); - studyReportFragmentsServiceImpl.assignOwnership(id, ownerTaskNum); + public CommonResult assignOwnership( + @PathVariable Integer id, @Valid @RequestBody AssignOwnershipRequest request) + throws NotFindEntitiesException { + studyReportFragmentsServiceImpl.assignOwnership(id, request.getOwnerTaskNum()); return CommonResult.success(); } @@ -67,8 +74,11 @@ public class reportFragmentsController { * 获取指定会话产生的所有知识碎片(记录上下文为会话) */ @GetMapping("/session/{sessionNum}") - public CommonResult> getFragmentsBySession(@PathVariable String sessionNum) { - List fragments = studyReportFragmentsServiceImpl.getFragmentsBySession(sessionNum); + public CommonResult> getFragmentsBySession(@PathVariable String sessionNum) { + List fragments = + studyReportFragmentsServiceImpl.getFragmentsBySession(sessionNum).stream() + .map(ReportFragmentResponse::of) + .toList(); return CommonResult.success(fragments); } @@ -76,7 +86,9 @@ public class reportFragmentsController { * 待归类内容:还没有确定内容归属的碎片 */ @GetMapping("/pending-ownership") - public CommonResult> getPendingOwnershipFragments() { - return CommonResult.success(studyReportFragmentsServiceImpl.getPendingOwnershipFragments()); + public CommonResult> getPendingOwnershipFragments() { + return CommonResult.success(studyReportFragmentsServiceImpl.getPendingOwnershipFragments().stream() + .map(ReportFragmentResponse::of) + .toList()); } } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/ReviewController.java b/src/main/java/com/guo/learningprogresstracker/controller/ReviewController.java index 60bdf23..eb788cd 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/ReviewController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/ReviewController.java @@ -1,30 +1,38 @@ package com.guo.learningprogresstracker.controller; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.guo.learningprogresstracker.dto.ReviewFeedItem; import com.guo.learningprogresstracker.dto.ReviewSortPreference; import com.guo.learningprogresstracker.dto.ReviewSummary; import com.guo.learningprogresstracker.dto.ReviewTaskStats; import com.guo.learningprogresstracker.dto.StudyReportDetail; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.guo.learningprogresstracker.dto.request.UpdateStandardMindMapRequest; +import com.guo.learningprogresstracker.dto.request.FindNodeRequest; import com.guo.learningprogresstracker.dto.request.ReviewFeedbackRequest; +import com.guo.learningprogresstracker.dto.request.SortPreferenceRequest; +import com.guo.learningprogresstracker.dto.request.UpdateStandardMindMapRequest; import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; +import com.guo.learningprogresstracker.dto.response.StandardMindMapResponse; +import com.guo.learningprogresstracker.dto.response.StudyReportResponse; import com.guo.learningprogresstracker.entity.CommonResult; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; -import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; -import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; import com.guo.learningprogresstracker.service.ReviewService; import com.guo.learningprogresstracker.service.StandardMindMapService; import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - import java.util.List; import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * 复习模块控制层 — 复习内容滚动展示与交互 @@ -44,8 +52,7 @@ public class ReviewController { */ @GetMapping("/feed") public CommonResult> getReviewFeed( - @RequestParam(defaultValue = "30") int limit, - @RequestParam(defaultValue = "recent") String mode) { + @RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "recent") String mode) { return CommonResult.success(reviewService.getReviewFeed(limit, mode)); } @@ -55,8 +62,8 @@ public class ReviewController { */ @PutMapping("/feed/{fragmentId}/feedback") public CommonResult submitFeedback( - @PathVariable Integer fragmentId, - @RequestBody ReviewFeedbackRequest request) throws NotFindEntitiesException { + @PathVariable Integer fragmentId, @RequestBody ReviewFeedbackRequest request) + throws NotFindEntitiesException { return CommonResult.success(reviewService.submitFeedback(fragmentId, request)); } @@ -81,9 +88,8 @@ public class ReviewController { * 保存复习排序偏好(复习-01):三档预设,不做精确权重。 */ @PutMapping("/sort-preference") - public CommonResult saveSortPreference(@RequestBody Map body) { - String preset = body == null ? null : body.get("preset"); - return CommonResult.success(reviewService.saveSortPreference(preset)); + public CommonResult saveSortPreference(@RequestBody SortPreferenceRequest request) { + return CommonResult.success(reviewService.saveSortPreference(request.getPreset())); } /** @@ -132,8 +138,8 @@ public class ReviewController { * 获取报告详情(原始实体) */ @GetMapping("/report/{id}") - public CommonResult getReportDetail(@PathVariable int id) throws NotFindEntitiesException { - return CommonResult.success(reviewService.getReportDetail(id)); + public CommonResult getReportDetail(@PathVariable int id) throws NotFindEntitiesException { + return CommonResult.success(StudyReportResponse.of(reviewService.getReportDetail(id))); } /** @@ -149,8 +155,7 @@ public class ReviewController { * 修改学习报告的三段文本 */ @PutMapping("/report/{id}") - public CommonResult updateReport(@PathVariable int id, - @RequestBody UpdateStudyReportRequest request) + public CommonResult updateReport(@PathVariable int id, @RequestBody UpdateStudyReportRequest request) throws NotFindEntitiesException { reviewService.updateReport(id, request); return CommonResult.success(); @@ -169,8 +174,9 @@ public class ReviewController { * 获取残片详情 */ @GetMapping("/fragment/{id}") - public CommonResult getFragmentDetail(@PathVariable int id) throws NotFindEntitiesException { - return CommonResult.success(reviewService.getFragmentDetail(id)); + public CommonResult getFragmentDetail(@PathVariable int id) + throws NotFindEntitiesException { + return CommonResult.success(ReportFragmentResponse.of(reviewService.getFragmentDetail(id))); } // ============ 标准思维导图与回忆对比 ============ @@ -182,19 +188,20 @@ public class ReviewController { * {@code POST /ai/tasks}(type=MIND_MAP)后轮询结果。

*/ @GetMapping("/standard-mind-map/{taskNum}") - public CommonResult getStandardMindMap( - @PathVariable String taskNum) throws NotFindEntitiesException { - return CommonResult.success(standardMindMapService.getExisting(taskNum)); + public CommonResult getStandardMindMap(@PathVariable String taskNum) + throws NotFindEntitiesException { + return CommonResult.success(StandardMindMapResponse.of(standardMindMapService.getExisting(taskNum))); } /** * 用户编辑标准思维导图(大纲文本形式) */ @PutMapping("/standard-mind-map/{taskNum}") - public CommonResult updateStandardMindMap( - @PathVariable String taskNum, - @Valid @RequestBody UpdateStandardMindMapRequest request) throws NotFindEntitiesException { - return CommonResult.success(standardMindMapService.updateByOutline(taskNum, request.getOutline())); + public CommonResult updateStandardMindMap( + @PathVariable String taskNum, @Valid @RequestBody UpdateStandardMindMapRequest request) + throws NotFindEntitiesException { + return CommonResult.success( + StandardMindMapResponse.of(standardMindMapService.updateByOutline(taskNum, request.getOutline()))); } /** @@ -202,27 +209,9 @@ public class ReviewController { */ @PostMapping("/standard-mind-map/{taskNum}/find-node") public CommonResult> findNode( - @PathVariable String taskNum, - @RequestBody Map body) throws NotFindEntitiesException, OperationFailedException { - String content = body != null ? body.getOrDefault("content", "") : ""; + @PathVariable String taskNum, @RequestBody FindNodeRequest request) + throws NotFindEntitiesException, OperationFailedException { + String content = request == null || request.getContent() == null ? "" : request.getContent(); return CommonResult.success(standardMindMapService.findNode(taskNum, content)); } - - /** - * 获取该任务的所有回忆对比记录 - */ - @GetMapping("/standard-mind-map/{taskNum}/recall-records") - public CommonResult> listRecallRecords( - @PathVariable String taskNum) throws NotFindEntitiesException { - return CommonResult.success(standardMindMapService.listRecallRecords(taskNum)); - } - - /** - * 获取单条回忆对比记录详情 - */ - @GetMapping("/standard-mind-map/recall-records/{recordId}") - public CommonResult getRecallRecord( - @PathVariable Integer recordId) throws NotFindEntitiesException { - return CommonResult.success(standardMindMapService.getRecallRecord(recordId)); - } } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java b/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java new file mode 100644 index 0000000..41da0c0 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/controller/ReviewRecallController.java @@ -0,0 +1,90 @@ +package com.guo.learningprogresstracker.controller; + +import com.fasterxml.jackson.databind.JsonNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.CreateRecallRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.EndRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallPage; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceContent; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferencePage; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ResumeRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.SaveDraftRequest; +import com.guo.learningprogresstracker.entity.CommonResult; +import com.guo.learningprogresstracker.service.ai.RecallJson; +import com.guo.learningprogresstracker.service.recall.ReviewRecallService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/review/recalls") +@RequiredArgsConstructor +public class ReviewRecallController { + private final ReviewRecallService service; + private final RecallJson json; + + @PostMapping + public CommonResult create(@RequestBody JsonNode body) { + return CommonResult.success(service.create(json.readInput(body, CreateRecallRequest.class))); + } + + @GetMapping + public CommonResult list( + @RequestParam(defaultValue = "1") int pageNum, + @RequestParam(defaultValue = "20") int pageSize, + @RequestParam(required = false) String status, + @RequestParam(required = false) String scopeType, + @RequestParam(required = false) String taskNum, + @RequestParam org.springframework.util.MultiValueMap query, + @RequestParam(required = false) String combineMode) { + // Read repeated values verbatim: a comma can be part of a single tag name. + return CommonResult.success( + service.list(pageNum, pageSize, status, scopeType, taskNum, query.get("tags"), combineMode)); + } + + @GetMapping("/{recallNum}") + public CommonResult get(@PathVariable String recallNum) { + return CommonResult.success(service.get(recallNum)); + } + + @PostMapping("/{recallNum}/resume") + public CommonResult resume(@PathVariable String recallNum, @RequestBody JsonNode body) { + return CommonResult.success(service.resume(recallNum, json.readInput(body, ResumeRequest.class))); + } + + @PutMapping("/{recallNum}/draft") + public CommonResult draft(@PathVariable String recallNum, @RequestBody JsonNode body) { + return CommonResult.success(service.draft(recallNum, json.readInput(body, SaveDraftRequest.class))); + } + + @GetMapping("/{recallNum}/references") + public CommonResult references( + @PathVariable String recallNum, + @RequestParam(defaultValue = "1") int pageNum, + @RequestParam(defaultValue = "10") int pageSize) { + return CommonResult.success(service.references(recallNum, pageNum, pageSize)); + } + + @GetMapping("/{recallNum}/references/sources/{sourceId}") + public CommonResult source(@PathVariable String recallNum, @PathVariable String sourceId) { + return CommonResult.success(service.source(recallNum, sourceId)); + } + + @PostMapping("/{recallNum}/end") + public CommonResult end(@PathVariable String recallNum, @RequestBody JsonNode body) { + return CommonResult.success(service.end(recallNum, json.readInput(body, EndRequest.class))); + } + + @DeleteMapping("/{recallNum}") + public CommonResult delete(@PathVariable String recallNum) { + service.delete(recallNum); + return CommonResult.success(); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/controller/StudySessionController.java b/src/main/java/com/guo/learningprogresstracker/controller/StudySessionController.java index ecb56e2..d9703ce 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/StudySessionController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/StudySessionController.java @@ -1,13 +1,15 @@ package com.guo.learningprogresstracker.controller; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.google.protobuf.ServiceException; import com.guo.learningprogresstracker.dto.request.AbortStudySessionRequest; import com.guo.learningprogresstracker.dto.request.EndedStudySessionRequest; import com.guo.learningprogresstracker.dto.request.UpsertExpectationRequest; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; +import com.guo.learningprogresstracker.dto.response.StudyExpectationResponse; +import com.guo.learningprogresstracker.dto.response.StudyReportResponse; import com.guo.learningprogresstracker.dto.response.StudySessionResponse; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.guo.learningprogresstracker.entity.CommonResult; -import com.guo.learningprogresstracker.entity.StudyExpectationsEntity; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.exception.ErrorParameterException; @@ -15,12 +17,18 @@ import com.guo.learningprogresstracker.service.StudyExpectationsService; import com.guo.learningprogresstracker.service.impl.StudySessionsServiceImpl; import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; +import java.time.LocalDateTime; +import java.util.ArrayList; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; -import java.time.LocalDateTime; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * 学习会话控制层 @@ -39,26 +47,27 @@ public class StudySessionController { * 创建/更新学习会话的学习预期 */ @PutMapping("/{sessionNum}/expectation") - public CommonResult upsertExpectation( - @PathVariable("sessionNum") String sessionNum, - @Valid @RequestBody UpsertExpectationRequest request) throws ErrorParameterException { - return CommonResult.success(studyExpectationsService.upsertExpectation(sessionNum, request.getDescription())); + public CommonResult upsertExpectation( + @PathVariable("sessionNum") String sessionNum, @Valid @RequestBody UpsertExpectationRequest request) + throws ErrorParameterException { + return CommonResult.success(StudyExpectationResponse.of( + studyExpectationsService.upsertExpectation(sessionNum, request.getDescription()))); } /** * 获取学习会话的学习预期 */ @GetMapping("/{sessionNum}/expectation") - public CommonResult getExpectation( - @PathVariable("sessionNum") String sessionNum) { - return CommonResult.success(studyExpectationsService.getBySessionNum(sessionNum)); + public CommonResult getExpectation(@PathVariable("sessionNum") String sessionNum) { + return CommonResult.success(StudyExpectationResponse.of(studyExpectationsService.getBySessionNum(sessionNum))); } /** * 通过sessionNum获取一个【学习会话】 */ @GetMapping("/{sessionNum}") - public CommonResult getStudySessionBySessionNum(@NotEmpty(message = "请提供学习会话编号") @PathVariable String sessionNum) throws ErrorParameterException { + public CommonResult getStudySessionBySessionNum( + @NotEmpty(message = "请提供学习会话编号") @PathVariable String sessionNum) throws ErrorParameterException { // 通过 service 层获取,包含归属校验 StudySessionResponse response = studySessionsServiceImpl.getStudySessionBySessionNum(sessionNum); return CommonResult.success(response); @@ -68,7 +77,8 @@ public class StudySessionController { * 开始一个【学习会话】 */ @PostMapping("/{sessionNum}/study-sessions/continue") - public CommonResult startStudySession(@PathVariable("sessionNum") String sessionNum) throws ErrorParameterException, ServiceException { + public CommonResult startStudySession(@PathVariable("sessionNum") String sessionNum) + throws ErrorParameterException, ServiceException { studySessionsServiceImpl.continueStudySession(sessionNum); return CommonResult.success(); } @@ -77,8 +87,9 @@ public class StudySessionController { * 暂停一个【学习会话】 */ @PostMapping("/{sessionNum}/study-sessions/pause") - public CommonResult pauseStudySession(@PathVariable("sessionNum") String sessionNum, - @RequestParam(value = "endTime", required = false) LocalDateTime endTime) + public CommonResult pauseStudySession( + @PathVariable("sessionNum") String sessionNum, + @RequestParam(value = "endTime", required = false) LocalDateTime endTime) throws ErrorParameterException, ServiceException { studySessionsServiceImpl.pauseStudySession(sessionNum, endTime); return CommonResult.success(); @@ -88,9 +99,11 @@ public class StudySessionController { * 结束一个【学习会话】 */ @PostMapping("/{sessionNum}/study-sessions/ended") - public CommonResult endedStudySession(@PathVariable("sessionNum") String sessionNum, - @Valid @RequestBody EndedStudySessionRequest request) throws ErrorParameterException { - String message = studySessionsServiceImpl.endedStudySession(sessionNum, + public CommonResult endedStudySession( + @PathVariable("sessionNum") String sessionNum, @Valid @RequestBody EndedStudySessionRequest request) + throws ErrorParameterException { + String message = studySessionsServiceImpl.endedStudySession( + sessionNum, new com.guo.learningprogresstracker.dto.ReportSections( request.getSessionSummary(), request.getExpectationVerdict(), request.getFreeSummary())); return message != null ? CommonResult.success(message) : CommonResult.success(); @@ -100,8 +113,9 @@ public class StudySessionController { * 误操作结束一个【学习会话】:需输入确认语,严格零数据(删除会话与预期),仅未产生学习残片时可用 */ @PostMapping("/{sessionNum}/study-sessions/abort") - public CommonResult abortStudySession(@PathVariable("sessionNum") String sessionNum, - @Valid @RequestBody AbortStudySessionRequest request) throws ErrorParameterException { + public CommonResult abortStudySession( + @PathVariable("sessionNum") String sessionNum, @Valid @RequestBody AbortStudySessionRequest request) + throws ErrorParameterException { studySessionsServiceImpl.abortStudySession(sessionNum, request.getConfirmation()); return CommonResult.success(); } @@ -110,36 +124,45 @@ public class StudySessionController { * 获取【学习会话】所有的学习残片数据,以列表返回 */ @GetMapping("/{sessionNum}/all-fragments") - public CommonResult> getAllFragments(@PathVariable("sessionNum") String sessionNum) throws ErrorParameterException { + public CommonResult> getAllFragments(@PathVariable("sessionNum") String sessionNum) + throws ErrorParameterException { ArrayList allFragments = studySessionsServiceImpl.getAllFragments(sessionNum); return CommonResult.success(allFragments); - } /** 分页查询任务的残片历史 */ @GetMapping("/tasks/{taskNum}/fragments") - public CommonResult> getTaskFragments( + public CommonResult> getTaskFragments( @PathVariable String taskNum, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size, @RequestParam(required = false) String keyword) { - return CommonResult.success(studySessionsServiceImpl.getTaskFragments(taskNum, page, size, keyword)); + Page entities = + studySessionsServiceImpl.getTaskFragments(taskNum, page, size, keyword); + Page result = + new Page<>(entities.getCurrent(), entities.getSize(), entities.getTotal()); + result.setRecords( + entities.getRecords().stream().map(ReportFragmentResponse::of).toList()); + return CommonResult.success(result); } /** 分页查询任务的报告历史 */ @GetMapping("/tasks/{taskNum}/reports") - public CommonResult> getTaskReports( + public CommonResult> getTaskReports( @PathVariable String taskNum, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size, @RequestParam(required = false) String keyword) { - return CommonResult.success(studySessionsServiceImpl.getTaskReports(taskNum, page, size, keyword)); + Page entities = studySessionsServiceImpl.getTaskReports(taskNum, page, size, keyword); + Page result = new Page<>(entities.getCurrent(), entities.getSize(), entities.getTotal()); + result.setRecords( + entities.getRecords().stream().map(StudyReportResponse::of).toList()); + return CommonResult.success(result); } /** 查询当前是否有活跃会话(用于跨页面恢复 + 阻止多任务) */ @GetMapping("/active") - public CommonResult getActiveSession( - @RequestParam(required = false) String excludeTaskNum) { + public CommonResult getActiveSession(@RequestParam(required = false) String excludeTaskNum) { return CommonResult.success(studySessionsServiceImpl.getActiveSession(excludeTaskNum)); } } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java b/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java index 09ec29f..9545879 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/TagMindMapController.java @@ -6,17 +6,20 @@ 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.dto.response.TagMindMapResponse; import com.guo.learningprogresstracker.entity.CommonResult; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -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.*; - -import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** * 标签导图控制层(闭环-04)。 @@ -24,8 +27,7 @@ import java.util.List; *

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

* - *

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

+ *

生成走 {@code POST /ai/tasks}(type=TAG_MIND_MAP),复习统一进入自由回忆工作区。

*/ @RequestMapping("/review/tag-mind-map") @RestController @@ -52,10 +54,11 @@ public class TagMindMapController { * 用户编辑标签导图(大纲文本形式);该范围还没有导图时保存即为新建。 */ @PutMapping - public CommonResult updateTagMindMap( - @Valid @RequestBody UpdateTagMindMapRequest request) throws ErrorParameterException { + 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())); + return CommonResult.success( + TagMindMapResponse.of(reviewTagMindMapService.updateByOutline(scope, request.getOutline()))); } /** @@ -70,14 +73,4 @@ public class TagMindMapController { @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) { return CommonResult.success(reviewTagMindMapService.listMaps(pageNum, pageSize)); } - - /** - * 该范围的回忆对比记录(倒序,最近一次在最前);范围里没有记录时返回空列表。 - */ - @PostMapping("/recall-records") - public CommonResult> listRecallRecords( - @Valid @RequestBody TagScopeRequest request) throws ErrorParameterException { - TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode()); - return CommonResult.success(reviewTagMindMapService.listRecallRecords(scope)); - } } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/TaskController.java b/src/main/java/com/guo/learningprogresstracker/controller/TaskController.java index de9bf40..9ee06b4 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/TaskController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/TaskController.java @@ -6,13 +6,14 @@ import com.guo.learningprogresstracker.common.Ops; import com.guo.learningprogresstracker.dto.TaskInfo; import com.guo.learningprogresstracker.dto.TaskOption; import com.guo.learningprogresstracker.dto.request.CreateTaskApplicationRequest; -import com.guo.learningprogresstracker.dto.response.StudySessionResponse; -import com.guo.learningprogresstracker.dto.response.TaskInfoResponse; -import com.guo.learningprogresstracker.entity.CommonResult; +import com.guo.learningprogresstracker.dto.request.PriorityWeightsRequest; import com.guo.learningprogresstracker.dto.request.TaskRequest; import com.guo.learningprogresstracker.dto.request.UpdateTaskApplicationRequest; -import com.guo.learningprogresstracker.entity.TaskApplicationEntity; -import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity; +import com.guo.learningprogresstracker.dto.response.PriorityWeightsResponse; +import com.guo.learningprogresstracker.dto.response.StudySessionResponse; +import com.guo.learningprogresstracker.dto.response.TaskApplicationResponse; +import com.guo.learningprogresstracker.dto.response.TaskInfoResponse; +import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.service.PriorityWeightsService; @@ -21,6 +22,8 @@ import com.guo.learningprogresstracker.service.impl.StudySessionsServiceImpl; import io.swagger.v3.oas.annotations.Operation; import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; +import java.rmi.ServerException; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; @@ -33,9 +36,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.rmi.ServerException; -import java.util.List; - /** * 任务控制层 * @@ -55,20 +55,21 @@ public class TaskController { @GetMapping("/priority-weights") @Operation(summary = "获取优先级维度权重配置") - public CommonResult getPriorityWeights() { - return CommonResult.success(priorityWeightsService.getWeights()); + public CommonResult getPriorityWeights() { + return CommonResult.success(PriorityWeightsResponse.of(priorityWeightsService.getWeights())); } @PutMapping("/priority-weights") @Operation(summary = "保存优先级维度权重配置并重算全部任务优先级") - public CommonResult savePriorityWeights( - @RequestBody UserPriorityWeightsEntity weights) throws ErrorParameterException { - return CommonResult.success(priorityWeightsService.saveWeights(weights)); + public CommonResult savePriorityWeights(@Valid @RequestBody PriorityWeightsRequest request) + throws ErrorParameterException { + return CommonResult.success(PriorityWeightsResponse.of(priorityWeightsService.saveWeights(request.toEntity()))); } @PostMapping @Operation(summary = "添加新任务") - public CommonResult addTask(@RequestBody @Validated({Ops.CreateG.class}) TaskRequest taskRequest) throws ErrorParameterException { + public CommonResult addTask(@RequestBody @Validated({Ops.CreateG.class}) TaskRequest taskRequest) + throws ErrorParameterException { return CommonResult.success("请求成功", tasksService.addTask(taskRequest)); } @@ -80,7 +81,8 @@ public class TaskController { @PutMapping("/{taskId}") @Operation(summary = "更新任务详情") - public CommonResult updateTask(@PathVariable("taskId") String taskId, @Validated(Ops.UpdateG.class) @RequestBody TaskRequest updatedTask) { + public CommonResult updateTask( + @PathVariable("taskId") String taskId, @Validated(Ops.UpdateG.class) @RequestBody TaskRequest updatedTask) { tasksService.updateTask(taskId, updatedTask); return CommonResult.success(); } @@ -101,25 +103,28 @@ public class TaskController { @GetMapping("/{taskNum}/applications") @Operation(summary = "获取任务应用场景列表") - public CommonResult> getApplications(@PathVariable String taskNum) throws NotFindEntitiesException { - return CommonResult.success(tasksService.getApplications(taskNum)); + public CommonResult> getApplications(@PathVariable String taskNum) + throws NotFindEntitiesException { + return CommonResult.success(tasksService.getApplications(taskNum).stream() + .map(TaskApplicationResponse::of) + .toList()); } @PostMapping("/{taskNum}/applications") @Operation(summary = "创建任务应用场景") - public CommonResult createApplication( - @PathVariable String taskNum, - @Valid @RequestBody CreateTaskApplicationRequest request) throws NotFindEntitiesException { + public CommonResult createApplication( + @PathVariable String taskNum, @Valid @RequestBody CreateTaskApplicationRequest request) + throws NotFindEntitiesException { request.setTaskNum(taskNum); - return CommonResult.success(tasksService.createApplication(request)); + return CommonResult.success(TaskApplicationResponse.of(tasksService.createApplication(request))); } @PutMapping("/applications/{id}") @Operation(summary = "更新任务应用场景") - public CommonResult updateApplication( - @PathVariable Integer id, - @Valid @RequestBody UpdateTaskApplicationRequest request) throws NotFindEntitiesException { - return CommonResult.success(tasksService.updateApplication(id, request)); + public CommonResult updateApplication( + @PathVariable Integer id, @Valid @RequestBody UpdateTaskApplicationRequest request) + throws NotFindEntitiesException { + return CommonResult.success(TaskApplicationResponse.of(tasksService.updateApplication(id, request))); } @DeleteMapping("/applications/{id}") @@ -137,8 +142,9 @@ public class TaskController { @GetMapping @Operation(summary = "获取所有任务列表") - public CommonResult> tasksList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, - @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { + public CommonResult> tasksList( + @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, + @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { return CommonResult.success(tasksService.taskList(pageNum, pageSize)); } @@ -146,19 +152,19 @@ public class TaskController { * 开始或继续一个【学习会话】 */ @GetMapping("/{taskNum}/study-sessions/start-or-continue") - public CommonResult startOrContinueStudySession(@NotEmpty(message = "请提供任务编号") - @PathVariable String taskNum) throws NotFindEntitiesException, ServiceException { + public CommonResult startOrContinueStudySession( + @NotEmpty(message = "请提供任务编号") @PathVariable String taskNum) + throws NotFindEntitiesException, ErrorParameterException, ServiceException { StudySessionResponse response = studySessionsServiceImpl.startOrContinueStudySession(taskNum); return CommonResult.success(response); - } /** * 通过学习任务num获取该任务的未结束会话 */ @GetMapping("/{taskNum}/not-ended-study-session") - public CommonResult getNotEndedStudySessionByTaskNum(@NotEmpty(message = "请提供任务编号") - @PathVariable String taskNum) throws ErrorParameterException { + public CommonResult getNotEndedStudySessionByTaskNum( + @NotEmpty(message = "请提供任务编号") @PathVariable String taskNum) throws ErrorParameterException { StudySessionResponse response = studySessionsServiceImpl.getNotEndedStudySessionByTaskNum(taskNum); return CommonResult.success(response); } diff --git a/src/main/java/com/guo/learningprogresstracker/controller/UtilsController.java b/src/main/java/com/guo/learningprogresstracker/controller/UtilsController.java index df8c44b..a0020a0 100644 --- a/src/main/java/com/guo/learningprogresstracker/controller/UtilsController.java +++ b/src/main/java/com/guo/learningprogresstracker/controller/UtilsController.java @@ -3,13 +3,12 @@ package com.guo.learningprogresstracker.controller; import com.guo.learningprogresstracker.entity.CommonResult; import com.guo.learningprogresstracker.utils.TitleFetcher; import io.swagger.v3.oas.annotations.Operation; +import java.util.Map; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.Map; - @RestController @RequestMapping("/utils") public class UtilsController { diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiTaskResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/AiTaskResponse.java index 9eef487..71feb2f 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiTaskResponse.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiTaskResponse.java @@ -2,10 +2,9 @@ package com.guo.learningprogresstracker.dto; import com.guo.learningprogresstracker.entity.AiTaskEntity; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - import java.time.LocalDateTime; import java.util.Map; +import lombok.Data; /** * AI 任务对外视图(AI-02)。 @@ -18,7 +17,7 @@ public class AiTaskResponse { @Schema(description = "AI 任务编号") private String taskNum; - @Schema(description = "任务类型:RECALL_COMPARE / MIND_MAP / REPORT_DRAFT") + @Schema(description = "任务类型:RECALL_HINT / RECALL_CHECK / MIND_MAP / TAG_MIND_MAP / REPORT_DRAFT / GUIDANCE") private String type; @Schema(description = "目标编号:学习任务编号或学习会话编号") @@ -30,6 +29,8 @@ public class AiTaskResponse { @Schema(description = "失败原因(用户可见文案)") private String errorMessage; + private String errorCode; + @Schema(description = "提交时间") private LocalDateTime createdTime; @@ -39,6 +40,28 @@ public class AiTaskResponse { @Schema(description = "成功结果,随任务类型不同;未完成时为 null") private Map result; + @com.fasterxml.jackson.annotation.JsonGetter("createdTime") + public Object createdTimeJson() { + return createdTime == null + ? null + : isRecall() + ? createdTime.atZone(java.time.ZoneId.systemDefault()).toInstant() + : createdTime; + } + + @com.fasterxml.jackson.annotation.JsonGetter("finishedTime") + public Object finishedTimeJson() { + return finishedTime == null + ? null + : isRecall() + ? finishedTime.atZone(java.time.ZoneId.systemDefault()).toInstant() + : finishedTime; + } + + private boolean isRecall() { + return "RECALL_HINT".equals(type) || "RECALL_CHECK".equals(type); + } + public static AiTaskResponse from(AiTaskEntity entity, Map result) { AiTaskResponse response = new AiTaskResponse(); response.setTaskNum(entity.getTaskNum()); @@ -46,6 +69,7 @@ public class AiTaskResponse { response.setTargetNum(entity.getTargetNum()); response.setStatus(entity.getStatus()); response.setErrorMessage(entity.getErrorMessage()); + response.setErrorCode(entity.getErrorCode()); response.setCreatedTime(entity.getCreatedTime()); response.setFinishedTime(entity.getFinishedTime()); response.setResult(result); diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java index 5ef0365..ee0c101 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownItem.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * 用量按任务类型 / 模型 / 用户分组的一项(契约 2.4、v2 第 4.2 节,{@code GET /ai/usage/breakdown})。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownRow.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownRow.java index a13bb35..8a27365 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownRow.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageBreakdownRow.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * 用量按任务类型 / 模型分组的聚合结果(Mapper 层直接映射,契约 2.4)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesPoint.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesPoint.java index abddf58..bbe8607 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesPoint.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesPoint.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * 用量趋势的一个分桶(契约 2.3,{@code GET /ai/usage/series})。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesRow.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesRow.java index 3a87033..dbc651f 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesRow.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSeriesRow.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * 用量趋势的分桶聚合结果(Mapper 层直接映射,契约 2.3)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummary.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummary.java index aba0243..6910425 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummary.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummary.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * AI 用量汇总(契约 2.2,{@code GET /ai/usage/summary})。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummaryRow.java b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummaryRow.java index 9eff3d9..f6034da 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummaryRow.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/AiUsageSummaryRow.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * 用量汇总的聚合结果(Mapper 层直接映射,契约 2.2)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/ExportDocument.java b/src/main/java/com/guo/learningprogresstracker/dto/ExportDocument.java index 5f0e5dd..a9ec35d 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/ExportDocument.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/ExportDocument.java @@ -1,11 +1,10 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import lombok.Data; /** * 一次导出的完整文档(导出-01)。Markdown 与 JSON 都由它渲染,保证两种格式内容一致。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/ExportEntry.java b/src/main/java/com/guo/learningprogresstracker/dto/ExportEntry.java index 46cd5b6..b84c03d 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/ExportEntry.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/ExportEntry.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.time.LocalDateTime; +import lombok.Data; /** * 导出的一条内容(学习报告或知识碎片,导出-01)。 @@ -12,9 +11,14 @@ public class ExportEntry { private Integer id; - /** 记录上下文:产生这条内容的学习会话编号 */ + /** 兼容字段:仅 SESSION 来源填写;复习行为不伪造学习会话。 */ private String sessionNum; + /** SESSION / REVIEW,独立于内容归属。 */ + private String contextType; + + private String contextNum; + private LocalDateTime createdTime; /** 报告或碎片的原文 */ diff --git a/src/main/java/com/guo/learningprogresstracker/dto/ExportTaskSection.java b/src/main/java/com/guo/learningprogresstracker/dto/ExportTaskSection.java index 04914d0..f5bab55 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/ExportTaskSection.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/ExportTaskSection.java @@ -1,9 +1,8 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.util.ArrayList; import java.util.List; +import lombok.Data; /** * 导出文档中的一个学习任务段落(导出-01)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/LoginResult.java b/src/main/java/com/guo/learningprogresstracker/dto/LoginResult.java index 51f6e24..86fb301 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/LoginResult.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/LoginResult.java @@ -17,4 +17,7 @@ public class LoginResult { /** 该用户是否在 {@code lpt.ai-usage.admin-usernames} 白名单里 */ private boolean aiAdmin; + + /** Stable opaque account identity for user-isolated draft caches; never an AI prompt field. */ + private String accountId; } diff --git a/src/main/java/com/guo/learningprogresstracker/dto/MindMapFragmentPayload.java b/src/main/java/com/guo/learningprogresstracker/dto/MindMapFragmentPayload.java index d46b067..cdb046b 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/MindMapFragmentPayload.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/MindMapFragmentPayload.java @@ -6,5 +6,4 @@ package com.guo.learningprogresstracker.dto; *

碎片正文之外带一个可空的 {@code reportRef}:指向同源的报告上下文。 * LLM 据此知道哪些碎片来自带报告的那次会话,从而只从中提取与这些碎片相关的内容。

*/ -public record MindMapFragmentPayload(String content, String reportRef) { -} +public record MindMapFragmentPayload(String content, String reportRef) {} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/MindMapReportContext.java b/src/main/java/com/guo/learningprogresstracker/dto/MindMapReportContext.java index 9793713..9201e1d 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/MindMapReportContext.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/MindMapReportContext.java @@ -14,16 +14,14 @@ import io.swagger.v3.oas.annotations.media.Schema; * 用于告诉 LLM 哪份报告与哪批碎片同源;{@code taskName} 帮助它判断领域是否一致。

*/ public record MindMapReportContext( - @Schema(description = "报告所属会话编号,用于与碎片记录上下文关联") - String ref, + @Schema(description = "报告所属会话编号,用于与碎片记录上下文关联") String ref, + @Schema(description = "产生该报告的会话所属任务名(仅作判断领域的参考,报告可能来自旁支任务)") String taskName, - @Schema(description = "会话摘要:这次实际学了什么") - String sessionSummary, - @Schema(description = "预期达成判断:对照学习预期得出的结论") - String expectationVerdict, - @Schema(description = "自由总结:用户对本次学习的叙述") - String freeSummary) { + + @Schema(description = "会话摘要:这次实际学了什么") String sessionSummary, + @Schema(description = "预期达成判断:对照学习预期得出的结论") String expectationVerdict, + @Schema(description = "自由总结:用户对本次学习的叙述") String freeSummary) { /** 三段是否都为空白:全空的报告没有参考价值,不进入导图上下文 */ public boolean isBlank() { diff --git a/src/main/java/com/guo/learningprogresstracker/dto/RecallCompareOutcome.java b/src/main/java/com/guo/learningprogresstracker/dto/RecallCompareOutcome.java deleted file mode 100644 index 3911009..0000000 --- a/src/main/java/com/guo/learningprogresstracker/dto/RecallCompareOutcome.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.guo.learningprogresstracker.dto; - -/** - * 一次回忆对比的结果(AI-02)。 - * - *

对比在 AI 任务执行器里完成,因此不再把「标准导图实体」直接返回给提交接口; - * 这个结果写进 AI 任务的 {@code result_payload},由前端在轮询到成功后再取详情。

- * - * @param standardMapId 对比所用的标准导图 ID - * @param recallRecordId 本次生成的回忆记录 ID - * @param recallRatio 覆盖率(0-1) - * @param matchedCount 命中节点数 - * @param missedCount 遗漏节点数 - * @param extraCount 额外节点数 - */ -public record RecallCompareOutcome(Integer standardMapId, Integer recallRecordId, Double recallRatio, - Integer matchedCount, Integer missedCount, Integer extraCount) { - - /** 转成 AI 任务结果载荷 */ - public java.util.Map toPayload() { - java.util.Map payload = new java.util.LinkedHashMap<>(); - payload.put("standardMapId", standardMapId); - payload.put("recallRecordId", recallRecordId); - payload.put("recallRatio", recallRatio); - payload.put("matchedCount", matchedCount); - payload.put("missedCount", missedCount); - payload.put("extraCount", extraCount); - return payload; - } -} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/ReviewFeedItem.java b/src/main/java/com/guo/learningprogresstracker/dto/ReviewFeedItem.java index 1aa5c1f..417f6f6 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/ReviewFeedItem.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/ReviewFeedItem.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.time.LocalDateTime; +import lombok.Data; /** * 复习滚动 feed 条目 / 任务记录条目。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/ReviewSummary.java b/src/main/java/com/guo/learningprogresstracker/dto/ReviewSummary.java index 5164ae4..b3f723a 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/ReviewSummary.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/ReviewSummary.java @@ -14,10 +14,6 @@ import io.swagger.v3.oas.annotations.media.Schema; * 任务删除后残留的报告也不计入。

*/ public record ReviewSummary( - @Schema(description = "任务总数") - long taskTotal, - @Schema(description = "学习报告总数") - long reportTotal, - @Schema(description = "学习碎片总数") - long fragmentTotal) { -} + @Schema(description = "任务总数") long taskTotal, + @Schema(description = "学习报告总数") long reportTotal, + @Schema(description = "学习碎片总数") long fragmentTotal) {} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/ReviewTiming.java b/src/main/java/com/guo/learningprogresstracker/dto/ReviewTiming.java index e2af0d2..cc538ad 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/ReviewTiming.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/ReviewTiming.java @@ -11,5 +11,4 @@ import java.time.LocalDateTime; * @param lastInteractionAt 最近一次交互时刻 * @param durationSeconds 前端结算出的净耗时(秒) */ -public record ReviewTiming(LocalDateTime startedAt, LocalDateTime lastInteractionAt, Integer durationSeconds) { -} +public record ReviewTiming(LocalDateTime startedAt, LocalDateTime lastInteractionAt, Integer durationSeconds) {} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/StudyReportDetail.java b/src/main/java/com/guo/learningprogresstracker/dto/StudyReportDetail.java index 75f43e5..4b8b2c3 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/StudyReportDetail.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/StudyReportDetail.java @@ -3,10 +3,9 @@ package com.guo.learningprogresstracker.dto; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - import java.util.ArrayList; import java.util.List; +import lombok.Data; /** * 学习报告详情(归属-01:结构化报告)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/StudySessionsDto.java b/src/main/java/com/guo/learningprogresstracker/dto/StudySessionsDto.java index 3acc2c1..f3b73df 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/StudySessionsDto.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/StudySessionsDto.java @@ -1,8 +1,7 @@ package com.guo.learningprogresstracker.dto; -import lombok.Data; - import java.time.LocalDateTime; +import lombok.Data; @Data public class StudySessionsDto { diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapSummary.java b/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapSummary.java index e941e9a..9b4fa6c 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapSummary.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapSummary.java @@ -1,10 +1,9 @@ package com.guo.learningprogresstracker.dto; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - import java.time.LocalDateTime; import java.util.List; +import lombok.Data; /** * 已有标签导图的摘要(闭环-04):用于「已生成的标签导图」列表。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java b/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java index 80ba372..8fca1c6 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/TagMindMapView.java @@ -1,11 +1,9 @@ package com.guo.learningprogresstracker.dto; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - import java.util.List; +import lombok.Data; /** * 一个标签复习范围的当前状态(闭环-04)。 @@ -28,7 +26,4 @@ public class TagMindMapView { @Schema(description = "该范围已有的标签导图;没有时为 null") private ReviewTagMindMapEntity map; - - @Schema(description = "该范围最近一次回忆对比记录;没复习过时为 null") - private ReviewRecallRecordEntity latestRecallRecord; } diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java b/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java index ad6dc1e..f93f0d0 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/TagScope.java @@ -1,7 +1,6 @@ package com.guo.learningprogresstracker.dto; import com.guo.learningprogresstracker.enums.TagCombineModeEnum; - import java.util.List; /** diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TaskDeletionSummary.java b/src/main/java/com/guo/learningprogresstracker/dto/TaskDeletionSummary.java index 1e9ef74..02251b8 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/TaskDeletionSummary.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/TaskDeletionSummary.java @@ -24,9 +24,6 @@ public class TaskDeletionSummary { @Schema(description = "将软删除的标准思维导图数") private int deletedMindMaps; - @Schema(description = "将软删除的回忆记录数") - private int deletedRecallRecords; - @Schema(description = "将软删除的应用场景数") private int deletedApplications; } diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TaskOption.java b/src/main/java/com/guo/learningprogresstracker/dto/TaskOption.java index e2439f3..8eab19e 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/TaskOption.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/TaskOption.java @@ -12,8 +12,5 @@ import io.swagger.v3.oas.annotations.media.Schema; *

排序与任务列表一致(优先级倒序),保证下拉里的顺序稳定。

*/ public record TaskOption( - @Schema(description = "任务编号") - String taskNum, - @Schema(description = "任务名称") - String taskName) { -} + @Schema(description = "任务编号") String taskNum, + @Schema(description = "任务名称") String taskName) {} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TaskRecallRatio.java b/src/main/java/com/guo/learningprogresstracker/dto/TaskRecallRatio.java deleted file mode 100644 index 3e36d05..0000000 --- a/src/main/java/com/guo/learningprogresstracker/dto/TaskRecallRatio.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.guo.learningprogresstracker.dto; - -import lombok.Data; - -/** - * 任务最近一次回忆对比的覆盖率(复习-04)。 - * - *

原先按任务取「最近一条回忆记录」是把该任务的全部回忆记录(含体积较大的 - * {@code compare_result} JSON)拉回内存再逐条取第一条。改为在 SQL 侧按任务分组取最新, - * 返回行数等于任务数,不随复习次数增长。

- */ -@Data -public class TaskRecallRatio { - - private String taskNum; - - /** 最近一次回忆对比的覆盖率(0-1);记录里为空时按 0 处理 */ - private Double recallRatio; -} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TaskReviewDuration.java b/src/main/java/com/guo/learningprogresstracker/dto/TaskReviewDuration.java deleted file mode 100644 index 74c6c14..0000000 --- a/src/main/java/com/guo/learningprogresstracker/dto/TaskReviewDuration.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.guo.learningprogresstracker.dto; - -import lombok.Data; - -/** - * 任务维度的复习耗时聚合结果(复习-07)。 - *

由 Mapper 层的聚合查询直接映射,避免用 Map 承载查询结果。

- */ -@Data -public class TaskReviewDuration { - - private String taskNum; - - /** 该任务累计复习耗时(秒) */ - private Long reviewDurationSeconds; -} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java b/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java new file mode 100644 index 0000000..ce9c522 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/recall/RecallDtos.java @@ -0,0 +1,197 @@ +package com.guo.learningprogresstracker.dto.recall; + +import java.time.Instant; +import java.util.List; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** Free recall stores one current expression and one current reference set per recall. */ +public final class RecallDtos { + private RecallDtos() {} + + public record ScopeInput(String type, String taskNum, List tags, String combineMode) {} + + public record ScopeSnapshot( + String type, + String taskNum, + List tags, + List normalizedTags, + String combineMode, + String scopeKey, + String displayName, + Instant selectedAt) {} + + public record Provenance(String kind, String recallNum, String requestTaskNum, String itemId) {} + + public record NodeStyle(String background, String color) {} + + public record ExpressionNode( + String id, + String title, + String notes, + List provenance, + NodeStyle style, + List children) {} + + public record Expression(int schemaVersion, ExpressionNode root) {} + + public record Timing(long segmentActiveMs, Long segmentActualMs, Instant lastInteractionAt) { + /** 兼容尚未上报实际用时的调用方:实际按有效时间处理。 */ + public Timing(long segmentActiveMs, Instant lastInteractionAt) { + this(segmentActiveMs, segmentActiveMs, lastInteractionAt); + } + } + + public record Entry(String type, String sourceType, String entityId) {} + + public record CreateRecallRequest(String clientRequestId, String editorId, ScopeInput scope, Entry entry) {} + + public record EditorGuard(String editorId, String writeToken) {} + + public record ResumeRequest(String clientRequestId, String editorId, String writeToken) {} + + public record SaveDraftRequest( + String clientRequestId, String editorId, String writeToken, Expression expression, Timing timing) {} + + public record EndRequest( + String clientRequestId, String editorId, String writeToken, Expression expression, Timing timing) {} + + public record AiParams(int schemaVersion, String requestId, String editorId, String writeToken, String hintForm) {} + + public record ReferenceSource( + String sourceId, + String type, + String entityId, + String title, + String content, + String role, + String contextType, + String contextNum, + List relatedFragmentSourceIds, + String status) {} + + public record ReferenceSourceSummary(String sourceId, String title, String preview, String role, String status) {} + + public record ReferencePage(int current, int size, long total, List records) {} + + public record ReferenceContent(String sourceId, String title, String content, String role, String status) {} + + public record ReferenceSummary(String status, long total, List limitations) {} + + public record ReferenceUnit( + String unitId, String sourceId, int start, int end, String text, String role, String status) {} + /** One source set captured when this recall starts; it is replaced only by starting a new recall. */ + public record ReferenceSnapshot( + String status, List sources, List units, List limitations) {} + + public record Citation(String unitId, int start, int end, String quote) {} + + public record ExpressionEvidence(String nodeId, String field, int start, int end, String quote) {} + + public record UnitAssessment( + String unitId, String status, String reason, String exclusion, List citations) {} + + public record HintNode(String id, String parentId, String text) {} + + public record HintItem( + String id, String form, String clue, String anchorNodeId, List nodes, List citations) {} + + public record Finding( + String id, + String category, + String clue, + String explanation, + List citations, + List expressionEvidence) {} + + public record RecallAiResult( + int schemaVersion, + String kind, + String model, + String analysisStatus, + List assessments, + List hints, + List findings, + List limitations) {} + + public record AiReferenceUnit( + String unitId, + String sourceId, + String sourceType, + String role, + String title, + int start, + int end, + String text, + List relatedFragmentSourceIds) {} + + public record AiScope(String type, String displayName, List tags, String combineMode) {} + + public record Limits(int maxHintItems, int maxHintNodes, int maxFindings) {} + /** AI input expression: presentation-only style is not part of the semantic contract. */ + public record AiExpressionNode( + String id, String title, String notes, List provenance, List children) {} + + public record AiExpression(int schemaVersion, AiExpressionNode root) {} + + public record RecallAiParams( + int schemaVersion, + String promptVersion, + AiScope scope, + AiExpression expression, + String hintForm, + List units, + Limits limits, + List limitations) {} + + public record RecallRequest( + String requestId, + String taskNum, + String type, + String hintForm, + String promptVersion, + String status, + String errorCode, + String errorMessage, + Instant submittedAt, + Instant finishedAt, + RecallAiResult result) {} + + public record RecallPage(long current, long size, long total, List records) {} + + public record BusinessError(String reason) {} + + @Data + public static class RecallSummary { + private String recallNum; + private String status; + private ScopeSnapshot scope; + private String scopeStatus; + private long activeDurationMs; + private Long actualDurationMs; + private Instant createdAt; + private Instant updatedAt; + private Instant endedAt; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class RecallDetail extends RecallSummary { + private String editorId; + private String writeToken; + private Expression expression; + private ReferenceSummary reference; + private List requests; + } + /** Persisted aggregate under a database lock, never returned to the client. */ + @Data + public static class RecallDocument { + private RecallDetail detail; + private ReferenceSnapshot reference; + private Instant epochStartedAt; + private long acceptedSegmentMs; + private Long acceptedSegmentActualMs; + private String lastDraftRequestId; + private String lastDraftPayloadHash; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/recall/TaskRecallDuration.java b/src/main/java/com/guo/learningprogresstracker/dto/recall/TaskRecallDuration.java new file mode 100644 index 0000000..143728f --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/recall/TaskRecallDuration.java @@ -0,0 +1,9 @@ +package com.guo.learningprogresstracker.dto.recall; + +import lombok.Data; + +@Data +public class TaskRecallDuration { + private String taskNum; + private Long activeDurationMs; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AddUserTagRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AddUserTagRequest.java new file mode 100644 index 0000000..b8d248a --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AddUserTagRequest.java @@ -0,0 +1,18 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 给对象打用户标签的请求。 */ +@Data +public class AddUserTagRequest { + + @NotBlank(message = "对象类型不能为空") + private String objectType; + + @NotBlank(message = "对象编号不能为空") + private String objectNum; + + @NotBlank(message = "标签名不能为空") + private String markerName; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AiTaskSubmitRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AiTaskSubmitRequest.java index 50ffb5a..594658a 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/AiTaskSubmitRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AiTaskSubmitRequest.java @@ -1,9 +1,8 @@ package com.guo.learningprogresstracker.dto.request; import jakarta.validation.constraints.NotBlank; -import lombok.Data; - import java.util.Map; +import lombok.Data; /** * 提交 AI 任务请求(AI-02)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java index fc2564a..631f9df 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageRecordRequest.java @@ -3,9 +3,8 @@ package com.guo.learningprogresstracker.dto.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; -import lombok.Data; - import java.math.BigDecimal; +import lombok.Data; /** * 一条 AI 用量记录(契约 1)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageReportRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageReportRequest.java index 5a9ac27..b111ec6 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageReportRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AiUsageReportRequest.java @@ -2,9 +2,8 @@ package com.guo.learningprogresstracker.dto.request; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; -import lombok.Data; - import java.util.List; +import lombok.Data; /** * lpt-ai 用量上报请求体(契约 1,{@code POST /internal/ai-usage/records})。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/AssignOwnershipRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/AssignOwnershipRequest.java new file mode 100644 index 0000000..afd7680 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/AssignOwnershipRequest.java @@ -0,0 +1,10 @@ +package com.guo.learningprogresstracker.dto.request; + +import lombok.Data; + +/** 调整知识碎片内容归属;ownerTaskNum 传空字符串表示清空归属(回到待归类)。 */ +@Data +public class AssignOwnershipRequest { + + private String ownerTaskNum; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/ConfirmGuidanceFragmentRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/ConfirmGuidanceFragmentRequest.java new file mode 100644 index 0000000..fffb87b --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/ConfirmGuidanceFragmentRequest.java @@ -0,0 +1,13 @@ +package com.guo.learningprogresstracker.dto.request; + +import lombok.Data; + +/** 确认引导产出、记成知识碎片的请求。 */ +@Data +public class ConfirmGuidanceFragmentRequest { + + private String content; + private String reviewStartedAt; + private String reviewLastInteractionAt; + private Integer reviewDurationSeconds; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/CreateDictionaryTagRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/CreateDictionaryTagRequest.java new file mode 100644 index 0000000..d4f189b --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/CreateDictionaryTagRequest.java @@ -0,0 +1,12 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 新建标签字典项的请求。 */ +@Data +public class CreateDictionaryTagRequest { + + @NotBlank(message = "标签名不能为空") + private String tagName; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/FindNodeRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/FindNodeRequest.java new file mode 100644 index 0000000..11e08a5 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/FindNodeRequest.java @@ -0,0 +1,10 @@ +package com.guo.learningprogresstracker.dto.request; + +import lombok.Data; + +/** 在标准思维导图里查找最接近的节点。 */ +@Data +public class FindNodeRequest { + + private String content; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/GuidanceStartRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/GuidanceStartRequest.java new file mode 100644 index 0000000..2d71bb0 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/GuidanceStartRequest.java @@ -0,0 +1,15 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 开始一次学习引导的请求。 */ +@Data +public class GuidanceStartRequest { + + @NotBlank(message = "任务编号不能为空") + private String taskNum; + + @NotBlank(message = "概念不能为空") + private String concept; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/GuidanceTurnRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/GuidanceTurnRequest.java new file mode 100644 index 0000000..8cc5fc9 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/GuidanceTurnRequest.java @@ -0,0 +1,12 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 提交一轮用户发言的请求。 */ +@Data +public class GuidanceTurnRequest { + + @NotBlank(message = "发言内容不能为空") + private String message; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/PriorityWeightsRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/PriorityWeightsRequest.java new file mode 100644 index 0000000..a330cdd --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/PriorityWeightsRequest.java @@ -0,0 +1,25 @@ +package com.guo.learningprogresstracker.dto.request; + +import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity; +import lombok.Data; + +/** 优先级权重保存请求。 */ +@Data +public class PriorityWeightsRequest { + + private Double urgencyWeight; + private Double importanceWeight; + private Double contentDifficultyWeight; + private Double futureValueWeight; + private Double subjectivePriorityWeight; + + public UserPriorityWeightsEntity toEntity() { + UserPriorityWeightsEntity entity = new UserPriorityWeightsEntity(); + entity.setUrgencyWeight(urgencyWeight); + entity.setImportanceWeight(importanceWeight); + entity.setContentDifficultyWeight(contentDifficultyWeight); + entity.setFutureValueWeight(futureValueWeight); + entity.setSubjectivePriorityWeight(subjectivePriorityWeight); + return entity; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/RecallCompareRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/RecallCompareRequest.java deleted file mode 100644 index 5986323..0000000 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/RecallCompareRequest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.guo.learningprogresstracker.dto.request; - -import com.fasterxml.jackson.annotation.JsonFormat; -import jakarta.validation.constraints.NotBlank; -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 用户回忆对比请求 - */ -@Data -public class RecallCompareRequest { - - @NotBlank(message = "请先填写回忆大纲") - private String recallOutline; - - /** 复习起点节点路径(以 / 分隔),null 为任务维度 */ - private String focusPath; - - /** 本次回忆复习开始时刻(本地时间),复习-07 */ - @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") - private LocalDateTime reviewStartedAt; - - /** 最近一次交互时刻(本地时间),供服务端按 5 分钟空闲截断,复习-07 */ - @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") - private LocalDateTime reviewLastInteractionAt; - - /** 前端按 5 分钟空闲截断后的净耗时(秒),复习-07 */ - private Integer reviewDurationSeconds; -} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/RenameDictionaryTagRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/RenameDictionaryTagRequest.java new file mode 100644 index 0000000..b3ae365 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/RenameDictionaryTagRequest.java @@ -0,0 +1,12 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 重命名标签字典项的请求。 */ +@Data +public class RenameDictionaryTagRequest { + + @NotBlank(message = "标签名不能为空") + private String newName; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/RenameUserTagRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/RenameUserTagRequest.java new file mode 100644 index 0000000..f01b385 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/RenameUserTagRequest.java @@ -0,0 +1,15 @@ +package com.guo.learningprogresstracker.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 重命名用户标签的请求(影响所有带该标签的对象)。 */ +@Data +public class RenameUserTagRequest { + + @NotBlank(message = "原标签名不能为空") + private String oldName; + + @NotBlank(message = "新标签名不能为空") + private String newName; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/SortPreferenceRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/SortPreferenceRequest.java new file mode 100644 index 0000000..5e4cbb7 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/SortPreferenceRequest.java @@ -0,0 +1,10 @@ +package com.guo.learningprogresstracker.dto.request; + +import lombok.Data; + +/** 保存复习排序偏好的请求(preset 取值见 ReviewSortPresetEnum,非法值回落默认档)。 */ +@Data +public class SortPreferenceRequest { + + private String preset; +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java index 8300b27..a3c0969 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/TagScopeRequest.java @@ -1,9 +1,8 @@ package com.guo.learningprogresstracker.dto.request; import jakarta.validation.constraints.NotEmpty; -import lombok.Data; - import java.util.List; +import lombok.Data; /** * 标签复习范围(闭环-04):标签集合 + 取数模式。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/TaskRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/TaskRequest.java index 2ae83f1..1e5ca95 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/TaskRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/TaskRequest.java @@ -14,9 +14,10 @@ import lombok.Data; @Data public class TaskRequest { - public interface Create{} - @Null(message = "创建任务时不需要填写任务编号",groups = Ops.CreateG.class) - @NotNull(message = "缺少要更新的任务信息,请刷新后重试",groups = Ops.UpdateG.class) + public interface Create {} + + @Null(message = "创建任务时不需要填写任务编号", groups = Ops.CreateG.class) + @NotNull(message = "缺少要更新的任务信息,请刷新后重试", groups = Ops.UpdateG.class) private Integer id; /** * 学习任务的名称 @@ -36,40 +37,39 @@ public class TaskRequest { * 用户设置的任务紧急性 */ @NotNull(message = "请设置任务紧急性", groups = Ops.CreateG.class) - @Min(value = 0,message = "任务紧急性不能小于 0") - @Max(value = 5,message = "任务紧急性不能大于 5") + @Min(value = 0, message = "任务紧急性不能小于 0") + @Max(value = 5, message = "任务紧急性不能大于 5") private Integer urgency; /** * 用户设置的任务重要性 */ @NotNull(message = "请设置任务重要性", groups = Ops.CreateG.class) - @Min(value = 0,message = "任务重要性不能小于 0") - @Max(value = 5,message = "任务重要性不能大于 5") + @Min(value = 0, message = "任务重要性不能小于 0") + @Max(value = 5, message = "任务重要性不能大于 5") private Integer importance; /** * 任务的内容难度 */ @NotNull(message = "请设置内容难度", groups = Ops.CreateG.class) - @Min(value = 0,message = "内容难度不能小于 0") - @Max(value = 5,message = "内容难度不能大于 5") + @Min(value = 0, message = "内容难度不能小于 0") + @Max(value = 5, message = "内容难度不能大于 5") private Integer contentDifficulty; /** * 任务的未来价值 */ @NotNull(message = "请设置未来价值", groups = Ops.CreateG.class) - @Min(value = 0,message = "未来价值不能小于 0") - @Max(value = 5,message = "未来价值不能大于 5") + @Min(value = 0, message = "未来价值不能小于 0") + @Max(value = 5, message = "未来价值不能大于 5") private Integer futureValue; /** * 用户对任务的主观优先级 */ @NotNull(message = "请设置主观优先级", groups = Ops.CreateG.class) - @Min(value = 0,message = "主观优先级不能小于 0") - @Max(value = 5,message = "主观优先级不能大于 5") + @Min(value = 0, message = "主观优先级不能小于 0") + @Max(value = 5, message = "主观优先级不能大于 5") private Integer subjectivePriority; - } diff --git a/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java b/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java index 77149f0..d8b27c3 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/request/UpdateTagMindMapRequest.java @@ -2,9 +2,8 @@ package com.guo.learningprogresstracker.dto.request; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; -import lombok.Data; - import java.util.List; +import lombok.Data; /** * 用户编辑标签导图(大纲文本形式)请求(闭环-04)。 diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/GuidanceConversationResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/GuidanceConversationResponse.java new file mode 100644 index 0000000..82bdf27 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/GuidanceConversationResponse.java @@ -0,0 +1,41 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.ReviewGuidanceConversationEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 学习引导会话(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class GuidanceConversationResponse { + + private Integer id; + private String guidanceNum; + private String taskNum; + private String concept; + private String turnsPayload; + private Integer reviewDurationSeconds; + private Boolean finished; + private LocalDateTime startedTime; + private LocalDateTime finishedTime; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static GuidanceConversationResponse of(ReviewGuidanceConversationEntity entity) { + if (entity == null) { + return null; + } + GuidanceConversationResponse response = new GuidanceConversationResponse(); + response.setId(entity.getId()); + response.setGuidanceNum(entity.getGuidanceNum()); + response.setTaskNum(entity.getTaskNum()); + response.setConcept(entity.getConcept()); + response.setTurnsPayload(entity.getTurnsPayload()); + response.setReviewDurationSeconds(entity.getReviewDurationSeconds()); + response.setFinished(entity.getFinished()); + response.setStartedTime(entity.getStartedTime()); + response.setFinishedTime(entity.getFinishedTime()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/MarkerResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/MarkerResponse.java new file mode 100644 index 0000000..49cee46 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/MarkerResponse.java @@ -0,0 +1,35 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.MarkerEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 对象上的标记(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class MarkerResponse { + + private Integer id; + private String objectType; + private String objectNum; + private String kind; + private String markerName; + private String markerValue; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static MarkerResponse of(MarkerEntity entity) { + if (entity == null) { + return null; + } + MarkerResponse response = new MarkerResponse(); + response.setId(entity.getId()); + response.setObjectType(entity.getObjectType()); + response.setObjectNum(entity.getObjectNum()); + response.setKind(entity.getKind()); + response.setMarkerName(entity.getMarkerName()); + response.setMarkerValue(entity.getMarkerValue()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/PriorityWeightsResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/PriorityWeightsResponse.java new file mode 100644 index 0000000..0823bed --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/PriorityWeightsResponse.java @@ -0,0 +1,35 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 用户优先级权重(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class PriorityWeightsResponse { + + private Integer id; + private Double urgencyWeight; + private Double importanceWeight; + private Double contentDifficultyWeight; + private Double futureValueWeight; + private Double subjectivePriorityWeight; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static PriorityWeightsResponse of(UserPriorityWeightsEntity entity) { + if (entity == null) { + return null; + } + PriorityWeightsResponse response = new PriorityWeightsResponse(); + response.setId(entity.getId()); + response.setUrgencyWeight(entity.getUrgencyWeight()); + response.setImportanceWeight(entity.getImportanceWeight()); + response.setContentDifficultyWeight(entity.getContentDifficultyWeight()); + response.setFutureValueWeight(entity.getFutureValueWeight()); + response.setSubjectivePriorityWeight(entity.getSubjectivePriorityWeight()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/ReportFragmentResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/ReportFragmentResponse.java new file mode 100644 index 0000000..a3dbe07 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/ReportFragmentResponse.java @@ -0,0 +1,39 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 知识碎片(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class ReportFragmentResponse { + + private Integer id; + private String contextNum; + private String contextType; + private String ownerTaskNum; + private Boolean mastered; + private Boolean revisit; + private LocalDateTime lastReviewedTime; + private String content; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static ReportFragmentResponse of(StudyReportFragmentsEntity entity) { + if (entity == null) { + return null; + } + ReportFragmentResponse response = new ReportFragmentResponse(); + response.setId(entity.getId()); + response.setContextNum(entity.getContextNum()); + response.setContextType(entity.getContextType()); + response.setOwnerTaskNum(entity.getOwnerTaskNum()); + response.setMastered(entity.getMastered()); + response.setRevisit(entity.getRevisit()); + response.setLastReviewedTime(entity.getLastReviewedTime()); + response.setContent(entity.getContent()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/StandardMindMapResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/StandardMindMapResponse.java new file mode 100644 index 0000000..fbdea65 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/StandardMindMapResponse.java @@ -0,0 +1,49 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 标准思维导图(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class StandardMindMapResponse { + + private Integer id; + private String taskNum; + private String title; + private String content; + private String outline; + private String summary; + private String generator; + private String generatorVersion; + private Integer sourceReportCount; + private Integer sourceFragmentCount; + private LocalDateTime generatedTime; + private Boolean needsUpdate; + private LocalDateTime needsUpdateTime; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static StandardMindMapResponse of(ReviewStandardMindMapEntity entity) { + if (entity == null) { + return null; + } + StandardMindMapResponse response = new StandardMindMapResponse(); + response.setId(entity.getId()); + response.setTaskNum(entity.getTaskNum()); + response.setTitle(entity.getTitle()); + response.setContent(entity.getContent()); + response.setOutline(entity.getOutline()); + response.setSummary(entity.getSummary()); + response.setGenerator(entity.getGenerator()); + response.setGeneratorVersion(entity.getGeneratorVersion()); + response.setSourceReportCount(entity.getSourceReportCount()); + response.setSourceFragmentCount(entity.getSourceFragmentCount()); + response.setGeneratedTime(entity.getGeneratedTime()); + response.setNeedsUpdate(entity.getNeedsUpdate()); + response.setNeedsUpdateTime(entity.getNeedsUpdateTime()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/StudyExpectationResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/StudyExpectationResponse.java new file mode 100644 index 0000000..e410990 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/StudyExpectationResponse.java @@ -0,0 +1,29 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.StudyExpectationsEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 会话学习预期(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class StudyExpectationResponse { + + private Integer expectationId; + private String sessionNum; + private String description; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static StudyExpectationResponse of(StudyExpectationsEntity entity) { + if (entity == null) { + return null; + } + StudyExpectationResponse response = new StudyExpectationResponse(); + response.setExpectationId(entity.getExpectationId()); + response.setSessionNum(entity.getSessionNum()); + response.setDescription(entity.getDescription()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/StudyReportResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/StudyReportResponse.java new file mode 100644 index 0000000..fa0889f --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/StudyReportResponse.java @@ -0,0 +1,35 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.StudyReportsEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 学习报告(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class StudyReportResponse { + + private Integer id; + private String sessionNum; + private String sessionSummary; + private String expectationVerdict; + private String freeSummary; + private String sessionExpectation; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static StudyReportResponse of(StudyReportsEntity entity) { + if (entity == null) { + return null; + } + StudyReportResponse response = new StudyReportResponse(); + response.setId(entity.getId()); + response.setSessionNum(entity.getSessionNum()); + response.setSessionSummary(entity.getSessionSummary()); + response.setExpectationVerdict(entity.getExpectationVerdict()); + response.setFreeSummary(entity.getFreeSummary()); + response.setSessionExpectation(entity.getSessionExpectation()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/StudySessionResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/StudySessionResponse.java index c7e8050..562a418 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/response/StudySessionResponse.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/StudySessionResponse.java @@ -1,9 +1,8 @@ package com.guo.learningprogresstracker.dto.response; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - import java.time.LocalDateTime; +import lombok.Data; @Data public class StudySessionResponse { @@ -29,23 +28,18 @@ public class StudySessionResponse { @Schema(description = "上次本会话开始时间") private LocalDateTime lastStartTime; - @Schema(description = "学习结束时间") private LocalDateTime endTime; - @Schema(description = "实际使用时间(秒)") private double actualTime; - @Schema(description = "有效学习时间(秒)") private double effectiveTime; - @Schema(description = "有效时间比") private Double effectivenessRatio; - @Schema(description = "学习会话的状态(进行中、暂停、已结束)") private String sessionState; diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/TagMindMapResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/TagMindMapResponse.java new file mode 100644 index 0000000..74cd134 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/TagMindMapResponse.java @@ -0,0 +1,51 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 标签思维导图(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class TagMindMapResponse { + + private Integer id; + private String scopeKey; + private String combineMode; + private String tagNames; + private String title; + private String content; + private String outline; + private String summary; + private String generator; + private String generatorVersion; + private Integer sourceFragmentCount; + private LocalDateTime generatedTime; + private Boolean needsUpdate; + private LocalDateTime needsUpdateTime; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static TagMindMapResponse of(ReviewTagMindMapEntity entity) { + if (entity == null) { + return null; + } + TagMindMapResponse response = new TagMindMapResponse(); + response.setId(entity.getId()); + response.setScopeKey(entity.getScopeKey()); + response.setCombineMode(entity.getCombineMode()); + response.setTagNames(entity.getTagNames()); + response.setTitle(entity.getTitle()); + response.setContent(entity.getContent()); + response.setOutline(entity.getOutline()); + response.setSummary(entity.getSummary()); + response.setGenerator(entity.getGenerator()); + response.setGeneratorVersion(entity.getGeneratorVersion()); + response.setSourceFragmentCount(entity.getSourceFragmentCount()); + response.setGeneratedTime(entity.getGeneratedTime()); + response.setNeedsUpdate(entity.getNeedsUpdate()); + response.setNeedsUpdateTime(entity.getNeedsUpdateTime()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/TaskApplicationResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/TaskApplicationResponse.java new file mode 100644 index 0000000..f7b0837 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/TaskApplicationResponse.java @@ -0,0 +1,35 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.TaskApplicationEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 任务应用场景(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class TaskApplicationResponse { + + private Integer id; + private String taskNum; + private String title; + private String description; + private String resourceUrl; + private String status; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static TaskApplicationResponse of(TaskApplicationEntity entity) { + if (entity == null) { + return null; + } + TaskApplicationResponse response = new TaskApplicationResponse(); + response.setId(entity.getId()); + response.setTaskNum(entity.getTaskNum()); + response.setTitle(entity.getTitle()); + response.setDescription(entity.getDescription()); + response.setResourceUrl(entity.getResourceUrl()); + response.setStatus(entity.getStatus()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/TaskInfoResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/TaskInfoResponse.java index 0166550..f522ffb 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/response/TaskInfoResponse.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/TaskInfoResponse.java @@ -22,7 +22,7 @@ public class TaskInfoResponse { private String materialUrl; /** - /** + * /** * 用户设置的任务紧急性 */ private Integer urgency; diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/TasksListInfoResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/TasksListInfoResponse.java index d872c93..3e3dbda 100644 --- a/src/main/java/com/guo/learningprogresstracker/dto/response/TasksListInfoResponse.java +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/TasksListInfoResponse.java @@ -1,9 +1,8 @@ package com.guo.learningprogresstracker.dto.response; import com.guo.learningprogresstracker.dto.TaskInfo; -import lombok.Data; - import java.util.List; +import lombok.Data; /** * 任务列表信息响应体 @@ -12,6 +11,4 @@ import java.util.List; public class TasksListInfoResponse { // 任务列表 private List taskList; - - } diff --git a/src/main/java/com/guo/learningprogresstracker/dto/response/UserTagResponse.java b/src/main/java/com/guo/learningprogresstracker/dto/response/UserTagResponse.java new file mode 100644 index 0000000..edcad58 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/dto/response/UserTagResponse.java @@ -0,0 +1,29 @@ +package com.guo.learningprogresstracker.dto.response; + +import com.guo.learningprogresstracker.entity.UserTagEntity; +import java.time.LocalDateTime; +import lombok.Data; + +/** 用户标签字典项(HTTP 出参;不暴露实体上的租户与审计列)。 */ +@Data +public class UserTagResponse { + + private Integer id; + private String tagName; + private String normalizedName; + private LocalDateTime createdTime; + private LocalDateTime lastModifiedTime; + + public static UserTagResponse of(UserTagEntity entity) { + if (entity == null) { + return null; + } + UserTagResponse response = new UserTagResponse(); + response.setId(entity.getId()); + response.setTagName(entity.getTagName()); + response.setNormalizedName(entity.getNormalizedName()); + response.setCreatedTime(entity.getCreatedTime()); + response.setLastModifiedTime(entity.getLastModifiedTime()); + return response; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/AiTaskEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/AiTaskEntity.java index db702c3..eb43107 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/AiTaskEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/AiTaskEntity.java @@ -6,10 +6,9 @@ import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.guo.learningprogresstracker.enums.AiTaskStatusEnum; import com.guo.learningprogresstracker.utils.GenerateNumTool; -import lombok.Data; - import java.io.Serializable; import java.time.LocalDateTime; +import lombok.Data; /** * AI 异步任务(AI-02):提交后立即返回任务标识,结果由执行器回写、按标识重复获取。 @@ -49,6 +48,9 @@ public class AiTaskEntity extends BaseEntity implements Serializable { @TableField(value = "error_message") private String errorMessage; + @TableField(value = "error_code") + private String errorCode; + @TableField(value = "started_time") private LocalDateTime startedTime; diff --git a/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java index a1c2464..aa205f8 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/AiUsageRecordEntity.java @@ -4,11 +4,10 @@ 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.math.BigDecimal; import java.time.LocalDateTime; +import lombok.Data; /** * AI 用量记录:lpt-ai 每完成一次 AI 任务后上报一条,供「AI 用量统计」面板聚合。 @@ -34,7 +33,7 @@ public class AiUsageRecordEntity extends BaseEntity implements Serializable { @TableField(value = "occurred_at") private LocalDateTime occurredAt; - /** 任务类型:aggregate-report/generate-mind-map/compare-recall/guidance/fetch-title */ + /** 任务类型:aggregate-report/generate-mind-map/recall-hint/recall-check/guidance/fetch-title */ @TableField(value = "task_type") private String taskType; diff --git a/src/main/java/com/guo/learningprogresstracker/entity/BaseEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/BaseEntity.java index a8c0b2e..8832760 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/BaseEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/BaseEntity.java @@ -3,9 +3,8 @@ package com.guo.learningprogresstracker.entity; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableLogic; -import lombok.Data; - import java.time.LocalDateTime; +import lombok.Data; /** * @author guo diff --git a/src/main/java/com/guo/learningprogresstracker/entity/MarkerEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/MarkerEntity.java index 5754060..8ef08a1 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/MarkerEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/MarkerEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; /** * 统一标记(标记-01):附加在对象上的一段轻量元信息。 @@ -45,6 +44,8 @@ public class MarkerEntity extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; public boolean isSystemMarker() { - return com.guo.learningprogresstracker.enums.MarkerKindEnum.SYSTEM.name().equals(kind); + return com.guo.learningprogresstracker.enums.MarkerKindEnum.SYSTEM + .name() + .equals(kind); } } diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewGuidanceConversationEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewGuidanceConversationEntity.java index 09a0529..f110279 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/ReviewGuidanceConversationEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewGuidanceConversationEntity.java @@ -5,10 +5,9 @@ import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.guo.learningprogresstracker.utils.GenerateNumTool; -import lombok.Data; - import java.io.Serializable; import java.time.LocalDateTime; +import lombok.Data; /** * 学习引导会话(复习-06):一次复习行为。 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java new file mode 100644 index 0000000..9d350ea --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallEntity.java @@ -0,0 +1,21 @@ +package com.guo.learningprogresstracker.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("review_recalls") +public class ReviewRecallEntity extends BaseEntity { + @TableId(type = IdType.AUTO) + private Long id; + + private String recallNum; + private String scopeType; + private String taskNum; + private String scopeKey; + private String status; + private Long activeDurationMs; + private String documentJson; +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallReceiptEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallReceiptEntity.java new file mode 100644 index 0000000..67cbf33 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallReceiptEntity.java @@ -0,0 +1,18 @@ +package com.guo.learningprogresstracker.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("review_recall_receipts") +public class ReviewRecallReceiptEntity extends BaseEntity { + @TableId(type = IdType.AUTO) + private Long id; + + private String receiptKey; + private String payloadHash; + private String recallNum; + private String taskNum; +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallRecordEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallRecordEntity.java deleted file mode 100644 index aa94278..0000000 --- a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallRecordEntity.java +++ /dev/null @@ -1,86 +0,0 @@ -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; - -/** - * 复习回忆与标准导图的对比记录 - */ -@TableName(value = "review_recall_records") -@Data -public class ReviewRecallRecordEntity extends BaseEntity implements Serializable { - - @TableId(value = "id", type = IdType.AUTO) - private Integer id; - - /** 任务编码;标签范围复习时为空,取值口径见 {@code scopeType} */ - @TableField(value = "task_num") - private String taskNum; - - /** 复习范围:TASK=任务导图 / TAG=标签导图,取值见 {@code ReviewScopeTypeEnum} */ - @TableField(value = "scope_type") - private String scopeType; - - /** 标签范围的规范键(与标签导图同源);任务范围为空 */ - @TableField(value = "scope_key") - private String scopeKey; - - /** 范围的标签集合(JSON 数组,按归一化名排序);任务范围为空 */ - @TableField(value = "scope_tags") - private String scopeTags; - - /** 标签范围的取数模式:UNION / INTERSECT;任务范围为空 */ - @TableField(value = "scope_mode") - private String scopeMode; - - /** 对比时使用的基准导图 ID:任务范围指向任务导图,标签范围指向标签导图 */ - @TableField(value = "standard_map_id") - private Integer standardMapId; - - /** - * 复习起点节点路径(以 / 分隔),null 表示整棵树 - */ - @TableField(value = "focus_path") - private String focusPath; - - /** - * 用户回忆绘制的导图大纲文本 - */ - @TableField(value = "recall_content") - private String recallContent; - - /** - * 与标准导图的结构对比结果 JSON - */ - @TableField(value = "compare_result") - private String compareResult; - - /** - * 回忆覆盖率(0-1) - */ - @TableField(value = "recall_ratio") - private Double recallRatio; - - @TableField(value = "matched_count") - private Integer matchedCount; - - @TableField(value = "missed_count") - private Integer missedCount; - - @TableField(value = "extra_count") - private Integer extraCount; - - /** - * 本次复习耗时(秒),已按「超过 5 分钟无交互则截断」规则结算 - */ - @TableField(value = "review_duration_seconds") - private Integer reviewDurationSeconds; - - @TableField(exist = false) - private static final long serialVersionUID = 1L; -} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallRequestEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallRequestEntity.java new file mode 100644 index 0000000..38d6a85 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewRecallRequestEntity.java @@ -0,0 +1,19 @@ +package com.guo.learningprogresstracker.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("review_recall_requests") +public class ReviewRecallRequestEntity extends BaseEntity { + @TableId(type = IdType.AUTO) + private Long id; + + private String recallNum; + private String taskNum; + private String paramsJson; + private String remoteTaskId; + private Integer redacted; +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewStandardMindMapEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewStandardMindMapEntity.java index a13304f..ad62e64 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/ReviewStandardMindMapEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewStandardMindMapEntity.java @@ -4,10 +4,9 @@ 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; +import lombok.Data; /** * 任务标准思维导图:由内置规则或 AI 从学习报告生成,用户可修改 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java index 55a81fc..64a061a 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/ReviewTagMindMapEntity.java @@ -4,10 +4,9 @@ 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; +import lombok.Data; /** * 标签思维导图(闭环-04):以一个「标签集合 + 取数模式」为范围的导图,与任务导图并存。 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/StudyExpectationsEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/StudyExpectationsEntity.java index 7299575..0246ea6 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/StudyExpectationsEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/StudyExpectationsEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; /** * 存储每次学习开始前的预期 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/StudyReportFragmentsEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/StudyReportFragmentsEntity.java index 11d629a..974bd41 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/StudyReportFragmentsEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/StudyReportFragmentsEntity.java @@ -5,9 +5,8 @@ import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum; -import lombok.Data; - import java.io.Serializable; +import lombok.Data; /** * 记录学习过程中的学习内容报告残片(知识碎片)。 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/StudyReportsEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/StudyReportsEntity.java index c14bb13..2901525 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/StudyReportsEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/StudyReportsEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; /** * 存储每次学习结束时的完整学习报告。 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/StudySessionsEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/StudySessionsEntity.java index 898c503..4ad1de9 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/StudySessionsEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/StudySessionsEntity.java @@ -8,19 +8,18 @@ import com.google.protobuf.ServiceException; import com.guo.learningprogresstracker.common.StudyTimePolicy; import com.guo.learningprogresstracker.enums.StudySessionStateEnum; import com.guo.learningprogresstracker.utils.GenerateNumTool; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.springframework.util.ObjectUtils; - import java.io.Serializable; import java.time.Duration; import java.time.LocalDateTime; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.util.ObjectUtils; /** * 记录每次学习会话的具体数据 * @TableName study_sessions */ -@TableName(value ="study_sessions") +@TableName(value = "study_sessions") @Slf4j @Data public class StudySessionsEntity extends BaseEntity implements Serializable { @@ -83,7 +82,6 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { @TableField(value = "auto_converged") private Boolean autoConverged; - /** * 计时器指针位置,时间戳形式存储(毫秒) */ @@ -96,14 +94,14 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { /** * 初始化新会话(使用默认时间口径) */ - public static StudySessionsEntity initNewSession(){ + public static StudySessionsEntity initNewSession() { return initNewSession(StudyTimePolicy.DEFAULT); } /** * 初始化新会话 */ - public static StudySessionsEntity initNewSession(StudyTimePolicy policy){ + public static StudySessionsEntity initNewSession(StudyTimePolicy policy) { StudySessionsEntity studySessionsEntity = new StudySessionsEntity(); studySessionsEntity.setSessionNum(GenerateNumTool.generateNum("SESSION")); studySessionsEntity.setStartTime(LocalDateTime.now()); @@ -126,35 +124,36 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { * 继续会话 */ public void continueStudySession(StudyTimePolicy policy) throws ServiceException { - if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())){ + if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())) { this.setSessionState(StudySessionStateEnum.ONGOING.name()); this.setLastStartTime(LocalDateTime.now()); this.calculatePointerPosition(policy); } else if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) { - log.info("进行中的学习会话({})被重新开始",this.getSessionNum()); - } else{ - log.warn("不应出现的情况:开始了一个状态为【{}】的学习会话({})",this.getSessionState(),this.getSessionNum()); + log.info("进行中的学习会话({})被重新开始", this.getSessionNum()); + } else { + log.warn("不应出现的情况:开始了一个状态为【{}】的学习会话({})", this.getSessionState(), this.getSessionNum()); } } /** * 暂停会话(使用默认时间口径) */ - public void pausedStudySession(LocalDateTime endTime){ + public void pausedStudySession(LocalDateTime endTime) { pausedStudySession(endTime, StudyTimePolicy.DEFAULT); } /** * 暂停会话 */ - public void pausedStudySession(LocalDateTime endTime, StudyTimePolicy policy){ + public void pausedStudySession(LocalDateTime endTime, StudyTimePolicy policy) { if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())) { log.warn("不应出现的情况:暂停了一个状态为【{}】的学习会话({})", this.getSessionState(), this.getSessionNum()); } else { LocalDateTime settlementTime = this.resolveSettlementTime(endTime, policy); this.setEndTime(settlementTime); this.setActualTime(Duration.between(this.startTime, this.endTime).toSeconds()); - this.setEffectiveTime(this.getEffectiveTime() + Duration.between(this.lastStartTime, this.endTime).toSeconds()); + this.setEffectiveTime(this.getEffectiveTime() + + Duration.between(this.lastStartTime, this.endTime).toSeconds()); this.setEffectivenessRatio(this.effectiveTime / this.actualTime); this.setSessionState(StudySessionStateEnum.PAUSED.name()); } @@ -181,8 +180,11 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { } long minutes = Duration.between(this.lastStartTime, end).toMinutes(); if (minutes >= policy.getForgetThresholdMinutes()) { - log.info("会话[{}]本段学习已超过{}分钟无操作,按{}分钟结算", - this.getSessionNum(), policy.getForgetThresholdMinutes(), policy.getWorkDurationMinutes()); + log.info( + "会话[{}]本段学习已超过{}分钟无操作,按{}分钟结算", + this.getSessionNum(), + policy.getForgetThresholdMinutes(), + policy.getWorkDurationMinutes()); return this.lastStartTime.plusMinutes(policy.getWorkDurationMinutes()); } return end; @@ -199,15 +201,18 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { * 结束会话 */ public void endedStudySession(StudyTimePolicy policy) { - if (this.isEnded()){ - log.warn("不应出现的情况:结束了一个状态为【{}】的学习会话",this.getSessionState()); - }else { + if (this.isEnded()) { + log.warn("不应出现的情况:结束了一个状态为【{}】的学习会话", this.getSessionState()); + } else { if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) { this.pausedStudySession(LocalDateTime.now(), policy); } if (this.getEffectiveTime() < policy.getMinEffectiveTimeSeconds()) { - log.info("会话[{}]有效学习时间({}秒)不足{}分钟,不计入总学习时间", - this.getSessionNum(), this.getEffectiveTime(), policy.getMinEffectiveTimeSeconds() / 60); + log.info( + "会话[{}]有效学习时间({}秒)不足{}分钟,不计入总学习时间", + this.getSessionNum(), + this.getEffectiveTime(), + policy.getMinEffectiveTimeSeconds() / 60); this.setEffectiveTime(0); this.setEffectivenessRatio(0); } @@ -253,7 +258,6 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { return ObjectUtils.isEmpty(this.pointerPosition); } - /** * 计算当前倒计时指针的位置(使用默认时间口径) */ @@ -287,10 +291,10 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { return; case ONGOING: - long elapsedMillis = Duration.between(lastStartTime, LocalDateTime.now()).toMillis(); - long basePointerPosition = ObjectUtils.isEmpty(pointerPosition) - ? policy.workDurationMillis() - : pointerPosition; + long elapsedMillis = + Duration.between(lastStartTime, LocalDateTime.now()).toMillis(); + long basePointerPosition = + ObjectUtils.isEmpty(pointerPosition) ? policy.workDurationMillis() : pointerPosition; long newPointerPosition = basePointerPosition - elapsedMillis; if (newPointerPosition <= 0) { // 如果循环已经结束,则需要重置指针位置 @@ -313,7 +317,6 @@ public class StudySessionsEntity extends BaseEntity implements Serializable { } } - /** * 学习会话是否已经结束。 */ diff --git a/src/main/java/com/guo/learningprogresstracker/entity/TaskApplicationEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/TaskApplicationEntity.java index f942a0e..3f3e5cd 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/TaskApplicationEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/TaskApplicationEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; @TableName(value = "task_applications") @Data diff --git a/src/main/java/com/guo/learningprogresstracker/entity/TaskEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/TaskEntity.java index d5fd3bb..31284d8 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/TaskEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/TaskEntity.java @@ -4,16 +4,15 @@ 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 lombok.Data; /** * 存储学习任务的基本信息,包括优先级的多维度计算 * @author guo * @TableName tasks */ -@TableName(value ="tasks") +@TableName(value = "tasks") @Data public class TaskEntity extends BaseEntity implements Serializable { @@ -38,7 +37,6 @@ public class TaskEntity extends BaseEntity implements Serializable { @TableField(value = "task_description") private String taskDescription; - /** * 学习材料的存储URL */ @@ -89,4 +87,4 @@ public class TaskEntity extends BaseEntity implements Serializable { @TableField(exist = false) private static final long serialVersionUID = 1L; -} \ No newline at end of file +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/UserEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/UserEntity.java index 215ed44..52989aa 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/UserEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/UserEntity.java @@ -11,7 +11,7 @@ import lombok.Data; * 用户信息表 * @TableName user */ -@TableName(value ="user") +@TableName(value = "user") @Data public class UserEntity extends BaseEntity implements Serializable { /** @@ -33,17 +33,17 @@ public class UserEntity extends BaseEntity implements Serializable { private String userPassword; /** - * + * */ @TableField(value = "created_time") private LocalDateTime createdTime; /** - * + * */ @TableField(value = "created_by") private String createdBy; @TableField(exist = false) private static final long serialVersionUID = 1L; -} \ No newline at end of file +} diff --git a/src/main/java/com/guo/learningprogresstracker/entity/UserPriorityWeightsEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/UserPriorityWeightsEntity.java index 0d66c2c..7050be9 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/UserPriorityWeightsEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/UserPriorityWeightsEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; /** * 用户自定义的任务优先级维度权重(每用户一行,依赖多租户拦截器隔离) diff --git a/src/main/java/com/guo/learningprogresstracker/entity/UserReviewPreferencesEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/UserReviewPreferencesEntity.java index f7ce558..68f8473 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/UserReviewPreferencesEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/UserReviewPreferencesEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; /** * 复习排序偏好(复习-01):每个用户一条,保存三档预设之一。 diff --git a/src/main/java/com/guo/learningprogresstracker/entity/UserTagEntity.java b/src/main/java/com/guo/learningprogresstracker/entity/UserTagEntity.java index f614b89..713cf72 100644 --- a/src/main/java/com/guo/learningprogresstracker/entity/UserTagEntity.java +++ b/src/main/java/com/guo/learningprogresstracker/entity/UserTagEntity.java @@ -4,9 +4,8 @@ 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 lombok.Data; /** * 标签字典项(闭环-03)。 diff --git a/src/main/java/com/guo/learningprogresstracker/enums/AiTaskStatusEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/AiTaskStatusEnum.java index 74b98e7..b56b5a1 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/AiTaskStatusEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/AiTaskStatusEnum.java @@ -1,10 +1,9 @@ package com.guo.learningprogresstracker.enums; -import lombok.AllArgsConstructor; -import lombok.Getter; - import java.util.EnumSet; import java.util.Set; +import lombok.AllArgsConstructor; +import lombok.Getter; /** * AI 任务状态(AI-02)。 diff --git a/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java index 7207934..e859f9a 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/AiTaskTypeEnum.java @@ -9,9 +9,9 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum AiTaskTypeEnum { + RECALL_HINT("回忆提示"), - /** 回忆对比:把用户回忆大纲与标准导图对比 */ - RECALL_COMPARE("回忆对比"), + RECALL_CHECK("内容查漏"), /** 标准思维导图生成:全量、增量或按需生成 */ MIND_MAP("思维导图生成"), @@ -19,9 +19,6 @@ public enum AiTaskTypeEnum { /** 标签思维导图生成:按「标签集合 + 取数模式」生成或重建(闭环-04) */ TAG_MIND_MAP("标签思维导图生成"), - /** 标签范围回忆对比:把用户回忆大纲与标签导图对比(闭环-04) */ - TAG_RECALL_COMPARE("标签回忆对比"), - /** 学习报告草稿聚合 */ REPORT_DRAFT("学习报告草稿"), diff --git a/src/main/java/com/guo/learningprogresstracker/enums/MarkerKindEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/MarkerKindEnum.java index 9a4fc55..0e63ac0 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/MarkerKindEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/MarkerKindEnum.java @@ -12,7 +12,6 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum MarkerKindEnum { - SYSTEM("系统标记"), USER("用户标签"); diff --git a/src/main/java/com/guo/learningprogresstracker/enums/MarkerObjectTypeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/MarkerObjectTypeEnum.java index 11527e0..0d13b82 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/MarkerObjectTypeEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/MarkerObjectTypeEnum.java @@ -12,7 +12,6 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum MarkerObjectTypeEnum { - FRAGMENT("知识碎片"), TASK("学习任务"); diff --git a/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java index 811eee7..3c59e4a 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/MindMapGenerateModeEnum.java @@ -1,10 +1,9 @@ package com.guo.learningprogresstracker.enums; +import java.util.Locale; import lombok.AllArgsConstructor; import lombok.Getter; -import java.util.Locale; - /** * 思维导图的生成模式(AI-02):同一条生成链路按需全量重建、增量合并或缺失时才生成。 */ diff --git a/src/main/java/com/guo/learningprogresstracker/enums/ReviewScopeTypeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/ReviewScopeTypeEnum.java deleted file mode 100644 index 9794108..0000000 --- a/src/main/java/com/guo/learningprogresstracker/enums/ReviewScopeTypeEnum.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.guo.learningprogresstracker.enums; - -import lombok.AllArgsConstructor; -import lombok.Getter; - -/** - * 回忆记录的复习范围(闭环-04)。 - * - *

两种范围并存、互不替代:任务范围取材于内容归属为该任务的碎片,标签范围取材于带该标签集合的碎片。 - * 范围落在回忆记录上,让复习耗时与覆盖率统计仍然可用。

- */ -@Getter -@AllArgsConstructor -public enum ReviewScopeTypeEnum { - - /** 任务导图:复习对象是一个学习任务 */ - TASK("任务"), - - /** 标签导图:复习对象是一个标签集合 + 取数模式 */ - TAG("标签"); - - private final String description; -} diff --git a/src/main/java/com/guo/learningprogresstracker/enums/ReviewSortPresetEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/ReviewSortPresetEnum.java index 1b42eae..6070005 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/ReviewSortPresetEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/ReviewSortPresetEnum.java @@ -43,7 +43,8 @@ public enum ReviewSortPresetEnum { return DEFAULT; } try { - return valueOf(value.trim().toUpperCase()); + ReviewSortPresetEnum parsed = valueOf(value.trim().toUpperCase(java.util.Locale.ROOT)); + return parsed == MASTERY_FIRST ? BALANCED : parsed; } catch (IllegalArgumentException e) { return DEFAULT; } diff --git a/src/main/java/com/guo/learningprogresstracker/enums/StudySessionStateEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/StudySessionStateEnum.java index 22fb086..a365ff2 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/StudySessionStateEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/StudySessionStateEnum.java @@ -13,5 +13,4 @@ public enum StudySessionStateEnum { public String getDescription() { return this.description; } - } diff --git a/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java index dd6b0db..839ead0 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/TagCombineModeEnum.java @@ -1,10 +1,9 @@ package com.guo.learningprogresstracker.enums; +import java.util.Locale; import lombok.AllArgsConstructor; import lombok.Getter; -import java.util.Locale; - /** * 标签导图的取数模式(闭环-04)。 * diff --git a/src/main/java/com/guo/learningprogresstracker/enums/TaskApplicationStatusEnum.java b/src/main/java/com/guo/learningprogresstracker/enums/TaskApplicationStatusEnum.java index d0219af..23f3e51 100644 --- a/src/main/java/com/guo/learningprogresstracker/enums/TaskApplicationStatusEnum.java +++ b/src/main/java/com/guo/learningprogresstracker/enums/TaskApplicationStatusEnum.java @@ -1,9 +1,8 @@ package com.guo.learningprogresstracker.enums; -import lombok.AllArgsConstructor; - import java.util.Arrays; import java.util.Locale; +import lombok.AllArgsConstructor; @AllArgsConstructor public enum TaskApplicationStatusEnum { diff --git a/src/main/java/com/guo/learningprogresstracker/exception/AppException.java b/src/main/java/com/guo/learningprogresstracker/exception/AppException.java index 5b3e95d..cac4cab 100644 --- a/src/main/java/com/guo/learningprogresstracker/exception/AppException.java +++ b/src/main/java/com/guo/learningprogresstracker/exception/AppException.java @@ -4,9 +4,9 @@ package com.guo.learningprogresstracker.exception; * * 数据库连接失败等潜在异常 * */ -public class AppException extends Exception{ +public class AppException extends Exception { // 应用程序异常类 - public AppException(String message){ + public AppException(String message) { super(message); } } diff --git a/src/main/java/com/guo/learningprogresstracker/exception/ErrorParameterException.java b/src/main/java/com/guo/learningprogresstracker/exception/ErrorParameterException.java index 0cad1d6..5df0713 100644 --- a/src/main/java/com/guo/learningprogresstracker/exception/ErrorParameterException.java +++ b/src/main/java/com/guo/learningprogresstracker/exception/ErrorParameterException.java @@ -8,7 +8,7 @@ package com.guo.learningprogresstracker.exception; * * @author guo*/ public class ErrorParameterException extends Exception { - public ErrorParameterException(String message){ + public ErrorParameterException(String message) { super(message); } } diff --git a/src/main/java/com/guo/learningprogresstracker/exception/NotFindEntitiesException.java b/src/main/java/com/guo/learningprogresstracker/exception/NotFindEntitiesException.java index 12f6c87..0062041 100644 --- a/src/main/java/com/guo/learningprogresstracker/exception/NotFindEntitiesException.java +++ b/src/main/java/com/guo/learningprogresstracker/exception/NotFindEntitiesException.java @@ -10,7 +10,7 @@ package com.guo.learningprogresstracker.exception; * 响应code为404 * */ public class NotFindEntitiesException extends Exception { - public NotFindEntitiesException(String message){ + public NotFindEntitiesException(String message) { super(message); } } diff --git a/src/main/java/com/guo/learningprogresstracker/exception/OperationFailedException.java b/src/main/java/com/guo/learningprogresstracker/exception/OperationFailedException.java index 8235d2f..8e4ba34 100644 --- a/src/main/java/com/guo/learningprogresstracker/exception/OperationFailedException.java +++ b/src/main/java/com/guo/learningprogresstracker/exception/OperationFailedException.java @@ -6,9 +6,10 @@ package com.guo.learningprogresstracker.exception; * 当查询失败或者增删改的时候返回false * 响应code为404 * */ -public class OperationFailedException extends Exception{ - public OperationFailedException(){} - public OperationFailedException(String message){ +public class OperationFailedException extends Exception { + public OperationFailedException() {} + + public OperationFailedException(String message) { super(message); } } diff --git a/src/main/java/com/guo/learningprogresstracker/exception/RecallBusinessException.java b/src/main/java/com/guo/learningprogresstracker/exception/RecallBusinessException.java new file mode 100644 index 0000000..dade23b --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/exception/RecallBusinessException.java @@ -0,0 +1,14 @@ +package com.guo.learningprogresstracker.exception; + +import com.guo.learningprogresstracker.dto.recall.RecallDtos.BusinessError; +import lombok.Getter; + +@Getter +public class RecallBusinessException extends RuntimeException { + private final BusinessError data; + + public RecallBusinessException(String reason, String message) { + super(message); + data = new BusinessError(reason); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/AiTaskMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/AiTaskMapper.java index 3524416..fd408ec 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/AiTaskMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/AiTaskMapper.java @@ -3,14 +3,13 @@ package com.guo.learningprogresstracker.mapper; import com.baomidou.mybatisplus.annotation.InterceptorIgnore; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.guo.learningprogresstracker.entity.AiTaskEntity; +import java.time.LocalDateTime; +import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; -import java.time.LocalDateTime; -import java.util.List; - /** * AI 异步任务 Mapper(AI-02)。 */ @@ -26,13 +25,13 @@ public interface AiTaskMapper extends BaseMapper { */ @InterceptorIgnore(tenantLine = "true") @Select(""" - SELECT * - FROM ai_tasks - WHERE deleted = 0 - AND status = 'PENDING' - ORDER BY created_time ASC - LIMIT #{limit} - """) + SELECT * + FROM ai_tasks + WHERE deleted = 0 + AND status = 'PENDING' + ORDER BY created_time ASC + LIMIT #{limit} + """) List selectPendingTasks(@Param("limit") int limit); /** @@ -53,14 +52,14 @@ public interface AiTaskMapper extends BaseMapper { */ @InterceptorIgnore(tenantLine = "true") @Update(""" - UPDATE ai_tasks - SET status = 'RUNNING', - started_time = #{startedTime}, - last_modified_time = #{startedTime} - WHERE id = #{id} - AND status = 'PENDING' - AND deleted = 0 - """) + UPDATE ai_tasks + SET status = 'RUNNING', + started_time = #{startedTime}, + last_modified_time = #{startedTime} + WHERE id = #{id} + AND status = 'PENDING' + AND deleted = 0 + """) int claimTask(@Param("id") Integer id, @Param("startedTime") LocalDateTime startedTime); /** @@ -69,15 +68,15 @@ public interface AiTaskMapper extends BaseMapper { */ @InterceptorIgnore(tenantLine = "true") @Update(""" - UPDATE ai_tasks - SET status = 'PENDING', - started_time = NULL, - last_modified_time = #{now} - WHERE status = 'RUNNING' - AND deleted = 0 - AND started_time IS NOT NULL - AND started_time <= #{cutoff} - """) + UPDATE ai_tasks + SET status = 'PENDING', + started_time = NULL, + last_modified_time = #{now} + WHERE status = 'RUNNING' + AND deleted = 0 + AND started_time IS NOT NULL + AND started_time <= #{cutoff} + """) int reclaimStuckTasks(@Param("cutoff") LocalDateTime cutoff, @Param("now") LocalDateTime now); /** @@ -85,15 +84,23 @@ public interface AiTaskMapper extends BaseMapper { */ @InterceptorIgnore(tenantLine = "true") @Update(""" - UPDATE ai_tasks - SET status = #{status}, - result_payload = #{resultPayload}, - error_message = #{errorMessage}, - finished_time = #{finishedTime}, - last_modified_time = #{finishedTime} - WHERE id = #{id} - AND status = 'RUNNING' - AND deleted = 0 - """) + UPDATE ai_tasks + SET status = #{status}, + result_payload = #{resultPayload}, + error_message = #{errorMessage}, + finished_time = #{finishedTime}, + last_modified_time = #{finishedTime} + WHERE id = #{id} + AND status = 'RUNNING' + AND deleted = 0 + """) int finishTask(AiTaskEntity task); + + // New recall completion additionally checks the execution claim, leaving legacy behavior unchanged. + @Update(""" + UPDATE ai_tasks SET status = #{status}, result_payload = #{resultPayload}, + error_message = #{errorMessage}, error_code = #{errorCode}, finished_time = #{finishedTime} + WHERE id = #{id} AND status = 'RUNNING' AND deleted = 0 AND started_time = #{startedTime} + """) + int finishRecallTask(AiTaskEntity task); } diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java index b122f62..8351853 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/AiUsageRecordMapper.java @@ -5,11 +5,10 @@ import com.guo.learningprogresstracker.dto.AiUsageBreakdownRow; import com.guo.learningprogresstracker.dto.AiUsageSeriesRow; import com.guo.learningprogresstracker.dto.AiUsageSummaryRow; import com.guo.learningprogresstracker.entity.AiUsageRecordEntity; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; - import java.time.LocalDateTime; import java.util.List; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; /** * AI 用量记录 Mapper。 @@ -34,11 +33,12 @@ public interface AiUsageRecordMapper extends BaseMapper { * @param userId 归属用户精确匹配;null 表示不限(契约 v2 第 4.1 节) * @return 无匹配记录时返回全 0 的一行(AVG 为 null) */ - AiUsageSummaryRow selectSummary(@Param("from") LocalDateTime from, - @Param("to") LocalDateTime to, - @Param("taskType") String taskType, - @Param("model") String model, - @Param("userId") String userId); + AiUsageSummaryRow selectSummary( + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("taskType") String taskType, + @Param("model") String model, + @Param("userId") String userId); /** * P95 调用耗时(毫秒,最近秩法:取第 {@code ceil(0.95 × 调用数)} 小的耗时)。 @@ -48,33 +48,36 @@ public interface AiUsageRecordMapper extends BaseMapper { * * @return 无匹配记录时返回 null */ - Integer selectP95DurationMs(@Param("from") LocalDateTime from, - @Param("to") LocalDateTime to, - @Param("taskType") String taskType, - @Param("model") String model, - @Param("userId") String userId); + Integer selectP95DurationMs( + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("taskType") String taskType, + @Param("model") String model, + @Param("userId") String userId); /** * 按天或按小时分桶的用量趋势(契约 2.3)。 * * @param bucket {@code day}(默认)或 {@code hour} */ - List selectSeries(@Param("from") LocalDateTime from, - @Param("to") LocalDateTime to, - @Param("taskType") String taskType, - @Param("model") String model, - @Param("userId") String userId, - @Param("bucket") String bucket); + List selectSeries( + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("taskType") String taskType, + @Param("model") String model, + @Param("userId") String userId, + @Param("bucket") String bucket); /** * 按任务类型、模型或归属用户分组的用量(契约 2.4 / v2 第 4.2 节)。 * * @param groupBy {@code taskType}(默认)、{@code model} 或 {@code user} */ - List selectBreakdown(@Param("from") LocalDateTime from, - @Param("to") LocalDateTime to, - @Param("taskType") String taskType, - @Param("model") String model, - @Param("userId") String userId, - @Param("groupBy") String groupBy); + List selectBreakdown( + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("taskType") String taskType, + @Param("model") String model, + @Param("userId") String userId, + @Param("groupBy") String groupBy); } diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java index 2e3547a..a3361c1 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/MarkerMapper.java @@ -4,14 +4,13 @@ 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 java.util.Collection; +import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; -import java.util.Collection; -import java.util.List; - @Mapper public interface MarkerMapper extends BaseMapper { @@ -20,18 +19,39 @@ public interface MarkerMapper extends BaseMapper { *

只统计用户标签:系统标记不在用户的治理范围内。

*/ @Select(""" - SELECT marker_name AS marker_name, - COUNT(*) AS marker_count, - COUNT(DISTINCT object_num) AS object_count - FROM markers - WHERE deleted = 0 - AND kind = 'USER' - AND created_by = #{createdBy} - GROUP BY marker_name - ORDER BY marker_count DESC, marker_name ASC - """) + SELECT marker_name AS marker_name, + COUNT(*) AS marker_count, + COUNT(DISTINCT object_num) AS object_count + FROM markers + WHERE deleted = 0 + AND kind = 'USER' + AND created_by = #{createdBy} + GROUP BY marker_name + ORDER BY marker_count DESC, marker_name ASC + """) List selectUserTagUsage(@Param("createdBy") String createdBy); + /** Only tags attached to a live object owned by the same tenant may select a review scope. */ + @Select(""" + SELECT MIN(m.marker_name) AS marker_name, + COUNT(DISTINCT m.object_num) AS marker_count, + COUNT(DISTINCT m.object_num) AS object_count + FROM markers m + WHERE m.deleted = 0 AND m.kind = 'USER' + AND m.created_by = #{createdBy} AND m.object_type = #{objectType} + AND TRIM(m.marker_name) <> '' + AND ((m.object_type = 'FRAGMENT' AND EXISTS ( + SELECT 1 FROM study_report_fragments f + WHERE m.object_num = CONCAT('', f.id) AND f.deleted = 0 AND f.created_by = m.created_by)) + OR (m.object_type = 'TASK' AND EXISTS ( + SELECT 1 FROM tasks t + WHERE t.task_num = m.object_num AND t.deleted = 0 AND t.created_by = m.created_by))) + GROUP BY LOWER(TRIM(m.marker_name)) + ORDER BY marker_count DESC, marker_name ASC + """) + List selectUserTagUsageByObjectType( + @Param("createdBy") String createdBy, @Param("objectType") String objectType); + /** * 按对象 + 标签名取用户标签,含已逻辑删除的行。 * @@ -41,17 +61,19 @@ public interface MarkerMapper extends BaseMapper { * 租户条件 {@code created_by} 仍由 {@code TenantLineInnerInterceptor} 自动追加。

*/ @Select(""" - SELECT * FROM markers - WHERE object_type = #{objectType} - AND object_num = #{objectNum} - AND kind = #{kind} - AND marker_name = #{markerName} - LIMIT 1 - """) - MarkerEntity selectAnyByObjectAndName(@Param("objectType") String objectType, - @Param("objectNum") String objectNum, - @Param("kind") String kind, - @Param("markerName") String markerName); + SELECT * FROM markers + WHERE object_type = #{objectType} + AND object_num = #{objectNum} + AND kind = #{kind} + AND LOWER(TRIM(marker_name)) = LOWER(TRIM(#{markerName})) + ORDER BY deleted ASC, id ASC + LIMIT 1 + """) + MarkerEntity selectAnyByObjectAndName( + @Param("objectType") String objectType, + @Param("objectNum") String objectNum, + @Param("kind") String kind, + @Param("markerName") String markerName); /** * 复用(复活)一条已逻辑删除的标记:把 {@code deleted} 归零。 @@ -70,17 +92,17 @@ public interface MarkerMapper extends BaseMapper { * @param tagKeys 规范化标签名;为空时返回空列表 */ @Select(""" - - """) + + """) List countUserTagsPerFragment(@Param("tagKeys") Collection tagKeys); } diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewGuidanceConversationMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewGuidanceConversationMapper.java index d789ac4..61e312a 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewGuidanceConversationMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewGuidanceConversationMapper.java @@ -5,5 +5,4 @@ import com.guo.learningprogresstracker.entity.ReviewGuidanceConversationEntity; import org.apache.ibatis.annotations.Mapper; @Mapper -public interface ReviewGuidanceConversationMapper extends BaseMapper { -} +public interface ReviewGuidanceConversationMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallMapper.java new file mode 100644 index 0000000..d12fdcb --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallMapper.java @@ -0,0 +1,29 @@ +package com.guo.learningprogresstracker.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.entity.ReviewRecallEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ReviewRecallMapper extends BaseMapper { + @com.baomidou.mybatisplus.annotation.InterceptorIgnore(tenantLine = "true") + @org.apache.ibatis.annotations.Insert("INSERT IGNORE INTO review_recall_owner_locks (owner_id) VALUES (#{userId})") + int ensureOwnerLock(@org.apache.ibatis.annotations.Param("userId") String userId); + + // Dedicated lock row, not a login/session mutation. Explicit owner id prevents cross-user locking. + @com.baomidou.mybatisplus.annotation.InterceptorIgnore(tenantLine = "true") + @org.apache.ibatis.annotations.Select( + "SELECT owner_id FROM review_recall_owner_locks WHERE owner_id = #{userId} FOR UPDATE") + String lockUser(@org.apache.ibatis.annotations.Param("userId") String userId); + + @org.apache.ibatis.annotations.Select( + "SELECT task_num, SUM(active_duration_ms) AS active_duration_ms FROM review_recalls WHERE deleted = 0 AND" + + " scope_type = 'TASK' GROUP BY task_num") + @org.apache.ibatis.annotations.Results( + id = "taskRecallDuration", + value = { + @org.apache.ibatis.annotations.Result(column = "task_num", property = "taskNum"), + @org.apache.ibatis.annotations.Result(column = "active_duration_ms", property = "activeDurationMs") + }) + java.util.List sumTaskDuration(); +} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallReceiptMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallReceiptMapper.java new file mode 100644 index 0000000..9e97c13 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallReceiptMapper.java @@ -0,0 +1,8 @@ +package com.guo.learningprogresstracker.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.entity.ReviewRecallReceiptEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ReviewRecallReceiptMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallRecordMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallRecordMapper.java deleted file mode 100644 index db36b73..0000000 --- a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallRecordMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.guo.learningprogresstracker.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.guo.learningprogresstracker.dto.TaskRecallRatio; -import com.guo.learningprogresstracker.dto.TaskReviewDuration; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; - -import java.util.Collection; -import java.util.List; - -@Mapper -public interface ReviewRecallRecordMapper extends BaseMapper { - - /** - * 按任务汇总复习耗时(秒,复习-07)。 - *

Wrapper 无法表达 SUM + GROUP BY,因此放在 Mapper 层用自定义 SQL + 显式结果类; - * 语句见 {@code resources/mapper/ReviewRecallRecordMapper.xml}(逻辑删除条件已显式写出, - * 租户条件由拦截器自动追加)。

- * - * @param taskNums 需要汇总的任务编号;为空时返回空列表 - */ - List sumReviewDurationByTask(@Param("taskNums") Collection taskNums); - - /** - * 每个任务最近一条回忆记录的覆盖率(复习-04)。 - *

语句见 {@code resources/mapper/ReviewRecallRecordMapper.xml};返回行数等于任务数, - * 不随复习次数增长,且不读取 {@code compare_result} 大字段。

- * - * @param taskNums 需要查询的任务编号;为空时返回空列表 - */ - List selectLatestRatioByTask(@Param("taskNums") Collection taskNums); -} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallRequestMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallRequestMapper.java new file mode 100644 index 0000000..9c099ee --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewRecallRequestMapper.java @@ -0,0 +1,8 @@ +package com.guo.learningprogresstracker.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.entity.ReviewRecallRequestEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ReviewRecallRequestMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewStandardMindMapMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewStandardMindMapMapper.java index 2b023e3..cd90b16 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewStandardMindMapMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewStandardMindMapMapper.java @@ -5,5 +5,4 @@ import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import org.apache.ibatis.annotations.Mapper; @Mapper -public interface ReviewStandardMindMapMapper extends BaseMapper { -} +public interface ReviewStandardMindMapMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java index 50bfdf4..d9aa63b 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/ReviewTagMindMapMapper.java @@ -9,5 +9,4 @@ import org.apache.ibatis.annotations.Mapper; *

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

*/ @Mapper -public interface ReviewTagMindMapMapper extends BaseMapper { -} +public interface ReviewTagMindMapMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/StudyExpectationsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/StudyExpectationsMapper.java index d47a3ec..7cd96e3 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/StudyExpectationsMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/StudyExpectationsMapper.java @@ -5,5 +5,4 @@ import com.guo.learningprogresstracker.entity.StudyExpectationsEntity; import org.apache.ibatis.annotations.Mapper; @Mapper -public interface StudyExpectationsMapper extends BaseMapper { -} +public interface StudyExpectationsMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java index a12fc82..0898e12 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java @@ -1,21 +1,20 @@ package com.guo.learningprogresstracker.mapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.guo.learningprogresstracker.dto.IdRange; import com.guo.learningprogresstracker.dto.TaskContentCount; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import java.util.Collection; +import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; -import java.util.Collection; -import java.util.List; - /** -* @author guo -* @description 针对表【study_report_fragments(记录学习过程中的学习内容报告残片)】的数据库操作Mapper -* @createDate 2024-06-09 15:28:48 -* @Entity com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity -*/ + * @author guo + * @description 针对表【study_report_fragments(记录学习过程中的学习内容报告残片)】的数据库操作Mapper + * @createDate 2024-06-09 15:28:48 + * @Entity com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity + */ @Mapper public interface StudyReportFragmentsMapper extends BaseMapper { @@ -44,7 +43,3 @@ public interface StudyReportFragmentsMapper extends BaseMapper { @@ -40,7 +39,3 @@ public interface StudyReportsMapper extends BaseMapper { */ long countOwnedReports(); } - - - - diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java index 5bc5ab5..727750b 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java @@ -1,24 +1,23 @@ package com.guo.learningprogresstracker.mapper; -import com.guo.learningprogresstracker.dto.TaskSessionStats; -import com.guo.learningprogresstracker.entity.StudySessionsEntity; import com.baomidou.mybatisplus.annotation.InterceptorIgnore; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.dto.TaskSessionStats; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; -import java.time.LocalDateTime; -import java.util.Collection; -import java.util.List; - /** -* @author guo -* @description 针对表【study_sessions(记录每次学习会话的具体数据)】的数据库操作Mapper -* @createDate 2024-06-09 15:28:48 -* @Entity com.guo.learningprogresstracker.entity.StudySessionsEntity -*/ + * @author guo + * @description 针对表【study_sessions(记录每次学习会话的具体数据)】的数据库操作Mapper + * @createDate 2024-06-09 15:28:48 + * @Entity com.guo.learningprogresstracker.entity.StudySessionsEntity + */ @Mapper public interface StudySessionsMapper extends BaseMapper { @@ -31,16 +30,16 @@ public interface StudySessionsMapper extends BaseMapper { */ @InterceptorIgnore(tenantLine = "true") @Select(""" - SELECT * - FROM study_sessions - WHERE deleted = 0 - AND session_state = 'ONGOING' - AND last_start_time <= #{cutoff} - ORDER BY last_start_time ASC - LIMIT #{limit} - """) - List selectForcePausableSessions(@Param("cutoff") LocalDateTime cutoff, - @Param("limit") int limit); + SELECT * + FROM study_sessions + WHERE deleted = 0 + AND session_state = 'ONGOING' + AND last_start_time <= #{cutoff} + ORDER BY last_start_time ASC + LIMIT #{limit} + """) + List selectForcePausableSessions( + @Param("cutoff") LocalDateTime cutoff, @Param("limit") int limit); /** * 条件写入收敛结果(会话-04):只有仍然处于 ONGOING 的会话才会被写入,保证并发下不会重复结算。 @@ -52,18 +51,18 @@ public interface StudySessionsMapper extends BaseMapper { */ @InterceptorIgnore(tenantLine = "true") @Update(""" - UPDATE study_sessions - SET end_time = #{endTime}, - actual_time = #{actualTime}, - effective_time = #{effectiveTime}, - effectiveness_ratio = #{effectivenessRatio}, - session_state = #{sessionState}, - auto_converged = #{autoConverged}, - last_modified_time = #{lastModifiedTime} - WHERE id = #{id} - AND session_state = 'ONGOING' - AND deleted = 0 - """) + UPDATE study_sessions + SET end_time = #{endTime}, + actual_time = #{actualTime}, + effective_time = #{effectiveTime}, + effectiveness_ratio = #{effectivenessRatio}, + session_state = #{sessionState}, + auto_converged = #{autoConverged}, + last_modified_time = #{lastModifiedTime} + WHERE id = #{id} + AND session_state = 'ONGOING' + AND deleted = 0 + """) int convergeStaleSession(StudySessionsEntity session); /** @@ -75,7 +74,8 @@ public interface StudySessionsMapper extends BaseMapper { * @param todayStart 今日起点(含) * @param weekStart 本周起点(含) */ - List sumStudyStatsByTask(@Param("taskNums") Collection taskNums, - @Param("todayStart") LocalDateTime todayStart, - @Param("weekStart") LocalDateTime weekStart); + List sumStudyStatsByTask( + @Param("taskNums") Collection taskNums, + @Param("todayStart") LocalDateTime todayStart, + @Param("weekStart") LocalDateTime weekStart); } diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/TaskApplicationMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/TaskApplicationMapper.java index 517ab19..43b66f6 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/TaskApplicationMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/TaskApplicationMapper.java @@ -5,5 +5,4 @@ import com.guo.learningprogresstracker.entity.TaskApplicationEntity; import org.apache.ibatis.annotations.Mapper; @Mapper -public interface TaskApplicationMapper extends BaseMapper { -} +public interface TaskApplicationMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/TasksMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/TasksMapper.java index c63acdc..17d26c1 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/TasksMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/TasksMapper.java @@ -1,17 +1,17 @@ package com.guo.learningprogresstracker.mapper; -import com.guo.learningprogresstracker.entity.TaskEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; +import com.guo.learningprogresstracker.entity.TaskEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** -* @author guo -* @description 针对表【tasks(存储学习任务的基本信息,包括优先级的多维度计算)】的数据库操作Mapper -* @createDate 2024-06-09 15:28:48 -* @Entity com.guo.learningprogresstracker.entity.TasksEntity -*/ + * @author guo + * @description 针对表【tasks(存储学习任务的基本信息,包括优先级的多维度计算)】的数据库操作Mapper + * @createDate 2024-06-09 15:28:48 + * @Entity com.guo.learningprogresstracker.entity.TasksEntity + */ @Mapper public interface TasksMapper extends BaseMapper { @@ -28,7 +28,3 @@ public interface TasksMapper extends BaseMapper { */ IPage selectPageByMarker(IPage page, @Param("markerName") String markerName); } - - - - diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/UserMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/UserMapper.java index f9f0b77..a128644 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/UserMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/UserMapper.java @@ -1,20 +1,14 @@ package com.guo.learningprogresstracker.mapper; -import com.guo.learningprogresstracker.entity.UserEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.guo.learningprogresstracker.entity.UserEntity; import org.apache.ibatis.annotations.Mapper; /** -* @author guo -* @description 针对表【user(用户信息表)】的数据库操作Mapper -* @createDate 2024-06-09 15:28:48 -* @Entity com.guo.learningprogresstracker.entity.UserEntity -*/ + * @author guo + * @description 针对表【user(用户信息表)】的数据库操作Mapper + * @createDate 2024-06-09 15:28:48 + * @Entity com.guo.learningprogresstracker.entity.UserEntity + */ @Mapper -public interface UserMapper extends BaseMapper { - -} - - - - +public interface UserMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/UserPriorityWeightsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/UserPriorityWeightsMapper.java index c9092d0..7b7cfde 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/UserPriorityWeightsMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/UserPriorityWeightsMapper.java @@ -5,5 +5,4 @@ import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity; import org.apache.ibatis.annotations.Mapper; @Mapper -public interface UserPriorityWeightsMapper extends BaseMapper { -} +public interface UserPriorityWeightsMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/UserReviewPreferencesMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/UserReviewPreferencesMapper.java index 188a380..d449efa 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapper/UserReviewPreferencesMapper.java +++ b/src/main/java/com/guo/learningprogresstracker/mapper/UserReviewPreferencesMapper.java @@ -5,5 +5,4 @@ import com.guo.learningprogresstracker.entity.UserReviewPreferencesEntity; import org.apache.ibatis.annotations.Mapper; @Mapper -public interface UserReviewPreferencesMapper extends BaseMapper { -} +public interface UserReviewPreferencesMapper extends BaseMapper {} diff --git a/src/main/java/com/guo/learningprogresstracker/mapStruct/FragmentsConvert.java b/src/main/java/com/guo/learningprogresstracker/mapstruct/FragmentsConvert.java similarity index 82% rename from src/main/java/com/guo/learningprogresstracker/mapStruct/FragmentsConvert.java rename to src/main/java/com/guo/learningprogresstracker/mapstruct/FragmentsConvert.java index ff4d89f..170bec7 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapStruct/FragmentsConvert.java +++ b/src/main/java/com/guo/learningprogresstracker/mapstruct/FragmentsConvert.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.mapStruct; +package com.guo.learningprogresstracker.mapstruct; import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; import com.guo.learningprogresstracker.dto.request.UpdateFragmentsRequest; @@ -7,7 +7,7 @@ import org.mapstruct.Mapper; import org.mapstruct.ReportingPolicy; import org.mapstruct.factory.Mappers; -@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE) +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface FragmentsConvert { FragmentsConvert MAPPER = Mappers.getMapper(FragmentsConvert.class); diff --git a/src/main/java/com/guo/learningprogresstracker/mapstruct/RecallConvert.java b/src/main/java/com/guo/learningprogresstracker/mapstruct/RecallConvert.java new file mode 100644 index 0000000..5ec5d5f --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/mapstruct/RecallConvert.java @@ -0,0 +1,11 @@ +package com.guo.learningprogresstracker.mapstruct; + +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallSummary; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface RecallConvert { + RecallSummary toSummary(RecallDetail detail); +} diff --git a/src/main/java/com/guo/learningprogresstracker/mapStruct/RequestConvert.java b/src/main/java/com/guo/learningprogresstracker/mapstruct/RequestConvert.java similarity index 90% rename from src/main/java/com/guo/learningprogresstracker/mapStruct/RequestConvert.java rename to src/main/java/com/guo/learningprogresstracker/mapstruct/RequestConvert.java index ea55d2b..4fa2e8d 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapStruct/RequestConvert.java +++ b/src/main/java/com/guo/learningprogresstracker/mapstruct/RequestConvert.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.mapStruct; +package com.guo.learningprogresstracker.mapstruct; import com.guo.learningprogresstracker.dto.PriorityDto; import com.guo.learningprogresstracker.dto.request.TaskRequest; diff --git a/src/main/java/com/guo/learningprogresstracker/mapStruct/StudySessionConvert.java b/src/main/java/com/guo/learningprogresstracker/mapstruct/StudySessionConvert.java similarity index 81% rename from src/main/java/com/guo/learningprogresstracker/mapStruct/StudySessionConvert.java rename to src/main/java/com/guo/learningprogresstracker/mapstruct/StudySessionConvert.java index d8b606f..377adeb 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapStruct/StudySessionConvert.java +++ b/src/main/java/com/guo/learningprogresstracker/mapstruct/StudySessionConvert.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.mapStruct; +package com.guo.learningprogresstracker.mapstruct; import com.guo.learningprogresstracker.dto.StudySessionsDto; import com.guo.learningprogresstracker.dto.response.StudySessionResponse; @@ -7,11 +7,10 @@ import org.mapstruct.Mapper; import org.mapstruct.ReportingPolicy; import org.mapstruct.factory.Mappers; -@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE) +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface StudySessionConvert { StudySessionConvert MAPPER = Mappers.getMapper(StudySessionConvert.class); - StudySessionResponse toStudySessionResponse(StudySessionsEntity studySessionsEntity); StudySessionResponse toStudySessionResponse(StudySessionsDto dto); diff --git a/src/main/java/com/guo/learningprogresstracker/mapStruct/TaskConvert.java b/src/main/java/com/guo/learningprogresstracker/mapstruct/TaskConvert.java similarity index 88% rename from src/main/java/com/guo/learningprogresstracker/mapStruct/TaskConvert.java rename to src/main/java/com/guo/learningprogresstracker/mapstruct/TaskConvert.java index c6be1c5..7268ab3 100644 --- a/src/main/java/com/guo/learningprogresstracker/mapStruct/TaskConvert.java +++ b/src/main/java/com/guo/learningprogresstracker/mapstruct/TaskConvert.java @@ -1,5 +1,4 @@ -package com.guo.learningprogresstracker.mapStruct; - +package com.guo.learningprogresstracker.mapstruct; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.guo.learningprogresstracker.dto.TaskInfo; @@ -23,7 +22,7 @@ public interface TaskConvert { TaskInfoResponse taskEntityToTaskInfoResponse(TaskEntity taskEntity); - @Mapping(source = "calculatedPriority",target = "taskPriority") + @Mapping(source = "calculatedPriority", target = "taskPriority") TaskInfo toTaskInfo(TaskEntity taskEntity); Page toTaskInfoPage(Page page); diff --git a/src/main/java/com/guo/learningprogresstracker/service/AiTaskService.java b/src/main/java/com/guo/learningprogresstracker/service/AiTaskService.java index 8597e2d..f876705 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/AiTaskService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/AiTaskService.java @@ -5,7 +5,6 @@ import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest; import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; - import java.util.List; import java.util.Map; diff --git a/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java b/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java index b4b82b9..1d60619 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/AiUsageService.java @@ -8,7 +8,6 @@ import com.guo.learningprogresstracker.dto.AiUsageSummary; import com.guo.learningprogresstracker.dto.request.AiUsageQuery; import com.guo.learningprogresstracker.dto.request.AiUsageRecordRequest; import com.guo.learningprogresstracker.exception.ErrorParameterException; - import java.util.List; /** diff --git a/src/main/java/com/guo/learningprogresstracker/service/ExportService.java b/src/main/java/com/guo/learningprogresstracker/service/ExportService.java index 7048fa3..0ebea0a 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/ExportService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ExportService.java @@ -3,7 +3,6 @@ package com.guo.learningprogresstracker.service; import com.guo.learningprogresstracker.dto.ExportResult; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; - import java.time.LocalDate; /** diff --git a/src/main/java/com/guo/learningprogresstracker/service/MarkerService.java b/src/main/java/com/guo/learningprogresstracker/service/MarkerService.java index f998ee2..152b8b8 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/MarkerService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/MarkerService.java @@ -7,7 +7,6 @@ import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; import com.guo.learningprogresstracker.enums.SystemMarkerEnum; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; - import java.util.Collection; import java.util.List; import java.util.Map; @@ -59,14 +58,16 @@ public interface MarkerService { * * @param kind 可传 SYSTEM / USER 限定种类,null 表示不限 */ - List findObjectNumsByMarker(MarkerObjectTypeEnum objectType, String markerName, String markerValue, - String kind); + List findObjectNumsByMarker( + MarkerObjectTypeEnum objectType, String markerName, String markerValue, String kind); /** * 当前用户用过的标签及使用情况(标签管理界面)。 */ List listUserTagUsage(); + List listUserTagUsage(MarkerObjectTypeEnum objectType); + /** * 写入一个系统标记,供系统在产出内容时调用(如学习引导产出的碎片)。 *

幂等;标记名与值必须来自 {@link SystemMarkerEnum} 词表。

@@ -76,7 +77,8 @@ public interface MarkerService { /** * 残片获得内容归属时自动打「任务名标签」(闭环-02)。 * - *

标签名取任务当时的名字,走用户标签;幂等,任务编号为空或任务不存在时不打标。 + *

标签名取任务当时的名字,走用户标签;幂等,任务编号为空时保留待归类、不打标。 + * 有归属但任务不可用或标签写入失败时,随创建/归属事务回滚,避免留下无标签的已归属碎片。 * 任务改名不追溯、删任务时标签保留——因为标签只是带任务名字符串的普通用户标签, * 系统不会主动改写或级联删除它。

*/ diff --git a/src/main/java/com/guo/learningprogresstracker/service/MindMapAiClient.java b/src/main/java/com/guo/learningprogresstracker/service/MindMapAiClient.java index 174d1ce..bfbda1e 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/MindMapAiClient.java +++ b/src/main/java/com/guo/learningprogresstracker/service/MindMapAiClient.java @@ -5,7 +5,6 @@ import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.TaskApplicationEntity; import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.utils.MindMapNode; - import java.util.List; import java.util.Optional; @@ -32,11 +31,12 @@ public interface MindMapAiClient { * @param clientHint 前端已有的大纲文本(可选,用于 AI 续写而非全量生成) * @return 标准思维导图的根节点;若无可生成数据则返回 {@link Optional#empty()} */ - Optional generate(TaskEntity task, - List fragments, - List applications, - List reports, - String clientHint); + Optional generate( + TaskEntity task, + List fragments, + List applications, + List reports, + String clientHint); /** * 获取生成器标识(如 {@code BUILTIN} / {@code AI-4.5}) diff --git a/src/main/java/com/guo/learningprogresstracker/service/ReviewService.java b/src/main/java/com/guo/learningprogresstracker/service/ReviewService.java index 6e439cf..fd4d19e 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/ReviewService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ReviewService.java @@ -1,13 +1,12 @@ package com.guo.learningprogresstracker.service; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.guo.learningprogresstracker.dto.ReviewFeedItem; import com.guo.learningprogresstracker.dto.ReviewSummary; import com.guo.learningprogresstracker.dto.ReviewTaskStats; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; - import java.util.List; /** diff --git a/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java b/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java index 5d813a3..7ebb534 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ReviewTagMindMapService.java @@ -1,92 +1,30 @@ package com.guo.learningprogresstracker.service; -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; -import com.guo.learningprogresstracker.dto.ReviewTiming; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.guo.learningprogresstracker.dto.TagMindMapSummary; import com.guo.learningprogresstracker.dto.TagMindMapView; import com.guo.learningprogresstracker.dto.TagScope; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 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)异步完成;
  • - *
  • 重建手动触发:素材(碎片标签)变化只把导图置「待更新」,不自动重建。
  • - *
- */ +/** Tag-scope mind map service. */ public interface ReviewTagMindMapService { - - /** - * 解析复习范围:去空白、按归一化名去重排序、算范围键,并校验标签数量与取数模式。 - * - * @param mode UNION(默认,并集)/ INTERSECT(交集) - */ TagScope resolveScope(List tags, String mode) throws ErrorParameterException; - /** - * 读取该范围的状态:范围描述 + 已有导图 + 最近一次回忆对比;读取不触发生成。 - */ TagMindMapView query(TagScope scope); - /** - * 分页列出当前用户已经生成过导图的标签范围(待更新优先,其次按生成时间倒序)。 - * - *

「按标签复习」的主入口:用户先看到已经生成过导图的标签集合, - * 直接进入复习或把新碎片补充进去,不必先选标签再判断这个范围有没有导图。

- */ Page listMaps(int pageNum, int pageSize); - /** - * 用户手动编辑标签导图(用缩进大纲文本替换);该范围还没有导图时保存即为新建。 - */ ReviewTagMindMapEntity updateByOutline(TagScope scope, String outline); - /** - * 重新生成该范围的标签导图(由 AI 任务执行器在请求线程之外调用)。 - */ ReviewTagMindMapEntity regenerate(TagScope scope) throws OperationFailedException; - /** - * 增量更新:保留用户编辑过的节点,合并最新生成的节点。 - */ - ReviewTagMindMapEntity incrementalGenerate(TagScope scope) throws NotFindEntitiesException, OperationFailedException; + ReviewTagMindMapEntity incrementalGenerate(TagScope scope) + throws NotFindEntitiesException, OperationFailedException; - /** - * 提交一次标签范围的回忆对比并落回忆记录(范围=标签集合 + 取数模式,任务列为空)。 - * - *

由 AI 任务执行器在请求线程之外调用;方法本身不持有事务,避免等待 AI 时占用数据库连接。

- * - * @param recallOutline 用户回忆的缩进大纲文本 - * @param focusPath 可选:标签导图中的节点路径(/ 分隔),指定后仅对比该子树 - * @param timing 可选:本次复习行为的计时信息(复习-07),为空时不计复习耗时 - * @return 对比结果;其中 {@code standardMapId} 是本次对比使用的基准导图 ID(标签范围下即标签导图 ID) - */ - RecallCompareOutcome recallCompare(TagScope scope, String recallOutline, String focusPath, ReviewTiming timing) - throws OperationFailedException; - - /** - * 该范围的回忆对比记录(倒序,最近一次在最前)。 - */ - List listRecallRecords(TagScope scope); - - /** - * 素材发生变化时的置「待更新」(不重建)。 - * - *

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

- */ 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 e0d2f0e..ed8e129 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/StandardMindMapService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/StandardMindMapService.java @@ -1,82 +1,21 @@ package com.guo.learningprogresstracker.service; -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; -import com.guo.learningprogresstracker.dto.ReviewTiming; -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; -/** - * 标准思维导图服务。 - *

负责标准导图的按需生成、查询、用户编辑,以及用户回忆导图的对比。

- */ +/** Task standard mind maps used by the learning screen. */ public interface StandardMindMapService { - - /** - * 获取指定任务已有的标准思维导图;不存在时返回 null。 - * - *

不在读取路径上触发生成:生成可能耗时数分钟(AI-02),应由 AI 任务异步完成。

- */ ReviewStandardMindMapEntity getExisting(String taskNum) throws NotFindEntitiesException; - /** - * 强制重新生成指定任务的标准思维导图。 - */ ReviewStandardMindMapEntity regenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException; - /** - * 增量更新:保留用户编辑过的节点,合并最新生成的节点。 - */ - ReviewStandardMindMapEntity incrementalGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException; + ReviewStandardMindMapEntity incrementalGenerate(String taskNum) + throws NotFindEntitiesException, OperationFailedException; - /** - * 用户手动编辑标准思维导图(用缩进大纲文本替换)。 - */ ReviewStandardMindMapEntity updateByOutline(String taskNum, String outline) throws NotFindEntitiesException; - /** - * 用户提交回忆大纲,与标准导图对比。 - * - *

由 AI 任务执行器在请求线程之外调用;方法本身不持有事务,避免等待 AI 时占用数据库连接。

- * - * @param recallOutline 用户回忆的缩进大纲文本 - * @param focusPath 可选:标准导图中的节点路径(/ 分隔),指定后仅对比该子树 - * @param timing 可选:本次复习行为的计时信息(复习-07),为空时不计复习耗时 - */ - 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); - - /** - * 根据内容文本在标准导图中查找最匹配的节点,返回节点路径。 - * - * @return { "path": "节点A / 节点B", "nodeTitle": "节点B", "score": 0.85 } - */ - Map findNode(String taskNum, String content) throws NotFindEntitiesException, OperationFailedException; - - /** - * 获取该任务的所有回忆对比记录。 - */ - List listRecallRecords(String taskNum) throws NotFindEntitiesException; - - /** - * 获取单条对比记录详情。 - */ - ReviewRecallRecordEntity getRecallRecord(Integer recordId) throws NotFindEntitiesException; + Map findNode(String taskNum, String content) + throws NotFindEntitiesException, OperationFailedException; } diff --git a/src/main/java/com/guo/learningprogresstracker/service/StudyReportFragmentsService.java b/src/main/java/com/guo/learningprogresstracker/service/StudyReportFragmentsService.java index 812f0c8..0899034 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/StudyReportFragmentsService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/StudyReportFragmentsService.java @@ -1,18 +1,17 @@ package com.guo.learningprogresstracker.service; +import com.baomidou.mybatisplus.extension.service.IService; import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; import com.guo.learningprogresstracker.dto.request.UpdateFragmentsRequest; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; -import com.baomidou.mybatisplus.extension.service.IService; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; - import java.util.List; /** -* @author guo -* @description 针对表【study_report_fragments(记录学习过程中的学习内容报告残片)】的数据库操作Service -* @createDate 2024-06-09 15:28:48 -*/ + * @author guo + * @description 针对表【study_report_fragments(记录学习过程中的学习内容报告残片)】的数据库操作Service + * @createDate 2024-06-09 15:28:48 + */ public interface StudyReportFragmentsService extends IService { void createFragments(CreateFragmentsRequest request) throws NotFindEntitiesException; diff --git a/src/main/java/com/guo/learningprogresstracker/service/StudyReportsService.java b/src/main/java/com/guo/learningprogresstracker/service/StudyReportsService.java index e664b0e..1c76ab3 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/StudyReportsService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/StudyReportsService.java @@ -1,13 +1,11 @@ package com.guo.learningprogresstracker.service; -import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.baomidou.mybatisplus.extension.service.IService; +import com.guo.learningprogresstracker.entity.StudyReportsEntity; /** -* @author guo -* @description 针对表【study_reports(存储每次学习结束时的完整学习报告)】的数据库操作Service -* @createDate 2024-06-09 15:28:48 -*/ -public interface StudyReportsService extends IService { - -} + * @author guo + * @description 针对表【study_reports(存储每次学习结束时的完整学习报告)】的数据库操作Service + * @createDate 2024-06-09 15:28:48 + */ +public interface StudyReportsService extends IService {} diff --git a/src/main/java/com/guo/learningprogresstracker/service/StudySessionsService.java b/src/main/java/com/guo/learningprogresstracker/service/StudySessionsService.java index a62d278..ee0eec1 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/StudySessionsService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/StudySessionsService.java @@ -1,23 +1,21 @@ package com.guo.learningprogresstracker.service; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; import com.google.protobuf.ServiceException; import com.guo.learningprogresstracker.dto.response.StudySessionResponse; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.entity.StudySessionsEntity; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.IService; import com.guo.learningprogresstracker.exception.ErrorParameterException; - import java.time.LocalDateTime; import java.util.ArrayList; /** -* @author guo -* @description 针对表【study_sessions(记录每次学习会话的具体数据)】的数据库操作Service -* @createDate 2024-06-09 15:28:48 -*/ + * @author guo + * @description 针对表【study_sessions(记录每次学习会话的具体数据)】的数据库操作Service + * @createDate 2024-06-09 15:28:48 + */ public interface StudySessionsService extends IService { StudySessionResponse getNotEndedStudySessionByTaskNum(String taskNum) throws ErrorParameterException; diff --git a/src/main/java/com/guo/learningprogresstracker/service/TasksService.java b/src/main/java/com/guo/learningprogresstracker/service/TasksService.java index 9752228..0a0fe5c 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/TasksService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/TasksService.java @@ -13,15 +13,14 @@ import com.guo.learningprogresstracker.entity.TaskApplicationEntity; import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; - import java.rmi.ServerException; import java.util.List; /** -* @author guo -* @description 针对表【tasks(存储学习任务的基本信息,包括优先级的多维度计算)】的数据库操作Service -* @createDate 2024-06-09 15:28:48 -*/ + * @author guo + * @description 针对表【tasks(存储学习任务的基本信息,包括优先级的多维度计算)】的数据库操作Service + * @createDate 2024-06-09 15:28:48 + */ public interface TasksService extends IService { Page taskList(Integer pageNum, Integer pageSize); @@ -48,7 +47,8 @@ public interface TasksService extends IService { TaskApplicationEntity createApplication(CreateTaskApplicationRequest request) throws NotFindEntitiesException; - TaskApplicationEntity updateApplication(Integer id, UpdateTaskApplicationRequest request) throws NotFindEntitiesException; + TaskApplicationEntity updateApplication(Integer id, UpdateTaskApplicationRequest request) + throws NotFindEntitiesException; void deleteApplication(Integer id) throws NotFindEntitiesException; } diff --git a/src/main/java/com/guo/learningprogresstracker/service/UserService.java b/src/main/java/com/guo/learningprogresstracker/service/UserService.java index b738a5b..4bf0feb 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/UserService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/UserService.java @@ -1,17 +1,16 @@ package com.guo.learningprogresstracker.service; -import com.guo.learningprogresstracker.entity.UserEntity; import com.baomidou.mybatisplus.extension.service.IService; +import com.guo.learningprogresstracker.entity.UserEntity; import com.guo.learningprogresstracker.exception.AppException; - import java.util.Collection; import java.util.Map; /** -* @author guo -* @description 针对表【user(用户信息表)】的数据库操作Service -* @createDate 2024-06-09 15:28:48 -*/ + * @author guo + * @description 针对表【user(用户信息表)】的数据库操作Service + * @createDate 2024-06-09 15:28:48 + */ public interface UserService extends IService { /** diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiServiceClient.java similarity index 90% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiServiceClient.java index abb7cb5..dbeadea 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiServiceClient.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiServiceClient.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import cn.dev33.satoken.exception.SaTokenException; import cn.dev33.satoken.stp.StpUtil; @@ -9,11 +9,6 @@ import com.guo.learningprogresstracker.dto.MindMapFragmentPayload; import com.guo.learningprogresstracker.dto.MindMapReportContext; import com.guo.learningprogresstracker.dto.ReportSections; import jakarta.annotation.PostConstruct; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -24,6 +19,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * lpt-ai 独立 AI 服务客户端。 @@ -58,9 +57,8 @@ public class AiServiceClient { @PostConstruct void init() { - httpClient = HttpClient.newBuilder() - .connectTimeout(Duration.ofSeconds(10)) - .build(); + httpClient = + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); if (isConfigured()) { log.info("AiServiceClient 已配置: {} (超时 {}s, 异步任务模式)", url, timeoutSeconds); } else { @@ -114,10 +112,10 @@ public class AiServiceClient { Optional result = submitAndWait("aggregate-report", params); return result.map(r -> new ReportSections( - textOrNull(r, "sessionSummary"), - textOrNull(r, "expectationVerdict"), - textOrNull(r, "freeSummary") - )).filter(sections -> !sections.isEmpty()); + textOrNull(r, "sessionSummary"), + textOrNull(r, "expectationVerdict"), + textOrNull(r, "freeSummary"))) + .filter(sections -> !sections.isEmpty()); } catch (Exception e) { log.warn("lpt-ai 聚合报告异常,将降级: {}", e.getMessage()); return Optional.empty(); @@ -135,16 +133,20 @@ public class AiServiceClient { * @param fragments 该任务名下的知识碎片正文(按内容归属取),带可空的报告关联 * @param reports 碎片同源会话的学习报告,作为参考上下文(报告-02);由 LLM 按相关性决定是否采用 */ - public Optional generateMindMap(String taskName, String taskDescription, - List fragments, - List reports) { + public Optional generateMindMap( + String taskName, + String taskDescription, + List fragments, + List reports) { if (!isConfigured()) { return Optional.empty(); } try { - List> fragmentBodies = fragments == null ? List.of() + List> fragmentBodies = fragments == null + ? List.of() : fragments.stream().map(AiServiceClient::fragmentPayload).toList(); - List> reportBodies = reports == null ? List.of() + List> reportBodies = reports == null + ? List.of() : reports.stream().map(AiServiceClient::reportPayload).toList(); // 用 LinkedHashMap 而不是 Map.of:字段多于 10 个时 Map.of 会直接抛异常 @@ -208,8 +210,7 @@ public class AiServiceClient { Map params = Map.of( "taskName", taskName, "concept", concept, - "history", history != null ? history : List.of() - ); + "history", history != null ? history : List.of()); Optional result = submitAndWait("guidance", params); return result.map(r -> r.path("reply").asText(null)).filter(s -> s != null && !s.isBlank()); } catch (AiServiceTaskFailedException e) { @@ -221,27 +222,6 @@ public class AiServiceClient { } } - /** - * 调用 lpt-ai 进行语义化回忆对比。 - */ - public Optional compareRecall(String taskName, String standardOutline, String recallOutline) { - if (!isConfigured()) { - return Optional.empty(); - } - try { - Map params = Map.of( - "taskName", taskName, - "standardOutline", standardOutline, - "recallOutline", recallOutline - ); - - return submitAndWait("compare-recall", params); - } catch (Exception e) { - log.warn("lpt-ai 回忆对比异常,将降级为内置算法: {}", e.getMessage()); - return Optional.empty(); - } - } - // ============ 内部异步 submit + poll ============ /** 提交任务并同步等待结果(内部轮询,调用方无感知) */ @@ -276,9 +256,15 @@ public class AiServiceClient { HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 201) { - log.warn("lpt-ai 提交任务失败: type={}, status={}, body={}", - type, response.statusCode(), - response.body() != null ? response.body().substring(0, Math.min(200, response.body().length())) : ""); + log.warn( + "lpt-ai 提交任务失败: type={}, status={}, body={}", + type, + response.statusCode(), + response.body() != null + ? response.body() + .substring( + 0, Math.min(200, response.body().length())) + : ""); return null; } JsonNode json = objectMapper.readTree(response.body()); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskFailedException.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskFailedException.java similarity index 87% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskFailedException.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskFailedException.java index a552ad9..3da49d9 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskFailedException.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskFailedException.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; /** * AI 任务执行失败(AI-02):{@code message} 是给用户看的文案,技术细节由抛出方写日志。 diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskHandler.java similarity index 94% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskHandler.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskHandler.java index 84e0ab4..9290c2d 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskHandler.java @@ -1,8 +1,7 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; - import java.util.Map; /** diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskHandlerRegistry.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskHandlerRegistry.java similarity index 79% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskHandlerRegistry.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskHandlerRegistry.java index 274b7b7..ceb2b13 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskHandlerRegistry.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskHandlerRegistry.java @@ -1,16 +1,15 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - import java.util.EnumMap; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; /** * AI 任务处理器注册表(AI-02):按类型分发到具体实现。 @@ -28,8 +27,11 @@ public class AiTaskHandlerRegistry { for (AiTaskHandler handler : handlerList) { AiTaskHandler previous = handlers.put(handler.type(), handler); if (previous != null) { - log.warn("AI 任务类型 {} 有多个处理器,后注册的 {} 覆盖了 {}", - handler.type(), handler.getClass().getSimpleName(), previous.getClass().getSimpleName()); + log.warn( + "AI 任务类型 {} 有多个处理器,后注册的 {} 覆盖了 {}", + handler.type(), + handler.getClass().getSimpleName(), + previous.getClass().getSimpleName()); } } log.info("AI 任务处理器已注册: {}", handlers.keySet()); @@ -55,9 +57,11 @@ public class AiTaskHandlerRegistry { return Map.of(); } try { - return objectMapper.readValue(task.getRequestPayload(), new TypeReference>() { - }); + return objectMapper.readValue(task.getRequestPayload(), new TypeReference>() {}); } catch (Exception e) { + if ("RECALL_HINT".equals(task.getAiType()) || "RECALL_CHECK".equals(task.getAiType())) { + throw RecallAiFailure.forCode("AI_REQUEST_FAILED"); + } log.error("AI 任务[{}]参数解析失败", task.getTaskNum(), e); throw new AiTaskFailedException("这次请求的参数丢了,请重新发起"); } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskParams.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskParams.java similarity index 96% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskParams.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskParams.java index 87033ea..2b6c941 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskParams.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskParams.java @@ -1,6 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; - -import lombok.extern.slf4j.Slf4j; +package com.guo.learningprogresstracker.service.ai; import java.time.LocalDateTime; import java.time.format.DateTimeParseException; @@ -8,6 +6,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; /** * AI 任务参数的宽松读取(AI-02)。 @@ -18,8 +17,7 @@ import java.util.Map; @Slf4j final class AiTaskParams { - private AiTaskParams() { - } + private AiTaskParams() {} static String asString(Map params, String key) { Object value = params == null ? null : params.get(key); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskRunner.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskRunner.java similarity index 71% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskRunner.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskRunner.java index 5483f6a..ec3dff6 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskRunner.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiTaskRunner.java @@ -1,23 +1,21 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; +import com.guo.learningprogresstracker.common.TenantContext; import com.guo.learningprogresstracker.config.AiTaskConfig; import com.guo.learningprogresstracker.config.AiTaskProperties; -import com.guo.learningprogresstracker.common.TenantContext; import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.service.AiTaskService; import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent; +import java.util.List; +import java.util.Map; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.event.TransactionPhase; import org.springframework.transaction.event.TransactionalEventListener; -import java.util.List; -import java.util.Map; - /** * AI 任务执行器(AI-02)。 * @@ -57,7 +55,8 @@ public class AiTaskRunner { *

{@code initialDelayString} 让「立即投递」先跑:生产上延迟一个扫描周期即可, * 测试环境把它调大,保证自动扫描不会与用例互相干扰(用例直接调本方法)。

*/ - @Scheduled(fixedDelayString = "${lpt.ai-task.scan-interval-ms:3000}", + @Scheduled( + fixedDelayString = "${lpt.ai-task.scan-interval-ms:3000}", initialDelayString = "${lpt.ai-task.scan-initial-delay-ms:3000}") public void scanPendingTasks() { try { @@ -78,18 +77,44 @@ public class AiTaskRunner { */ private void executeClaimed(AiTaskEntity task) { try { - Map result = TenantContext.callAs(task.getCreatedBy(), task.getDeviceInfo(), - () -> handlerRegistry.execute(task)); + Map result = TenantContext.callAs( + task.getCreatedBy(), task.getDeviceInfo(), () -> handlerRegistry.execute(task)); aiTaskService.markSucceeded(task, result); - log.info("[AI 任务] 完成: taskNum={}, type={}, targetNum={}", - task.getTaskNum(), task.getAiType(), task.getTargetNum()); + log.info( + "[AI 任务] 完成: taskNum={}, type={}, targetNum={}", + task.getTaskNum(), + task.getAiType(), + task.getTargetNum()); } catch (AiTaskFailedException e) { - log.warn("[AI 任务] 失败: taskNum={}, type={}, 原因={}", - task.getTaskNum(), task.getAiType(), e.getMessage()); + if (isRecall(task)) { + failRecall(task, e); + return; + } + log.warn("[AI 任务] 失败: taskNum={}, type={}, 原因={}", task.getTaskNum(), task.getAiType(), e.getMessage()); aiTaskService.markFailed(task, e.getMessage()); } catch (Exception e) { + if (isRecall(task)) { + failRecall(task, e); + return; + } log.error("[AI 任务] 异常: taskNum={}, type={}", task.getTaskNum(), task.getAiType(), e); aiTaskService.markFailed(task, "生成失败了,请稍后再试"); } } + + private static boolean isRecall(AiTaskEntity task) { + return "RECALL_HINT".equals(task.getAiType()) || "RECALL_CHECK".equals(task.getAiType()); + } + + private void failRecall(AiTaskEntity task, Exception error) { + RecallAiFailure failure = RecallAiFailure.fromException(error); + task.setErrorCode(failure.getCode()); + // Log only the local diagnostic identifier and allowlisted classification, never provider text/stack. + log.warn( + "[AI 任务] 回忆失败: taskNum={}, type={}, errorCode={}", + task.getTaskNum(), + task.getAiType(), + failure.getCode()); + aiTaskService.markFailed(task, failure.getMessage()); + } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageClient.java b/src/main/java/com/guo/learningprogresstracker/service/ai/AiUsageClient.java similarity index 95% rename from src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageClient.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/AiUsageClient.java index 12c0e78..8144c6c 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageClient.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/AiUsageClient.java @@ -1,20 +1,19 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.config.AiUsageProperties; import com.guo.learningprogresstracker.dto.AiUsageBalance; -import lombok.RequiredArgsConstructor; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * lpt-ai 用量相关接口的客户端。 @@ -41,9 +40,8 @@ public class AiUsageClient { private final AiUsageProperties usageProperties; - private final HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(Duration.ofSeconds(10)) - .build(); + private final HttpClient httpClient = + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); private final ObjectMapper objectMapper = new ObjectMapper(); diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/BuiltinMindMapGenerator.java b/src/main/java/com/guo/learningprogresstracker/service/ai/BuiltinMindMapGenerator.java new file mode 100644 index 0000000..7dbb23e --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/BuiltinMindMapGenerator.java @@ -0,0 +1,193 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.guo.learningprogresstracker.dto.MindMapReportContext; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.TaskApplicationEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.service.MindMapAiClient; +import com.guo.learningprogresstracker.utils.MindMapNode; +import com.guo.learningprogresstracker.utils.MindMapTreeTool; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * 内置规则引擎:从知识碎片提取内容并组织为树形思维导图(AI 不可用时的降级路径)。 + * + *

素材按**内容归属**给:一个任务名下的碎片,而不是产生于该任务会话的报告。 + * 因此学 A 时记下但归属到 B 的旁支知识,会出现在 B 的导图里。

+ * + *

规则策略:

+ *
    + *
  1. 根节点 = 任务名称
  2. + *
  3. 一级分支 = 按记录上下文(日期 + 首条碎片摘要)分组
  4. + *
  5. 二级分支 = 该上下文下的碎片
  6. + *
  7. 附加分支"应用场景" = 任务应用场景(如有)
  8. + *
  9. 去重:标准化后标题对比,合并内容相似的节点
  10. + *
  11. 引用追溯:每个节点携带 sourceType / sourceId
  12. + *
+ */ +@Slf4j +@Component +public class BuiltinMindMapGenerator implements MindMapAiClient { + + private static final int MAX_TITLE_LENGTH = 60; + + @Override + public boolean isAvailable() { + return true; // 始终可用 + } + + @Override + public String generatorName() { + return "BUILTIN"; + } + + @Override + public Optional generate( + TaskEntity task, + List fragments, + List applications, + List reports, + String clientHint) { + // 报告是参考上下文,需要语义判断「是否与碎片强相关」才能采用;内置规则不做这种判断, + // 因此报告只在 AI 路径参与(报告-02)。 + if (fragments == null || fragments.isEmpty()) { + return Optional.empty(); + } + + MindMapNode root = new MindMapNode(task.getTaskName() != null ? task.getTaskName() : "学习任务"); + root.setNotes(task.getTaskDescription() != null ? task.getTaskDescription() : ""); + + appendContextBranches(root, fragments); + appendApplicationBranch(root, applications); + deduplicateChildren(root); + + log.info( + "BuiltinMindMapGenerator: 为任务[{}]生成导图,共 {} 个节点,{} 层", + task.getTaskNum(), + MindMapTreeTool.countNodes(root), + MindMapTreeTool.maxDepth(root)); + return Optional.of(root); + } + + /** 按记录上下文分组:同一次学习会话(或复习行为)产生的碎片归在一支下(碎片缺失上下文时不参与分组)。 */ + private static void appendContextBranches(MindMapNode root, List fragments) { + Map> fragmentsByContext = fragments.stream() + .filter(f -> f.getContextNum() != null) + .collect(Collectors.groupingBy( + StudyReportFragmentsEntity::getContextNum, LinkedHashMap::new, Collectors.toList())); + for (List contextFragments : fragmentsByContext.values()) { + root.getChildren().add(contextBranch(contextFragments)); + } + } + + /** 一个上下文分支:日期 + 首条碎片摘要作标题,其下挂该上下文的每条碎片。 */ + private static MindMapNode contextBranch(List contextFragments) { + // 分支标题:日期 + 第一条碎片的前 60 字 + StudyReportFragmentsEntity first = contextFragments.get(0); + String contextTitle = truncate(first.getContent(), MAX_TITLE_LENGTH); + if (first.getCreatedTime() != null) { + contextTitle = formatDate(first.getCreatedTime()) + " " + contextTitle; + } + + MindMapNode contextNode = new MindMapNode(contextTitle); + for (StudyReportFragmentsEntity fragment : contextFragments) { + String content = fragment.getContent(); + if (content == null || content.isBlank()) { + continue; + } + MindMapNode fragmentNode = new MindMapNode(truncate(content, MAX_TITLE_LENGTH)); + fragmentNode.setNotes(content); + fragmentNode.setSourceType("FRAGMENT"); + fragmentNode.setSourceId(fragment.getId()); + contextNode.getChildren().add(fragmentNode); + } + return contextNode; + } + + /** 应用场景分支(如有):没有可用标题的应用场景不建分支。 */ + private static void appendApplicationBranch(MindMapNode root, List applications) { + if (applications == null || applications.isEmpty()) { + return; + } + MindMapNode appNode = new MindMapNode("应用场景"); + for (TaskApplicationEntity app : applications) { + if (app.getTitle() == null || app.getTitle().isBlank()) { + continue; + } + MindMapNode child = new MindMapNode(app.getTitle()); + child.setNotes(app.getDescription() != null ? app.getDescription() : ""); + child.setSourceType("APPLICATION"); + child.setSourceId(app.getId()); + appNode.getChildren().add(child); + } + if (!appNode.getChildren().isEmpty()) { + root.getChildren().add(appNode); + } + } + + /** 同级节点按标准化标题去重 */ + private void deduplicateChildren(MindMapNode node) { + if (node.getChildren() == null || node.getChildren().isEmpty()) { + return; + } + + Map seen = new LinkedHashMap<>(); + for (MindMapNode child : node.getChildren()) { + String key = normalize(child.getTitle()); + seen.merge(key, child, (a, b) -> { + // 保留 notes 较长的那个 + if (b.getNotes() != null + && b.getNotes().length() + > (a.getNotes() != null ? a.getNotes().length() : 0)) { + a.setNotes(b.getNotes()); + } + // 合并子节点 + if (b.getChildren() != null) { + a.getChildren().addAll(b.getChildren()); + } + return a; + }); + } + node.setChildren(new ArrayList<>(seen.values())); + + for (MindMapNode child : node.getChildren()) { + deduplicateChildren(child); + } + } + + private static String normalize(String s) { + if (s == null) { + return ""; + } + return s.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", "") + .toLowerCase(Locale.ROOT) + .trim(); + } + + private static String truncate(String s, int maxLen) { + if (s == null) { + return ""; + } + if (s.length() <= maxLen) { + return s; + } + return s.substring(0, maxLen) + "…"; + } + + private static String formatDate(LocalDateTime dt) { + if (dt == null) { + return ""; + } + return dt.format(DateTimeFormatter.ofPattern("MM-dd")); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/GuidanceAiTaskHandler.java similarity index 97% rename from src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceAiTaskHandler.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/GuidanceAiTaskHandler.java index 666d368..0a9fc05 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceAiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/GuidanceAiTaskHandler.java @@ -1,5 +1,6 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.dto.ReviewTiming; import com.guo.learningprogresstracker.entity.AiTaskEntity; @@ -9,17 +10,15 @@ import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.service.GuidanceService; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - import java.time.LocalDateTime; import java.time.format.DateTimeParseException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; /** * 学习引导任务处理器(复习-06)。 @@ -88,7 +87,8 @@ public class GuidanceAiTaskHandler implements AiTaskHandler { } private String loadTaskName(String taskNum) { - return tasksMapper.selectOne(Wrappers.lambdaQuery() + return tasksMapper + .selectOne(Wrappers.lambdaQuery() .eq(TaskEntity::getTaskNum, taskNum) .select(TaskEntity::getTaskName) .last("LIMIT 1")) diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/MindMapAiTaskHandler.java similarity index 93% rename from src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/MindMapAiTaskHandler.java index 347f6a8..ee3bb5a 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapAiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/MindMapAiTaskHandler.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.entity.AiTaskEntity; @@ -9,13 +9,12 @@ 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 java.util.LinkedHashMap; +import java.util.Map; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -import java.util.LinkedHashMap; -import java.util.Map; - /** * 标准思维导图生成任务(AI-02)。 * @@ -62,8 +61,8 @@ public class MindMapAiTaskHandler implements AiTaskHandler { Map payload = new LinkedHashMap<>(); payload.put("standardMapId", entity.getId()); payload.put("generator", entity.getGenerator()); - payload.put("nodeCount", MindMapTreeTool.countNodes( - MindMapTreeTool.fromJson(entity.getContent(), objectMapper))); + 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/service/impl/MindMapOutlineGenerator.java b/src/main/java/com/guo/learningprogresstracker/service/ai/MindMapOutlineGenerator.java similarity index 87% rename from src/main/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGenerator.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/MindMapOutlineGenerator.java index 48b7734..3741f08 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGenerator.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/MindMapOutlineGenerator.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.dto.MindMapReportContext; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; @@ -7,13 +7,12 @@ 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; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; /** * 「碎片 → 缩进大纲」生成链路:优先 AI 客户端,失败时降级到内置规则生成器。 @@ -35,16 +34,17 @@ public class MindMapOutlineGenerator { * @param generatorName 生成来源标识({@code BUILTIN} / AI 客户端名);沿用首选客户端的标识, * 与既有任务导图口径一致 */ - public record GeneratedOutline(MindMapNode root, String generatorName) { - } + public record GeneratedOutline(MindMapNode root, String generatorName) {} /** * 生成导图树;没有任何可用生成器或全部生成失败时抛出用户可见的业务异常。 */ - public GeneratedOutline generate(TaskEntity scope, - List fragments, - List applications, - List reports) throws OperationFailedException { + public GeneratedOutline generate( + TaskEntity scope, + List fragments, + List applications, + List reports) + throws OperationFailedException { // 优先选 AI 客户端(非 BUILTIN),其次内置生成器:AI 提升结构质量,内置规则保证 AI 不可用时仍能生成 MindMapAiClient client = aiClients.stream() .filter(MindMapAiClient::isAvailable) @@ -60,7 +60,8 @@ public class MindMapOutlineGenerator { log.info("AI 思维导图生成失败,降级到内置生成器"); MindMapAiClient fallback = aiClients.stream() .filter(c -> GENERATOR_BUILTIN.equals(c.generatorName()) && c.isAvailable()) - .findFirst().orElse(null); + .findFirst() + .orElse(null); if (fallback != null) { optRoot = fallback.generate(scope, fragments, applications, reports, null); } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapReportContextLoader.java b/src/main/java/com/guo/learningprogresstracker/service/ai/MindMapReportContextLoader.java similarity index 89% rename from src/main/java/com/guo/learningprogresstracker/service/impl/MindMapReportContextLoader.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/MindMapReportContextLoader.java index 4554513..6696317 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/MindMapReportContextLoader.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/MindMapReportContextLoader.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.guo.learningprogresstracker.dto.MindMapReportContext; @@ -10,11 +10,6 @@ import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum; import com.guo.learningprogresstracker.mapper.StudyReportsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; import com.guo.learningprogresstracker.mapper.TasksMapper; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; @@ -23,6 +18,10 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; /** * 导图取材时的报告上下文装载(报告-02)。 @@ -64,10 +63,9 @@ public class MindMapReportContextLoader { } // 最近若干份(id 倒序),最后再翻回时间正序呈现,先记的在前 - List reports = studyReportsMapper.selectList( - Wrappers.lambdaQuery() - .in(StudyReportsEntity::getSessionNum, sessionNums) - .orderByDesc(StudyReportsEntity::getId)); + List reports = studyReportsMapper.selectList(Wrappers.lambdaQuery() + .in(StudyReportsEntity::getSessionNum, sessionNums) + .orderByDesc(StudyReportsEntity::getId)); if (reports.isEmpty()) { return List.of(); } @@ -100,8 +98,7 @@ public class MindMapReportContextLoader { /** 会话 → 所属任务名;任务被删除时缺省,交给 LLM 只看内容判断领域 */ private Map loadTaskNamesBySession(Set sessionNums) { List sessions = studySessionsMapper.selectList( - Wrappers.lambdaQuery() - .in(StudySessionsEntity::getSessionNum, sessionNums)); + Wrappers.lambdaQuery().in(StudySessionsEntity::getSessionNum, sessionNums)); if (sessions.isEmpty()) { return Map.of(); } @@ -109,9 +106,10 @@ public class MindMapReportContextLoader { .map(StudySessionsEntity::getTaskNum) .filter(StringUtils::hasText) .collect(Collectors.toSet()); - Map taskNameByNum = taskNums.isEmpty() ? Map.of() - : tasksMapper.selectList(Wrappers.lambdaQuery() - .in(TaskEntity::getTaskNum, taskNums)) + Map taskNameByNum = taskNums.isEmpty() + ? Map.of() + : tasksMapper + .selectList(Wrappers.lambdaQuery().in(TaskEntity::getTaskNum, taskNums)) .stream() .filter(task -> StringUtils.hasText(task.getTaskName())) .collect(Collectors.toMap(TaskEntity::getTaskNum, TaskEntity::getTaskName, (a, b) -> a)); diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiClient.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiClient.java new file mode 100644 index 0000000..10c84d2 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiClient.java @@ -0,0 +1,281 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.fasterxml.jackson.databind.JsonNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiParams; +import com.guo.learningprogresstracker.service.recall.ReviewRecallStore; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.function.BooleanSupplier; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** New recall types only. No fallback, no remote body/error logging. */ +@Component +@Slf4j +public class RecallAiClient { + private final RecallJson json; + private final String url; + private final String token; + private final int timeoutSeconds; + private final int hintTimeoutSeconds; + private final HttpClient http = + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); + + public RecallAiClient( + RecallJson json, + @Value("${lpt.ai-service.url:}") String url, + @Value("${lpt.ai-service.token:}") String token, + @Value("${lpt.ai-service.timeout-seconds:600}") int timeoutSeconds, + @Value("${lpt.ai-service.hint-timeout-seconds:70}") int hintTimeoutSeconds) { + this.json = json; + this.url = url; + this.token = token; + this.timeoutSeconds = timeoutSeconds; + this.hintTimeoutSeconds = hintTimeoutSeconds; + } + + public String submit(String type, RecallAiParams params, String key) { + if (url.isBlank()) { + throw new RecallAiFailure("AI_UNAVAILABLE", "AI 服务尚未配置,未进行语义检查;仍可写草稿、查看原文或结束"); + } + Map body = new LinkedHashMap<>(); + body.put("type", type); + body.put("params", params); + body.put("idempotencyKey", key); + body.put("force", false); + body.put("callerRef", ReviewRecallStore.user()); + try { + HttpResponse response = http.send( + request("/ai/tasks", 30) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json.write(body))) + .build(), + HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 201) { + throw httpFailure(response.statusCode()); + } + JsonNode node = parseResponse(response.body()); + JsonNode id = node.get("taskId"); + if (id == null + || !id.isTextual() + || id.asText().isBlank() + || id.asText().length() > 64) { + throw protocol(); + } + return id.asText(); + } catch (RecallAiFailure e) { + throw e; + } catch (HttpTimeoutException e) { + throw timeout(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw unavailable(); + } catch (Exception e) { + log.warn("New recall submit failed: diagnostic={}", e.getClass().getSimpleName()); + throw unavailable(); + } + } + /** 查漏仍可用较长的总预算;提示必须按 60s 目标在服务端截止。 */ + public JsonNode awaitHint(String id, BooleanSupplier readable) { + return await(id, readable, hintTimeoutSeconds); + } + + public JsonNode await(String id, BooleanSupplier readable) { + return await(id, readable, timeoutSeconds); + } + + private JsonNode await(String id, BooleanSupplier readable, int seconds) { + Instant deadline = Instant.now().plusSeconds(seconds); + while (Instant.now().isBefore(deadline)) { + requireReadable(id, readable); + JsonNode result = pollOnce(id); + if (result != null) { + return result; + } + pausePoll(); + } + throw timeout(); + } + + /** redaction 后的任务不再轮询,也不能把远端结果留在那里。 */ + private void requireReadable(String id, BooleanSupplier readable) { + if (!readable.getAsBoolean()) { + purge(id); + throw redacted(); + } + } + + /** 一次轮询:done 返回结果,pending/running 返回 null 继续等,其它状态直接抛错。 */ + private JsonNode pollOnce(String id) { + try { + HttpResponse response = + http.send(request("/ai/tasks/" + id, 10).GET().build(), HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() == 404) { + throw unavailable(); + } + if (response.statusCode() != 200) { + throw httpFailure(response.statusCode()); + } + JsonNode node = parseResponse(response.body()); + switch (node.path("status").asText()) { + case "done": + return doneResult(node); + case "failed": + RecallAiFailure failure = remoteFailure(node); + log.warn("New recall remote failure: taskId={}, classification={}", id, failure.getCode()); + throw failure; + case "pending": + case "running": + return null; + default: + throw protocol(); + } + } catch (RecallAiFailure e) { + throw e; + } catch (HttpTimeoutException e) { + throw timeout(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw unavailable(); + } catch (Exception e) { + log.warn("New recall poll failed: diagnostic={}", e.getClass().getSimpleName()); + throw unavailable(); + } + } + + private static JsonNode doneResult(JsonNode node) { + JsonNode result = node.get("result"); + if (result == null || !result.isObject() || result.isEmpty()) { + throw protocol(); + } + return result; + } + + private static void pausePoll() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw unavailable(); + } + } + + private JsonNode parseResponse(String body) { + try { + JsonNode node = json.tree(json.readStored(body, Object.class)); + if (!node.isObject()) { + throw protocol(); + } + return node; + } catch (RuntimeException e) { + throw protocol(); + } + } + + private static final java.util.Set RECALL_REASONS = + java.util.Set.of("结构与字段", "分析判定", "提示结构", "查漏依据", "表达依据", "分析覆盖", "输出长度", "不是有效 JSON"); + private static final java.util.regex.Pattern RECALL_REASON = java.util.regex.Pattern.compile("(未通过:([^)]{1,40}))"); + + private static RecallAiFailure remoteFailure(JsonNode node) { + RecallAiFailure failure = RecallAiFailure.forCode(node.path("errorCode").asText()); + if ("INVALID_AI_RESULT".equals(failure.getCode())) { + String error = node.path("error").asText(""); + var matcher = RECALL_REASON.matcher(error); + if (matcher.find()) { + // 失败原因可能是「阶段:字段」,只取阶段,字段名不进用户文案 + String phase = matcher.group(1).split(":", 2)[0]; + if (RECALL_REASONS.contains(phase)) { + return RecallAiFailure.safe("INVALID_AI_RESULT", "这次 AI 回应未通过核验(" + phase + "),本次未产出结果"); + } + } + } + if (!"AI_REQUEST_FAILED".equals(failure.getCode())) { + return failure; + } + // Older services supplied AI_REQUEST_FAILED(category) or an HTTP status prefix. + // Do not infer a diagnosis from words/numbers inside provider text, which may echo user content. + String error = node.path("error").asText("").trim().toLowerCase(Locale.ROOT); + String category = error; + if (error.startsWith("ai_request_failed(") && error.endsWith(")")) { + category = error.substring("ai_request_failed(".length(), error.length() - 1); + } + String code = switch (category) { + case "timeout", "ai_timeout" -> "AI_TIMEOUT"; + case "auth", "auth_failed", "authentication_error", "ai_auth_failed" -> "AI_AUTH_FAILED"; + case "quota", "insufficient_quota", "ai_quota_exceeded" -> "AI_QUOTA_EXCEEDED"; + case "rate_limited", "rate_limit", "ai_rate_limited" -> "AI_RATE_LIMITED"; + default -> null; + }; + if (code != null) { + return RecallAiFailure.forCode(code); + } + var status = java.util.regex.Pattern.compile("^(?:http\\s+)?(401|403|402|429|408|504)\\b") + .matcher(error); + return status.find() ? httpFailure(Integer.parseInt(status.group(1))) : failure; + } + + public boolean purge(String id) { + try { + HttpResponse response = + http.send(request("/ai/tasks/" + id, 10).DELETE().build(), HttpResponse.BodyHandlers.discarding()); + if (response.statusCode() == 204 || response.statusCode() == 404) { + return true; + } + log.error( + "New recall remote purge failed: taskId={}, status={} (BE already redacted)", + id, + response.statusCode()); + } catch (Exception e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + log.error( + "New recall remote purge failed: taskId={}, diagnostic={} (BE already redacted)", + id, + e.getClass().getSimpleName()); + } + return false; + } + + private HttpRequest.Builder request(String path, int seconds) { + return HttpRequest.newBuilder(URI.create(url + path)) + .timeout(Duration.ofSeconds(seconds)) + .header("x-api-token", token); + } + + private static RecallAiFailure httpFailure(int status) { + return RecallAiFailure.forCode( + switch (status) { + case 401, 403 -> "AI_AUTH_FAILED"; + case 402 -> "AI_QUOTA_EXCEEDED"; + case 429 -> "AI_RATE_LIMITED"; + case 408, 504 -> "AI_TIMEOUT"; + default -> status >= 500 ? "AI_UNAVAILABLE" : "AI_REQUEST_FAILED"; + }); + } + + private static RecallAiFailure unavailable() { + return RecallAiFailure.forCode("AI_UNAVAILABLE"); + } + + private static RecallAiFailure timeout() { + return RecallAiFailure.forCode("AI_TIMEOUT"); + } + + private static RecallAiFailure protocol() { + return RecallAiFailure.forCode("INVALID_AI_RESULT"); + } + + private static RecallAiFailure redacted() { + return RecallAiFailure.forCode("SOURCE_REDACTED"); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiFailure.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiFailure.java new file mode 100644 index 0000000..6250964 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiFailure.java @@ -0,0 +1,64 @@ +package com.guo.learningprogresstracker.service.ai; + +import java.net.http.HttpTimeoutException; +import java.util.Map; +import lombok.Getter; + +/** The new recall pipeline only persists these codes and fixed, content-free messages. */ +@Getter +public class RecallAiFailure extends AiTaskFailedException { + private static final Map MESSAGES = Map.ofEntries( + Map.entry("AI_UNAVAILABLE", "AI 服务暂时不可用,未进行语义检查;草稿不受影响"), + Map.entry("AI_TIMEOUT", "AI 等待超时,未进行语义检查;请保留草稿并稍后重试"), + Map.entry("AI_REQUEST_FAILED", "AI 请求失败,未进行语义检查;草稿不受影响,请稍后重试"), + Map.entry("INVALID_AI_RESULT", "AI 回应多次未通过格式或引用核验,本次未产出结果;可稍后再试"), + Map.entry("SOURCE_REDACTED", "资料已清除,这次 AI 结果不再展示"), + Map.entry("AI_AUTH_FAILED", "AI 鉴权失败,未进行语义检查;请联系管理员检查配置"), + Map.entry("AI_QUOTA_EXCEEDED", "AI 额度不足,未进行语义检查;仍可保存草稿并稍后重试"), + Map.entry("AI_RATE_LIMITED", "AI 请求受限,未进行语义检查;请稍后重试"), + Map.entry("AI_OUTPUT_LIMIT", "AI 输出达到上限,本次未完成语义检查;请保留草稿并缩小分析范围后重试"), + Map.entry("AI_EMPTY_RESPONSE", "AI 没有返回可用内容,未进行语义检查;请保留草稿并稍后重试"), + Map.entry("NO_REFERENCE", "资料不足,未进行语义检查;仍可写草稿、查看原文或结束"), + Map.entry("INSUFFICIENT_REFERENCE", "资料不足,未进行语义检查;仍可写草稿、查看原文或结束"), + Map.entry("INPUT_TOO_LARGE", "表达或已显示帮助超过本次分析上限,请保留草稿并缩小新回忆范围")); + + private final String code; + private final boolean userSafe; + + public RecallAiFailure(String code, String message) { + this(code, message, false); + } + + private RecallAiFailure(String code, String message, boolean userSafe) { + super(message); + this.code = code; + this.userSafe = userSafe; + } + + /** Only allowlisted validator/client reasons may reach the user; arbitrary exception text never does. */ + public static RecallAiFailure safe(String code, String message) { + return new RecallAiFailure(code, message, true); + } + + public static RecallAiFailure forCode(String code) { + String safeCode = code != null && MESSAGES.containsKey(code) ? code : "AI_REQUEST_FAILED"; + return new RecallAiFailure(safeCode, MESSAGES.get(safeCode)); + } + + /** Framework wrappers must not erase a typed failure; unknown exceptions stay unknown request failures. */ + public static RecallAiFailure fromException(Throwable error) { + Throwable current = error; + for (int depth = 0; current != null && depth < 16; depth++, current = current.getCause()) { + if (current instanceof RecallAiFailure failure) { + String message = failure.getMessage(); + return failure.isUserSafe() && message != null && !message.isBlank() && message.length() <= 240 + ? failure + : forCode(failure.getCode()); + } + if (current instanceof HttpTimeoutException) { + return forCode("AI_TIMEOUT"); + } + } + return forCode("AI_REQUEST_FAILED"); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiResultValidator.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiResultValidator.java new file mode 100644 index 0000000..31061fb --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiResultValidator.java @@ -0,0 +1,143 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.fasterxml.jackson.databind.JsonNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiExpressionNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiReferenceUnit; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Citation; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ExpressionEvidence; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Finding; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.HintItem; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiParams; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiResult; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +/** + * AI 结果进入本服务存储前的唯一复核点:引文是否真的来自本次输入。 + * + *

结构、条数上限、字段枚举、提示树形状、锚点存在性和分析状态归一都由 lpt-ai 的 + * {@code normalizeRecallResult} 负责,本服务不再重复一遍——两套规则分叉只会互相误杀。 + * 这里只守一件事:模型声称的引用,必须能在本次提交的原文里按偏移逐字取回。 + * 本服务是落库与展示的边界,这条防线必须由本服务自己持有。

+ */ +@Component +@RequiredArgsConstructor +public class RecallAiResultValidator { + private final RecallJson json; + + public RecallAiResult validate(JsonNode raw, RecallAiParams input, ReferenceSnapshot full) { + RecallAiResult result; + try { + result = json.readAiResult(raw, RecallAiResult.class); + } catch (RuntimeException e) { + throw mismatch("结构与字段"); + } + Map units = new HashMap<>(); + // 本次送入 AI 的资料,加上本次落库的完整资料,共同构成可引用范围。 + input.units().forEach(u -> units.put(u.unitId(), u)); + for (ReferenceUnit u : full.units()) { + if (u.text() != null) { + units.putIfAbsent( + u.unitId(), + new AiReferenceUnit( + u.unitId(), + u.sourceId(), + null, + u.role(), + null, + u.start(), + u.end(), + u.text(), + List.of())); + } + } + Map nodes = new HashMap<>(); + if (input.expression() != null) { + collect(input.expression().root(), nodes); + } + + for (HintItem hint : list(result.hints())) { + for (Citation c : list(hint.citations())) { + verify(c, units); + } + } + for (Finding finding : list(result.findings())) { + for (Citation c : list(finding.citations())) { + verify(c, units); + } + for (ExpressionEvidence e : list(finding.expressionEvidence())) { + verify(e, nodes); + } + } + return result; + } + + /** A citation must reproduce the submitted text exactly, at an offset that never splits a surrogate pair. */ + private static void verify(Citation c, Map units) { + AiReferenceUnit u = c == null ? null : units.get(c.unitId()); + if (u == null + || u.text() == null + || c.quote() == null + || c.quote().isEmpty() + || c.start() < u.start() + || c.end() > u.end() + || c.start() >= c.end() + || !slice(u.text(), c.start() - u.start(), c.end() - u.start()).equals(c.quote())) { + throw mismatch("查漏依据"); + } + } + + private static void verify(ExpressionEvidence e, Map nodes) { + AiExpressionNode n = e == null ? null : nodes.get(e.nodeId()); + if (n == null || !("TITLE".equals(e.field()) || "NOTES".equals(e.field()))) { + throw mismatch("表达依据"); + } + String text = "TITLE".equals(e.field()) ? n.title() : n.notes(); + if (text == null + || e.quote() == null + || e.quote().isEmpty() + || e.start() < 0 + || e.end() > text.length() + || e.start() >= e.end() + || !slice(text, e.start(), e.end()).equals(e.quote())) { + throw mismatch("表达依据"); + } + } + + /** 只有两端都落在真实字符边界时才返回切片;否则返回一个不可能被引文命中的标记。 */ + private static String slice(String text, int start, int end) { + if (start < 0 || end > text.length() || start >= end || !boundary(text, start) || !boundary(text, end)) { + return "\u0000"; + } + return text.substring(start, end); + } + + private static boolean boundary(String s, int offset) { + return offset == 0 + || offset == s.length() + || !(Character.isHighSurrogate(s.charAt(offset - 1)) && Character.isLowSurrogate(s.charAt(offset))); + } + + private static void collect(AiExpressionNode n, Map nodes) { + if (n == null || n.id() == null) { + return; + } + nodes.put(n.id(), n); + for (AiExpressionNode child : list(n.children())) { + collect(child, nodes); + } + } + + private static List list(List value) { + return value == null ? List.of() : value; + } + + private static RecallAiFailure mismatch(String phase) { + return RecallAiFailure.safe("INVALID_AI_RESULT", "这次 AI 回应未通过核验(" + phase + "),本次未产出结果"); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiService.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiService.java new file mode 100644 index 0000000..080ea41 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallAiService.java @@ -0,0 +1,344 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.AiTaskResponse; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiExpression; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiExpressionNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiParams; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiReferenceUnit; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.AiScope; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Expression; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ExpressionNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Limits; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiParams; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiResult; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDocument; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSource; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceUnit; +import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest; +import com.guo.learningprogresstracker.entity.AiTaskEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallReceiptEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallRequestEntity; +import com.guo.learningprogresstracker.mapper.AiTaskMapper; +import com.guo.learningprogresstracker.mapper.ReviewRecallRequestMapper; +import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent; +import com.guo.learningprogresstracker.service.recall.ReviewRecallStore; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class RecallAiService { + private static final String PROMPT_VERSION = "recall-v1"; + private final ReviewRecallStore store; + private final ReviewRecallRequestMapper requests; + private final AiTaskMapper tasks; + private final RecallJson json; + private final RecallAiResultValidator validator; + private final ApplicationEventPublisher events; + + @Transactional(rollbackFor = Exception.class) + public AiTaskResponse submit(AiTaskSubmitRequest r) { + store.lock(); + RecallDocument doc = store.load(r.getTargetNum()); + AiParams params = requestParams(r); + Object payload = List.of(r.getType(), r.getTargetNum(), params); + AiTaskResponse replayed = replayedResponse(r.getTargetNum(), params.requestId(), payload); + if (replayed != null) { + return replayed; + } + RecallDetail detail = doc.getDetail(); + store.guard(detail, params.editorId(), params.writeToken()); + store.validScope(doc); + validateRequestType(r, params); + AiTaskEntity task = AiTaskEntity.initNewTask(r.getType(), detail.getRecallNum(), json.write(params)); + task.setTaskNum("AITASK-" + UUID.randomUUID()); + RecallAiParams aiParams = null; + try { + aiParams = bounded(doc, params.hintForm()); + boolean knowledge = aiParams.units().stream().anyMatch(u -> !"APPLICATION".equals(u.sourceType())); + if (!knowledge) { + task.setStatus("FAILED"); + task.setErrorCode(doc.getReference().sources().isEmpty() ? "NO_REFERENCE" : "INSUFFICIENT_REFERENCE"); + task.setErrorMessage("资料不足,未进行语义检查;仍可写草稿、查看原文或结束"); + task.setFinishedTime(LocalDateTime.now()); + } + } catch (RecallAiFailure failure) { + task.setStatus("FAILED"); + task.setErrorCode(failure.getCode()); + task.setErrorMessage(failure.getMessage()); + task.setFinishedTime(LocalDateTime.now()); + } + tasks.insert(task); + ReviewRecallRequestEntity association = new ReviewRecallRequestEntity(); + association.setRecallNum(detail.getRecallNum()); + association.setTaskNum(task.getTaskNum()); + association.setParamsJson( + aiParams == null || !"PENDING".equals(task.getStatus()) ? null : json.write(aiParams)); + association.setRedacted(0); + requests.insert(association); + if ("PENDING".equals(task.getStatus())) { + events.publishEvent(new AiTaskSubmittedEvent(task.getId())); + } + List all = new ArrayList<>(detail.getRequests()); + all.add(new RecallRequest( + params.requestId(), + task.getTaskNum(), + r.getType(), + params.hintForm(), + PROMPT_VERSION, + task.getStatus(), + task.getErrorCode(), + task.getErrorMessage(), + Instant.now(), + null, + null)); + detail.setRequests(all); + store.persist(doc); + store.receipt(detail.getRecallNum(), "AI", params.requestId(), payload, task.getTaskNum()); + return response(task); + } + + /** 读入并校验客户端参数:版本不符说明前端拿的是旧文档。 */ + private AiParams requestParams(AiTaskSubmitRequest r) { + AiParams params = json.readInput(json.tree(r.getParams()), AiParams.class); + if (params.schemaVersion() != 1) { + throw new com.guo.learningprogresstracker.exception.RecallBusinessException( + "INVALID_INPUT", "请重新打开回忆后再请求提示"); + } + return params; + } + + /** 同一提交编号已经落过回执:直接回放那次结果,不重复建任务。 */ + private AiTaskResponse replayedResponse(String targetNum, String requestId, Object payload) { + ReviewRecallReceiptEntity replay = store.replay(targetNum, "AI", requestId, payload); + return replay == null ? null : response(store.task(replay.getTaskNum())); + } + + /** 提示必须选形式,内容查漏不能带形式。 */ + private static void validateRequestType(AiTaskSubmitRequest r, AiParams params) { + boolean hint = "RECALL_HINT".equals(r.getType()); + if ((!hint && !"RECALL_CHECK".equals(r.getType())) + || (hint + && !Set.of("KEYWORD", "QUESTION", "LEAF", "TREE") + .contains(params.hintForm() == null ? "" : params.hintForm())) + || (!hint && params.hintForm() != null)) { + throw new com.guo.learningprogresstracker.exception.RecallBusinessException( + "INVALID_INPUT", "请选择提示形式或内容查漏"); + } + } + + private RecallAiParams bounded(RecallDocument doc, String hintForm) { + RecallDetail detail = doc.getDetail(); + ReferenceSnapshot reference = doc.getReference(); + Map sources = new HashMap<>(); + reference.sources().forEach(s -> sources.put(s.sourceId(), s)); + List ordered = reference.units().stream() + .filter(u -> u.text() != null && "AVAILABLE".equals(u.status())) + .sorted(Comparator.comparing((ReferenceUnit u) -> "PRIMARY".equals(u.role()) ? 0 : 1) + .thenComparing(ReferenceUnit::sourceId) + .thenComparingInt(ReferenceUnit::start)) + .toList(); + if (ordered.size() > 40 + || ordered.stream().mapToInt(u -> u.text().length()).sum() > 12000) { + throw new RecallAiFailure("INPUT_TOO_LARGE", "本次资料超出 AI 分析范围,请缩小标签范围后重新开始"); + } + List units = ordered.stream() + .map(u -> { + ReferenceSource source = sources.get(u.sourceId()); + return new AiReferenceUnit( + u.unitId(), + u.sourceId(), + source.type(), + u.role(), + source.title(), + u.start(), + u.end(), + u.text(), + source.relatedFragmentSourceIds()); + }) + .toList(); + RecallAiParams input = new RecallAiParams( + 1, + PROMPT_VERSION, + new AiScope( + detail.getScope().type(), + detail.getScope().displayName(), + detail.getScope().tags(), + detail.getScope().combineMode()), + semanticExpression(detail.getExpression()), + hintForm, + units, + new Limits(3, 5, 12), + reference.limitations()); + if (json.write(input).getBytes(StandardCharsets.UTF_8).length > 200 * 1024) { + throw new RecallAiFailure("INPUT_TOO_LARGE", "本次导图、资料或已显示提示超过 AI 分析上限,请缩小范围或精简导图"); + } + return input; + } + /** Node colors are presentation only; the model receives the same IDs/tree without style fields. */ + private static AiExpression semanticExpression(Expression expression) { + return new AiExpression(1, semanticNode(expression.root())); + } + + private static AiExpressionNode semanticNode(ExpressionNode node) { + return new AiExpressionNode( + node.id(), + node.title(), + node.notes(), + node.provenance(), + node.children().stream().map(RecallAiService::semanticNode).toList()); + } + + @Transactional(rollbackFor = Exception.class) + public RecallAiParams prepare(String taskNum) { + store.lock(); + ReviewRecallRequestEntity req = require(taskNum); + store.load(req.getRecallNum()); + req = require(taskNum); + return json.readStored(req.getParamsJson(), RecallAiParams.class); + } + + @Transactional(rollbackFor = Exception.class) + public String remoteKey(String taskNum) { + store.lock(); + require(taskNum); + return RecallJson.hash(taskNum); + } + + @Transactional(rollbackFor = Exception.class) + public String remoteId(String taskNum) { + store.lock(); + return require(taskNum).getRemoteTaskId(); + } + + @Transactional(rollbackFor = Exception.class) + public boolean bindRemote(String taskNum, String remoteId) { + store.lock(); + ReviewRecallRequestEntity req = store.request(taskNum); + if (req == null || Integer.valueOf(1).equals(req.getRedacted())) { + store.purgeAfterCommit(remoteId); + return false; + } + requests.update( + null, + Wrappers.lambdaUpdate() + .eq(ReviewRecallRequestEntity::getId, req.getId()) + .set(ReviewRecallRequestEntity::getRemoteTaskId, remoteId)); + return true; + } + + @Transactional(rollbackFor = Exception.class) + public boolean readable(String taskNum) { + store.lock(); + ReviewRecallRequestEntity req = store.request(taskNum); + if (req == null || Integer.valueOf(1).equals(req.getRedacted())) { + return false; + } + try { + store.load(req.getRecallNum()); + return !Integer.valueOf(1).equals(store.request(taskNum).getRedacted()); + } catch (com.guo.learningprogresstracker.exception.RecallBusinessException e) { + return false; + } + } + + @Transactional(rollbackFor = Exception.class) + public void succeed(AiTaskEntity task, Map result) { + store.lock(); + ReviewRecallRequestEntity req = require(task.getTaskNum()); + RecallDocument doc = store.load(req.getRecallNum()); + req = require(task.getTaskNum()); + RecallAiParams input = json.readStored(req.getParamsJson(), RecallAiParams.class); + RecallAiResult checked = validator.validate(json.tree(result), input, doc.getReference()); + task.setStatus("SUCCEEDED"); + task.setResultPayload(json.write(checked)); + task.setErrorMessage(null); + task.setErrorCode(null); + task.setFinishedTime(LocalDateTime.now()); + if (tasks.finishRecallTask(task) > 0) { + clearParams(task.getTaskNum()); + } + } + + @Transactional(rollbackFor = Exception.class) + public void fail(AiTaskEntity task, String message) { + store.lock(); + ReviewRecallRequestEntity req = store.request(task.getTaskNum()); + if (req == null || Integer.valueOf(1).equals(req.getRedacted())) { + return; + } + RecallAiFailure failure = RecallAiFailure.forCode(task.getErrorCode()); + String reason = message == null || message.isBlank() || message.length() > 240 ? failure.getMessage() : message; + task.setStatus("FAILED"); + task.setResultPayload(null); + task.setErrorMessage(reason); + task.setErrorCode(failure.getCode()); + task.setFinishedTime(LocalDateTime.now()); + if (tasks.finishRecallTask(task) > 0) { + clearParams(task.getTaskNum()); + } + } + + private void clearParams(String taskNum) { + ReviewRecallRequestEntity req = store.request(taskNum); + if (req != null) { + requests.update( + null, + Wrappers.lambdaUpdate() + .eq(ReviewRecallRequestEntity::getId, req.getId()) + .set(ReviewRecallRequestEntity::getParamsJson, null)); + } + } + + @Transactional(rollbackFor = Exception.class) + public AiTaskResponse get(AiTaskEntity task) { + store.lock(); + store.load(task.getTargetNum()); + return response(store.task(task.getTaskNum())); + } + + private AiTaskResponse response(AiTaskEntity task) { + if (task == null) { + throw new RecallAiFailure("AI_UNAVAILABLE", "这次 AI 结果已不可用"); + } + Map result = null; + if ("SUCCEEDED".equals(task.getStatus())) { + try { + RecallAiResult typed = json.readStored(task.getResultPayload(), RecallAiResult.class); + result = new com.fasterxml.jackson.databind.ObjectMapper() + .convertValue( + json.tree(typed), + new com.fasterxml.jackson.core.type.TypeReference>() {}); + } catch (RuntimeException e) { + task.setStatus("FAILED"); + task.setErrorCode("AI_UNAVAILABLE"); + task.setErrorMessage("这次 AI 结果是旧版本格式,暂时无法展示;请重新请求。"); + } + } + return AiTaskResponse.from(task, result); + } + + private ReviewRecallRequestEntity require(String taskNum) { + ReviewRecallRequestEntity req = store.request(taskNum); + if (req == null || Integer.valueOf(1).equals(req.getRedacted()) || req.getParamsJson() == null) { + throw new RecallAiFailure("SOURCE_REDACTED", "资料已清除,这次 AI 结果不再展示"); + } + return req; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallCheckAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallCheckAiTaskHandler.java new file mode 100644 index 0000000..0ae180c --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallCheckAiTaskHandler.java @@ -0,0 +1,39 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiParams; +import com.guo.learningprogresstracker.entity.AiTaskEntity; +import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class RecallCheckAiTaskHandler implements AiTaskHandler { + private final RecallAiService service; + private final RecallAiClient client; + private final ObjectMapper mapper; + + @Override + public AiTaskTypeEnum type() { + return AiTaskTypeEnum.RECALL_CHECK; + } + + @Override + public Map execute(AiTaskEntity task, Map ignored) { + RecallAiParams input = service.prepare(task.getTaskNum()); + String id = service.remoteId(task.getTaskNum()); + if (id == null) { + String key = service.remoteKey(task.getTaskNum()); + id = client.submit("recall-check", input, key); + if (!service.bindRemote(task.getTaskNum(), id)) { + throw new RecallAiFailure("SOURCE_REDACTED", "资料已清除,这次 AI 结果不再展示"); + } + } + return mapper.convertValue( + client.await(id, () -> service.readable(task.getTaskNum())), + new TypeReference>() {}); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallHintAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallHintAiTaskHandler.java new file mode 100644 index 0000000..9149d2c --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallHintAiTaskHandler.java @@ -0,0 +1,39 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiParams; +import com.guo.learningprogresstracker.entity.AiTaskEntity; +import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class RecallHintAiTaskHandler implements AiTaskHandler { + private final RecallAiService service; + private final RecallAiClient client; + private final ObjectMapper mapper; + + @Override + public AiTaskTypeEnum type() { + return AiTaskTypeEnum.RECALL_HINT; + } + + @Override + public Map execute(AiTaskEntity task, Map ignored) { + RecallAiParams input = service.prepare(task.getTaskNum()); + String id = service.remoteId(task.getTaskNum()); + if (id == null) { + String key = service.remoteKey(task.getTaskNum()); + id = client.submit("recall-hint", input, key); + if (!service.bindRemote(task.getTaskNum(), id)) { + throw new RecallAiFailure("SOURCE_REDACTED", "资料已清除,这次 AI 结果不再展示"); + } + } + return mapper.convertValue( + client.awaitHint(id, () -> service.readable(task.getTaskNum())), + new TypeReference>() {}); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/ai/RecallJson.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallJson.java new file mode 100644 index 0000000..4f79ef9 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RecallJson.java @@ -0,0 +1,86 @@ +package com.guo.learningprogresstracker.service.ai; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import org.springframework.stereotype.Component; + +/** + * 回忆链路的 JSON 出入口。 + * + *

{@link #write} 同时产出落盘文档和幂等摘要({@code receipt_key} / {@code payload_hash}), + * 序列化配置一改,既有收据的摘要就全部失配,所以这里只允许调整反序列化行为。

+ * + *

结构契约由产出方自己保证:前端请求的结构由本服务的 DTO 定义,AI 结果的结构由 lpt-ai 的 + * {@code normalizeRecallResult} 校验。本类不再重复"字段是否齐全"的防御。

+ */ +@Component +public class RecallJson { + /** 序列化与落盘读取:完全沿用历史配置,保证摘要可比。 */ + private final ObjectMapper mapper; + /** 外部请求:拒绝未知字段、拒绝标量与浮点强转,但不要求可选字段必须出现。 */ + private final ObjectMapper inputMapper; + + public RecallJson(ObjectMapper mapper) { + // FAIL_ON_MISSING_CREATOR_PROPERTIES 会把 record 的可选组件变成必填(前端省略 style 时整单 400), + // 而真正的必填字段已由 service 校验,因此只对外部请求关闭这一项。 + this.mapper = mapper.copy() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + this.inputMapper = mapper.copy() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT); + } + /** 外部输入(HTTP 请求体):结构与类型不符即拒绝,缺可选字段不算错误。 */ + public T readInput(JsonNode node, Class type) { + try { + return inputMapper.treeToValue(node, type); + } catch (Exception e) { + throw new RecallBusinessException("INVALID_INPUT", "这些内容没能读取,请保留输入并重新打开页面"); + } + } + /** 存储读取:形状由写入方保证,读不出来就按损坏数据交给调用方删除。 */ + public T readStored(String text, Class type) { + try { + return mapper.readValue(text, type); + } catch (Exception e) { + throw new IllegalStateException("Stored recall data is invalid"); + } + } + /** AI 结果映射:结构由 lpt-ai 的严格解析器保证,这里只做 JSON→DTO 转换。 */ + public T readAiResult(JsonNode node, Class type) { + try { + return mapper.treeToValue(node, type); + } catch (Exception e) { + throw new IllegalStateException("AI result does not match the agreed structure"); + } + } + + public String write(Object value) { + try { + return mapper.writeValueAsString(value); + } catch (Exception e) { + throw new IllegalStateException("Recall serialization failed"); + } + } + + public JsonNode tree(Object value) { + return mapper.valueToTree(value); + } + + public static String hash(String text) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (Exception e) { + throw new IllegalStateException("SHA-256 unavailable"); + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/RemoteAiMindMapClient.java b/src/main/java/com/guo/learningprogresstracker/service/ai/RemoteAiMindMapClient.java similarity index 78% rename from src/main/java/com/guo/learningprogresstracker/service/impl/RemoteAiMindMapClient.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/RemoteAiMindMapClient.java index ea2a542..a8e1a5b 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/RemoteAiMindMapClient.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/RemoteAiMindMapClient.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.dto.MindMapFragmentPayload; import com.guo.learningprogresstracker.dto.MindMapReportContext; @@ -9,15 +9,14 @@ import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum; import com.guo.learningprogresstracker.service.MindMapAiClient; import com.guo.learningprogresstracker.utils.MindMapNode; import com.guo.learningprogresstracker.utils.MindMapTreeTool; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; /** * 远程 AI 思维导图生成客户端。 @@ -42,11 +41,12 @@ public class RemoteAiMindMapClient implements MindMapAiClient { } @Override - public Optional generate(TaskEntity task, - List fragments, - List applications, - List reports, - String clientHint) { + public Optional generate( + TaskEntity task, + List fragments, + List applications, + List reports, + String clientHint) { if (!isAvailable()) { return Optional.empty(); } @@ -58,11 +58,7 @@ public class RemoteAiMindMapClient implements MindMapAiClient { } Optional optOutline = aiServiceClient.generateMindMap( - task.getTaskName(), - task.getTaskDescription(), - payloads, - reports == null ? List.of() : reports - ); + task.getTaskName(), task.getTaskDescription(), payloads, reports == null ? List.of() : reports); if (optOutline.isEmpty() || optOutline.get().isBlank()) { log.warn("RemoteAiMindMapClient: lpt-ai 返回空大纲,降级"); @@ -71,8 +67,11 @@ public class RemoteAiMindMapClient implements MindMapAiClient { String outline = optOutline.get(); MindMapNode root = MindMapTreeTool.parseOutline(outline); - log.info("RemoteAiMindMapClient: 为任务[{}]生成 AI 导图,共 {} 个节点,{} 层,携带报告 {} 份", - task.getTaskNum(), MindMapTreeTool.countNodes(root), MindMapTreeTool.maxDepth(root), + log.info( + "RemoteAiMindMapClient: 为任务[{}]生成 AI 导图,共 {} 个节点,{} 层,携带报告 {} 份", + task.getTaskNum(), + MindMapTreeTool.countNodes(root), + MindMapTreeTool.maxDepth(root), reports == null ? 0 : reports.size()); return Optional.of(root); } @@ -86,7 +85,8 @@ public class RemoteAiMindMapClient implements MindMapAiClient { if (fragments == null || fragments.isEmpty()) { return List.of(); } - Set reportRefs = reports == null ? Set.of() + Set reportRefs = reports == null + ? Set.of() : reports.stream().map(MindMapReportContext::ref).collect(Collectors.toSet()); List payloads = new ArrayList<>(); for (StudyReportFragmentsEntity fragment : fragments) { @@ -95,7 +95,7 @@ public class RemoteAiMindMapClient implements MindMapAiClient { continue; } String reportRef = FragmentContextTypeEnum.SESSION.name().equals(fragment.getContextType()) - && reportRefs.contains(fragment.getContextNum()) + && reportRefs.contains(fragment.getContextNum()) ? fragment.getContextNum() : null; payloads.add(new MindMapFragmentPayload(content, reportRef)); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/ReportDraftAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/ReportDraftAiTaskHandler.java similarity index 97% rename from src/main/java/com/guo/learningprogresstracker/service/impl/ReportDraftAiTaskHandler.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/ReportDraftAiTaskHandler.java index a8a3e4f..c680139 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/ReportDraftAiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/ReportDraftAiTaskHandler.java @@ -1,17 +1,16 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; -import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.dto.ReportSections; +import com.guo.learningprogresstracker.entity.AiTaskEntity; import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.service.StudySessionsService; +import java.util.LinkedHashMap; +import java.util.Map; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -import java.util.LinkedHashMap; -import java.util.Map; - /** * 学习报告草稿任务(AI-02)。 * diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/TagMindMapAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/ai/TagMindMapAiTaskHandler.java similarity index 93% rename from src/main/java/com/guo/learningprogresstracker/service/impl/TagMindMapAiTaskHandler.java rename to src/main/java/com/guo/learningprogresstracker/service/ai/TagMindMapAiTaskHandler.java index 61d9ed5..8f76353 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/TagMindMapAiTaskHandler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/ai/TagMindMapAiTaskHandler.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.dto.TagScope; @@ -11,13 +11,12 @@ 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 java.util.LinkedHashMap; +import java.util.Map; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -import java.util.LinkedHashMap; -import java.util.Map; - /** * 标签思维导图生成任务(闭环-04)。 * @@ -53,7 +52,8 @@ public class TagMindMapAiTaskHandler implements AiTaskHandler { // ensure 模式下已有导图就直接返回,不做无意义的重新生成(也不重复计费) if (mode == MindMapGenerateModeEnum.ENSURE) { - ReviewTagMindMapEntity existing = reviewTagMindMapService.query(scope).getMap(); + ReviewTagMindMapEntity existing = + reviewTagMindMapService.query(scope).getMap(); if (existing != null) { return toPayload(existing, scope, "已存在,跳过生成"); } @@ -83,8 +83,8 @@ public class TagMindMapAiTaskHandler implements AiTaskHandler { 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( + "nodeCount", MindMapTreeTool.countNodes(MindMapTreeTool.fromJson(entity.getContent(), objectMapper))); payload.put("summary", summary); return payload; } diff --git a/src/main/java/com/guo/learningprogresstracker/service/event/AiTaskSubmittedEvent.java b/src/main/java/com/guo/learningprogresstracker/service/event/AiTaskSubmittedEvent.java index a90f466..a8e5a32 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/event/AiTaskSubmittedEvent.java +++ b/src/main/java/com/guo/learningprogresstracker/service/event/AiTaskSubmittedEvent.java @@ -8,5 +8,4 @@ package com.guo.learningprogresstracker.service.event; * * @param taskId 任务主键 */ -public record AiTaskSubmittedEvent(Integer taskId) { -} +public record AiTaskSubmittedEvent(Integer taskId) {} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImpl.java index 461712f..b3ac9bd 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImpl.java @@ -13,19 +13,20 @@ import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.mapper.AiTaskMapper; import com.guo.learningprogresstracker.service.AiTaskService; +import com.guo.learningprogresstracker.service.ai.RecallAiService; import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; /** * AI 异步任务服务实现(AI-02)。 @@ -35,19 +36,26 @@ import java.util.Optional; @RequiredArgsConstructor public class AiTaskServiceImpl implements AiTaskService { + /** Stuck rows are only possible after a crash; checking every scheduler tick produces pointless UPDATE noise. */ + private static final long RECLAIM_INTERVAL_MS = 60_000; + private final AiTaskMapper aiTaskMapper; private final ObjectMapper objectMapper; private final AiTaskProperties properties; private final ApplicationEventPublisher eventPublisher; + private final RecallAiService recallAiService; + private final AtomicLong lastReclaimAt = new AtomicLong(0); @Override - public AiTaskResponse submit(AiTaskSubmitRequest request) - throws ErrorParameterException, NotFindEntitiesException { + public AiTaskResponse submit(AiTaskSubmitRequest request) throws ErrorParameterException, NotFindEntitiesException { AiTaskTypeEnum type = AiTaskTypeEnum.parse(request.getType()); if (type == null) { log.warn("不支持的 AI 任务类型: {}", request.getType()); throw new ErrorParameterException("这个功能暂时不可用,请稍后再试"); } + if (type == AiTaskTypeEnum.RECALL_HINT || type == AiTaskTypeEnum.RECALL_CHECK) { + return recallAiService.submit(request); + } if (!StringUtils.hasText(request.getTargetNum())) { throw new ErrorParameterException("请先指定要处理的对象"); } @@ -62,8 +70,11 @@ public class AiTaskServiceImpl implements AiTaskService { if (type != AiTaskTypeEnum.GUIDANCE) { Optional active = findActiveTask(type, targetNum); if (active.isPresent()) { - log.info("AI 任务复用进行中的任务: type={}, targetNum={}, taskNum={}", - type, targetNum, active.get().getTaskNum()); + log.info( + "AI 任务复用进行中的任务: type={}, targetNum={}, taskNum={}", + type, + targetNum, + active.get().getTaskNum()); return toResponse(active.get()); } } @@ -81,13 +92,13 @@ public class AiTaskServiceImpl implements AiTaskService { @Override public AiTaskResponse getByTaskNum(String taskNum) throws NotFindEntitiesException { AiTaskEntity task = aiTaskMapper.selectOne(Wrappers.lambdaQuery() - .eq(AiTaskEntity::getTaskNum, taskNum) - .last("LIMIT 1")); + .eq(AiTaskEntity::getTaskNum, taskNum) + .last("LIMIT 1")); if (task == null) { log.warn("AI 任务[{}]不存在", taskNum); throw new NotFindEntitiesException("这个任务不存在或已被清理,请重新发起"); } - return toResponse(task); + return isRecall(task) ? recallAiService.get(task) : toResponse(task); } @Override @@ -101,12 +112,16 @@ public class AiTaskServiceImpl implements AiTaskService { .eq(AiTaskEntity::getTargetNum, targetNum.trim()) .orderByDesc(AiTaskEntity::getCreatedTime) .last("LIMIT 1")); - return task == null ? null : toResponse(task); + return task == null ? null : isRecall(task) ? recallAiService.get(task) : toResponse(task); } @Override public List claimPendingTasks(int limit) { - reclaimStuckTasks(); + long now = System.currentTimeMillis(); + long previous = lastReclaimAt.get(); + if (now - previous >= RECLAIM_INTERVAL_MS && lastReclaimAt.compareAndSet(previous, now)) { + reclaimStuckTasks(); + } List pending = aiTaskMapper.selectPendingTasks(limit); if (pending.isEmpty()) { @@ -137,11 +152,20 @@ public class AiTaskServiceImpl implements AiTaskService { } task.setStatus(AiTaskStatusEnum.RUNNING.name()); task.setStartedTime(now); + // Use the persisted timestamp precision as the new recall execution token. + if (isRecall(task)) { + return Optional.ofNullable(aiTaskMapper.selectTaskById(id)); + } return Optional.of(task); } @Override public void markSucceeded(AiTaskEntity task, Map result) { + if (isRecall(task)) { + com.guo.learningprogresstracker.common.TenantContext.runAs( + task.getCreatedBy(), task.getDeviceInfo(), () -> recallAiService.succeed(task, result)); + return; + } task.setStatus(AiTaskStatusEnum.SUCCEEDED.name()); task.setResultPayload(writeJson(result)); task.setErrorMessage(null); @@ -153,6 +177,11 @@ public class AiTaskServiceImpl implements AiTaskService { @Override public void markFailed(AiTaskEntity task, String message) { + if (isRecall(task)) { + com.guo.learningprogresstracker.common.TenantContext.runAs( + task.getCreatedBy(), task.getDeviceInfo(), () -> recallAiService.fail(task, message)); + return; + } task.setStatus(AiTaskStatusEnum.FAILED.name()); task.setResultPayload(null); task.setErrorMessage(abbreviate(message)); @@ -194,8 +223,7 @@ public class AiTaskServiceImpl implements AiTaskService { return null; } try { - return objectMapper.readValue(task.getResultPayload(), new TypeReference>() { - }); + return objectMapper.readValue(task.getResultPayload(), new TypeReference>() {}); } catch (Exception e) { log.error("AI 任务[{}]结果解析失败", task.getTaskNum(), e); return null; @@ -214,6 +242,10 @@ public class AiTaskServiceImpl implements AiTaskService { } } + private static boolean isRecall(AiTaskEntity task) { + return "RECALL_HINT".equals(task.getAiType()) || "RECALL_CHECK".equals(task.getAiType()); + } + private String abbreviate(String message) { if (message == null) { return "生成失败,请稍后再试"; diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java index ad82f0f..e600da1 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceImpl.java @@ -18,12 +18,7 @@ import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.mapper.AiUsageRecordMapper; import com.guo.learningprogresstracker.service.AiUsageService; import com.guo.learningprogresstracker.service.UserService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.dao.DuplicateKeyException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - +import com.guo.learningprogresstracker.service.ai.AiUsageClient; import java.math.BigDecimal; import java.time.Duration; import java.time.Instant; @@ -38,6 +33,11 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; /** * AI 用量统计实现。 @@ -87,10 +87,10 @@ public class AiUsageServiceImpl implements AiUsageService { /** 批量取已存在的 recordId:这些就是本次要跳过的重复上报 */ private Set findExistingRecordIds(List entities) { - List recordIds = entities.stream() - .map(AiUsageRecordEntity::getRecordId) - .collect(Collectors.toList()); - return aiUsageRecordMapper.selectList(Wrappers.lambdaQuery() + List recordIds = + entities.stream().map(AiUsageRecordEntity::getRecordId).collect(Collectors.toList()); + return aiUsageRecordMapper + .selectList(Wrappers.lambdaQuery() .select(AiUsageRecordEntity::getRecordId) .in(AiUsageRecordEntity::getRecordId, recordIds)) .stream() @@ -104,8 +104,8 @@ public class AiUsageServiceImpl implements AiUsageService { *

已在库里的、以及同一批里重复出现的 recordId 都算 duplicated;库里的唯一索引是最终防线, * 并发下撞上它同样按「重复上报不报错」处理,不让整批数据白报。

*/ - private AiUsageIngestResult insertSkippingDuplicates(List entities, - Set knownRecordIds) { + private AiUsageIngestResult insertSkippingDuplicates( + List entities, Set knownRecordIds) { Set seen = new HashSet<>(knownRecordIds); int accepted = 0; int duplicated = 0; @@ -218,8 +218,8 @@ public class AiUsageServiceImpl implements AiUsageService { ResolvedFilter filter = resolve(query); String bucket = requireBucket(query == null ? null : query.getBucket()); - return aiUsageRecordMapper.selectSeries( - filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), bucket) + return aiUsageRecordMapper + .selectSeries(filter.from(), filter.to(), filter.taskType(), filter.model(), filter.userId(), bucket) .stream() .map(row -> { AiUsageSeriesPoint point = new AiUsageSeriesPoint(); @@ -259,8 +259,8 @@ public class AiUsageServiceImpl implements AiUsageService { return userService.getUserNamesByIds(userIds); } - private static AiUsageBreakdownItem toBreakdownItem(AiUsageBreakdownRow row, String groupBy, - Map userNames) { + private static AiUsageBreakdownItem toBreakdownItem( + AiUsageBreakdownRow row, String groupBy, Map userNames) { String key = row.getGroupKey(); AiUsageBreakdownItem item = new AiUsageBreakdownItem(); item.setKey(key); @@ -272,8 +272,7 @@ public class AiUsageServiceImpl implements AiUsageService { item.setCompletionTokens(nullToZero(row.getCompletionTokens())); item.setCacheHitTokens(nullToZero(row.getCacheHitTokens())); item.setCostUsd(nullToZero(row.getCostUsd())); - item.setAvgDurationMs(row.getAvgDurationMs() == null - ? null : Math.round(row.getAvgDurationMs())); + item.setAvgDurationMs(row.getAvgDurationMs() == null ? null : Math.round(row.getAvgDurationMs())); return item; } @@ -310,7 +309,9 @@ public class AiUsageServiceImpl implements AiUsageService { LocalDateTime toTime = to == null ? LocalDateTime.ofInstant(now, ZoneOffset.UTC) : LocalDateTime.ofInstant(Instant.ofEpochMilli(to), ZoneOffset.UTC); - return new ResolvedFilter(fromTime, toTime, + return new ResolvedFilter( + fromTime, + toTime, query == null ? null : query.getTaskType(), query == null ? null : query.getModel(), query == null ? null : query.getUserId()); @@ -347,6 +348,5 @@ public class AiUsageServiceImpl implements AiUsageService { } /** 解析后的查询条件(时间已转成 UTC 本地时间) */ - private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model, String userId) { - } + private record ResolvedFilter(LocalDateTime from, LocalDateTime to, String taskType, String model, String userId) {} } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/BuiltinMindMapGenerator.java b/src/main/java/com/guo/learningprogresstracker/service/impl/BuiltinMindMapGenerator.java deleted file mode 100644 index abaffc9..0000000 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/BuiltinMindMapGenerator.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.guo.learningprogresstracker.service.impl; - -import com.guo.learningprogresstracker.dto.MindMapReportContext; -import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; -import com.guo.learningprogresstracker.entity.TaskApplicationEntity; -import com.guo.learningprogresstracker.entity.TaskEntity; -import com.guo.learningprogresstracker.service.MindMapAiClient; -import com.guo.learningprogresstracker.utils.MindMapNode; -import com.guo.learningprogresstracker.utils.MindMapTreeTool; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 内置规则引擎:从知识碎片提取内容并组织为树形思维导图(AI 不可用时的降级路径)。 - * - *

素材按**内容归属**给:一个任务名下的碎片,而不是产生于该任务会话的报告。 - * 因此学 A 时记下但归属到 B 的旁支知识,会出现在 B 的导图里。

- * - *

规则策略:

- *
    - *
  1. 根节点 = 任务名称
  2. - *
  3. 一级分支 = 按记录上下文(日期 + 首条碎片摘要)分组
  4. - *
  5. 二级分支 = 该上下文下的碎片
  6. - *
  7. 附加分支"应用场景" = 任务应用场景(如有)
  8. - *
  9. 去重:标准化后标题对比,合并内容相似的节点
  10. - *
  11. 引用追溯:每个节点携带 sourceType / sourceId
  12. - *
- */ -@Slf4j -@Component -public class BuiltinMindMapGenerator implements MindMapAiClient { - - private static final int MAX_TITLE_LENGTH = 60; - - @Override - public boolean isAvailable() { - return true; // 始终可用 - } - - @Override - public String generatorName() { - return "BUILTIN"; - } - - @Override - public Optional generate(TaskEntity task, - List fragments, - List applications, - List reports, - String clientHint) { - // 报告是参考上下文,需要语义判断「是否与碎片强相关」才能采用;内置规则不做这种判断, - // 因此报告只在 AI 路径参与(报告-02)。 - if (fragments == null || fragments.isEmpty()) { - return Optional.empty(); - } - - MindMapNode root = new MindMapNode(task.getTaskName() != null ? task.getTaskName() : "学习任务"); - root.setNotes(task.getTaskDescription() != null ? task.getTaskDescription() : ""); - - // 按记录上下文分组:同一次学习会话(或复习行为)产生的碎片归在一支下 - Map> fragmentsByContext = fragments.stream() - .filter(f -> f.getContextNum() != null) - .collect(Collectors.groupingBy(StudyReportFragmentsEntity::getContextNum, - LinkedHashMap::new, Collectors.toList())); - - for (Map.Entry> entry : fragmentsByContext.entrySet()) { - List contextFragments = entry.getValue(); - - // 分支标题:日期 + 第一条碎片的前 60 字 - StudyReportFragmentsEntity first = contextFragments.get(0); - String contextTitle = truncate(first.getContent(), MAX_TITLE_LENGTH); - if (first.getCreatedTime() != null) { - contextTitle = formatDate(first.getCreatedTime()) + " " + contextTitle; - } - - MindMapNode contextNode = new MindMapNode(contextTitle); - - for (StudyReportFragmentsEntity fragment : contextFragments) { - String content = fragment.getContent(); - if (content == null || content.isBlank()) continue; - MindMapNode fragmentNode = new MindMapNode(truncate(content, MAX_TITLE_LENGTH)); - fragmentNode.setNotes(content); - fragmentNode.setSourceType("FRAGMENT"); - fragmentNode.setSourceId(fragment.getId()); - contextNode.getChildren().add(fragmentNode); - } - - root.getChildren().add(contextNode); - } - - // 应用场景分支(如有) - if (applications != null && !applications.isEmpty()) { - MindMapNode appNode = new MindMapNode("应用场景"); - for (TaskApplicationEntity app : applications) { - if (app.getTitle() == null || app.getTitle().isBlank()) continue; - MindMapNode child = new MindMapNode(app.getTitle()); - child.setNotes(app.getDescription() != null ? app.getDescription() : ""); - child.setSourceType("APPLICATION"); - child.setSourceId(app.getId()); - appNode.getChildren().add(child); - } - if (!appNode.getChildren().isEmpty()) { - root.getChildren().add(appNode); - } - } - - // 去重:同级 title 标准化后合并 - deduplicateChildren(root); - - log.info("BuiltinMindMapGenerator: 为任务[{}]生成导图,共 {} 个节点,{} 层", - task.getTaskNum(), MindMapTreeTool.countNodes(root), MindMapTreeTool.maxDepth(root)); - return Optional.of(root); - } - - /** 同级节点按标准化标题去重 */ - private void deduplicateChildren(MindMapNode node) { - if (node.getChildren() == null || node.getChildren().isEmpty()) return; - - Map seen = new LinkedHashMap<>(); - for (MindMapNode child : node.getChildren()) { - String key = normalize(child.getTitle()); - seen.merge(key, child, (a, b) -> { - // 保留 notes 较长的那个 - if (b.getNotes() != null && b.getNotes().length() > (a.getNotes() != null ? a.getNotes().length() : 0)) { - a.setNotes(b.getNotes()); - } - // 合并子节点 - if (b.getChildren() != null) { - a.getChildren().addAll(b.getChildren()); - } - return a; - }); - } - node.setChildren(new ArrayList<>(seen.values())); - - for (MindMapNode child : node.getChildren()) { - deduplicateChildren(child); - } - } - - private static String normalize(String s) { - if (s == null) return ""; - return s.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", "") - .toLowerCase(Locale.ROOT) - .trim(); - } - - private static String truncate(String s, int maxLen) { - if (s == null) return ""; - if (s.length() <= maxLen) return s; - return s.substring(0, maxLen) + "…"; - } - - private static String formatDate(LocalDateTime dt) { - if (dt == null) return ""; - return dt.format(DateTimeFormatter.ofPattern("MM-dd")); - } - -} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/ExportServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/ExportServiceImpl.java index d9629ac..94bb70b 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/ExportServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/ExportServiceImpl.java @@ -3,7 +3,10 @@ package com.guo.learningprogresstracker.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.guo.learningprogresstracker.dto.*; +import com.guo.learningprogresstracker.dto.ExportDocument; +import com.guo.learningprogresstracker.dto.ExportEntry; +import com.guo.learningprogresstracker.dto.ExportResult; +import com.guo.learningprogresstracker.dto.ExportTaskSection; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.entity.StudySessionsEntity; @@ -17,17 +20,24 @@ import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.service.ExportService; import com.guo.learningprogresstracker.service.ReviewService; import com.guo.learningprogresstracker.utils.ExportMarkdownRenderer; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; /** * 数据导出实现(导出-01)。 @@ -43,7 +53,6 @@ public class ExportServiceImpl implements ExportService { private static final String FORMAT_JSON = "json"; private static final String CONTENT_TYPE_MARKDOWN = "text/markdown; charset=UTF-8"; private static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8"; - private static final String SOURCE_REPORT = "REPORT"; private static final String SCOPE_TASK = "TASK"; private static final String SCOPE_RANGE = "RANGE"; private static final String SCOPE_ALL = "ALL"; @@ -51,6 +60,7 @@ public class ExportServiceImpl implements ExportService { /** 文件名里的不安全字符 */ private static final String UNSAFE_FILE_CHARS = "[\\\\/:*?\"<>|\\r\\n]"; + private static final int MAX_FILE_NAME_PART_LENGTH = 40; private final TasksMapper tasksMapper; @@ -64,7 +74,8 @@ public class ExportServiceImpl implements ExportService { public ExportResult exportTask(String taskNum, String format) throws NotFindEntitiesException, OperationFailedException { String safeFormat = normalizeFormat(format); - TaskEntity task = tasksMapper.selectList(Wrappers.lambdaQuery() + TaskEntity task = tasksMapper + .selectList(Wrappers.lambdaQuery() .eq(TaskEntity::getTaskNum, taskNum) .last("LIMIT 1")) .stream() @@ -78,7 +89,37 @@ public class ExportServiceImpl implements ExportService { section.setTaskNum(task.getTaskNum()); section.setTaskName(task.getTaskName()); section.setStats(reviewService.getReviewTaskStats(taskNum)); - applyFeedItems(section, reviewService.getTaskReview(taskNum)); + List sessionNums = studySessionsMapper + .selectList(Wrappers.lambdaQuery().eq(StudySessionsEntity::getTaskNum, taskNum)) + .stream() + .map(StudySessionsEntity::getSessionNum) + .toList(); + if (!sessionNums.isEmpty()) { + for (StudyReportsEntity report : studyReportsMapper.selectList(Wrappers.lambdaQuery() + .in(StudyReportsEntity::getSessionNum, sessionNums) + .orderByDesc(StudyReportsEntity::getCreatedTime))) { + section.getReports() + .add(entry( + report.getId(), + "SESSION", + report.getSessionNum(), + report.getCreatedTime(), + reportFreeText(report))); + } + } + for (StudyReportFragmentsEntity fragment : + studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() + .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) + .orderByDesc(StudyReportFragmentsEntity::getCreatedTime))) { + section.getFragments() + .add(entry( + fragment.getId(), + fragment.getContextType(), + fragment.getContextNum(), + fragment.getCreatedTime(), + fragment.getContent())); + } + alignContentCounts(section); ExportDocument document = new ExportDocument(); document.setGeneratedTime(LocalDateTime.now()); @@ -103,15 +144,18 @@ public class ExportServiceImpl implements ExportService { .ge(from != null, StudyReportsEntity::getCreatedTime, from) .le(to != null, StudyReportsEntity::getCreatedTime, to) .orderByDesc(StudyReportsEntity::getCreatedTime)); - List fragments = studyReportFragmentsMapper.selectList( - Wrappers.lambdaQuery() + List fragments = + studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() .ge(from != null, StudyReportFragmentsEntity::getCreatedTime, from) .le(to != null, StudyReportFragmentsEntity::getCreatedTime, to) .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)); Map sections = new LinkedHashMap<>(); appendRangeItems(sections, reports, fragments); - sections.values().forEach(section -> section.setStats(reviewService.getReviewTaskStats(section.getTaskNum()))); + sections.values().forEach(section -> { + section.setStats(reviewService.getReviewTaskStats(section.getTaskNum())); + alignContentCounts(section); + }); ExportDocument document = new ExportDocument(); document.setGeneratedTime(LocalDateTime.now()); @@ -146,22 +190,23 @@ public class ExportServiceImpl implements ExportService { text.append("【").append(title).append("】\n").append(body.trim()); } - /** 任务级导出:把 feed 条目按来源拆成报告与碎片 */ - private void applyFeedItems(ExportTaskSection section, List items) { - if (items == null) { - return; - } - for (ReviewFeedItem item : items) { - ExportEntry entry = new ExportEntry(); - entry.setId(item.getId()); - entry.setSessionNum(item.getContextNum()); - entry.setCreatedTime(item.getCreatedTime()); - entry.setContent(item.getContent()); - if (SOURCE_REPORT.equals(item.getSourceType())) { - section.getReports().add(entry); - } else { - section.getFragments().add(entry); - } + private static ExportEntry entry( + Integer id, String contextType, String contextNum, LocalDateTime time, String content) { + ExportEntry entry = new ExportEntry(); + entry.setId(id); + entry.setContextType(contextType); + entry.setContextNum(contextNum); + entry.setSessionNum("SESSION".equals(contextType) ? contextNum : null); + entry.setCreatedTime(time); + entry.setContent(content); + return entry; + } + + /** Counts describe the exported collection; time statistics remain cumulative task statistics. */ + private static void alignContentCounts(ExportTaskSection section) { + if (section.getStats() != null) { + section.getStats().setReportCount(section.getReports().size()); + section.getStats().setFragmentCount(section.getFragments().size()); } } @@ -169,30 +214,50 @@ public class ExportServiceImpl implements ExportService { * 范围级导出:报告与碎片先按时间倒序合并,再按内容归属(学习任务)分组, * 保证同一任务下两种内容交错时顺序仍然正确。 */ - private void appendRangeItems(Map sections, - List reports, - List fragments) { + private void appendRangeItems( + Map sections, + List reports, + List fragments) { List items = new ArrayList<>(); for (StudyReportsEntity report : reports) { - items.add(new RangeItem(report.getSessionNum(), report.getId(), report.getCreatedTime(), - reportFreeText(report), true)); + items.add(new RangeItem( + "SESSION", + report.getSessionNum(), + null, + report.getId(), + report.getCreatedTime(), + reportFreeText(report), + true)); } for (StudyReportFragmentsEntity fragment : fragments) { - items.add(new RangeItem(fragment.getContextNum(), fragment.getId(), fragment.getCreatedTime(), fragment.getContent(), false)); + items.add(new RangeItem( + fragment.getContextType(), + fragment.getContextNum(), + fragment.getOwnerTaskNum(), + fragment.getId(), + fragment.getCreatedTime(), + fragment.getContent(), + false)); } items.sort(Comparator.comparing(RangeItem::createdTime, Comparator.nullsLast(Comparator.reverseOrder()))); Set sessionNums = items.stream() - .map(RangeItem::sessionNum) + .filter(RangeItem::report) + .map(RangeItem::contextNum) .filter(Objects::nonNull) .collect(Collectors.toSet()); Map sessionToTask = resolveSessionToTask(sessionNums); - Map taskNames = resolveTaskNames(new HashSet<>(sessionToTask.values())); + Set taskNums = new HashSet<>(sessionToTask.values()); + fragments.stream() + .map(StudyReportFragmentsEntity::getOwnerTaskNum) + .filter(Objects::nonNull) + .forEach(taskNums::add); + Map taskNames = resolveTaskNames(taskNums); for (RangeItem item : items) { - String taskNum = sessionToTask.get(item.sessionNum()); - if (taskNum == null) { - // 学习会话已被删除时无法归属,跳过而不是塞进错误的段落 + String taskNum = item.report() ? sessionToTask.get(item.contextNum()) : item.ownerTaskNum(); + if (taskNum == null || !taskNames.containsKey(taskNum)) { + // Only export sections for accessible, active owner tasks. continue; } ExportTaskSection section = sections.computeIfAbsent(taskNum, num -> { @@ -201,11 +266,8 @@ public class ExportServiceImpl implements ExportService { created.setTaskName(taskNames.get(num)); return created; }); - ExportEntry entry = new ExportEntry(); - entry.setId(item.id()); - entry.setSessionNum(item.sessionNum()); - entry.setCreatedTime(item.createdTime()); - entry.setContent(item.content()); + ExportEntry entry = + entry(item.id(), item.contextType(), item.contextNum(), item.createdTime(), item.content()); if (item.report()) { section.getReports().add(entry); } else { @@ -218,22 +280,22 @@ public class ExportServiceImpl implements ExportService { if (sessionNums.isEmpty()) { return Collections.emptyMap(); } - return studySessionsMapper.selectList(Wrappers.lambdaQuery() + return studySessionsMapper + .selectList(Wrappers.lambdaQuery() .in(StudySessionsEntity::getSessionNum, sessionNums) .select(StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum)) .stream() .filter(session -> session.getSessionNum() != null && session.getTaskNum() != null) .collect(Collectors.toMap( - StudySessionsEntity::getSessionNum, - StudySessionsEntity::getTaskNum, - (a, b) -> a)); + StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum, (a, b) -> a)); } private Map resolveTaskNames(Set taskNums) { if (taskNums.isEmpty()) { return Collections.emptyMap(); } - return tasksMapper.selectList(Wrappers.lambdaQuery() + return tasksMapper + .selectList(Wrappers.lambdaQuery() .in(TaskEntity::getTaskNum, taskNums) .select(TaskEntity::getTaskNum, TaskEntity::getTaskName)) .stream() @@ -256,13 +318,17 @@ public class ExportServiceImpl implements ExportService { throw new OperationFailedException("导出内容生成失败了,请稍后再试"); } } - return new ExportResult(fileNamePrefix + "-" + timestamp + ".md", CONTENT_TYPE_MARKDOWN, + return new ExportResult( + fileNamePrefix + "-" + timestamp + ".md", + CONTENT_TYPE_MARKDOWN, ExportMarkdownRenderer.render(document)); } private String normalizeFormat(String format) throws OperationFailedException { String value = format == null ? "" : format.trim(); - if (!StringUtils.hasText(value) || FORMAT_MARKDOWN.equalsIgnoreCase(value) || FORMAT_MD_ALIAS.equalsIgnoreCase(value)) { + if (!StringUtils.hasText(value) + || FORMAT_MARKDOWN.equalsIgnoreCase(value) + || FORMAT_MD_ALIAS.equalsIgnoreCase(value)) { return FORMAT_MARKDOWN; } if (FORMAT_JSON.equalsIgnoreCase(value)) { @@ -291,7 +357,12 @@ public class ExportServiceImpl implements ExportService { } /** 合并排序用的中间载体 */ - private record RangeItem(String sessionNum, Integer id, LocalDateTime createdTime, String content, - boolean report) { - } + private record RangeItem( + String contextType, + String contextNum, + String ownerTaskNum, + Integer id, + LocalDateTime createdTime, + String content, + boolean report) {} } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceServiceImpl.java index f20e150..e0b4d07 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/GuidanceServiceImpl.java @@ -18,17 +18,16 @@ import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.service.GuidanceService; import com.guo.learningprogresstracker.service.MarkerService; import com.guo.learningprogresstracker.utils.ReviewDurationTool; -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.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; /** * 学习引导服务实现(复习-06)。 @@ -48,10 +47,10 @@ public class GuidanceServiceImpl implements GuidanceService { private final ObjectMapper objectMapper; @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public ReviewGuidanceConversationEntity start(String taskNum, String concept) throws NotFindEntitiesException { - if (!StringUtils.hasText(taskNum) || !tasksMapper.exists( - Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { + if (!StringUtils.hasText(taskNum) + || !tasksMapper.exists(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { throw new NotFindEntitiesException("这个任务不存在或已被删除"); } if (!StringUtils.hasText(concept)) { @@ -60,15 +59,14 @@ public class GuidanceServiceImpl implements GuidanceService { ReviewGuidanceConversationEntity conversation = ReviewGuidanceConversationEntity.initNewConversation(taskNum.trim(), concept.trim()); guidanceMapper.insert(conversation); - log.info("学习引导已开启: guidanceNum={}, taskNum={}, concept={}", - conversation.getGuidanceNum(), taskNum, concept); + log.info("学习引导已开启: guidanceNum={}, taskNum={}, concept={}", conversation.getGuidanceNum(), taskNum, concept); return conversation; } @Override public ReviewGuidanceConversationEntity getByGuidanceNum(String guidanceNum) throws NotFindEntitiesException { - ReviewGuidanceConversationEntity conversation = guidanceMapper.selectOne( - Wrappers.lambdaQuery() + ReviewGuidanceConversationEntity conversation = + guidanceMapper.selectOne(Wrappers.lambdaQuery() .eq(ReviewGuidanceConversationEntity::getGuidanceNum, guidanceNum) .last("LIMIT 1")); if (conversation == null) { @@ -89,7 +87,7 @@ public class GuidanceServiceImpl implements GuidanceService { } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public String appendUserTurn(String guidanceNum, String userMessage) throws NotFindEntitiesException { if (!StringUtils.hasText(userMessage)) { throw new NotFindEntitiesException("请先写下你的想法"); @@ -125,7 +123,7 @@ public class GuidanceServiceImpl implements GuidanceService { } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public StudyReportFragmentsEntity confirmFragment(String guidanceNum, String content, ReviewTiming timing) throws ErrorParameterException, NotFindEntitiesException { if (!StringUtils.hasText(content)) { @@ -146,16 +144,15 @@ public class GuidanceServiceImpl implements GuidanceService { fragmentsMapper.insert(fragment); // 「来自学习引导」只说明来源,不改变碎片的任何处理逻辑 - markerService.addSystemMarker(MarkerObjectTypeEnum.FRAGMENT, - String.valueOf(fragment.getId()), SystemMarkerEnum.FROM_GUIDANCE); + markerService.addSystemMarker( + MarkerObjectTypeEnum.FRAGMENT, String.valueOf(fragment.getId()), SystemMarkerEnum.FROM_GUIDANCE); // 引导产出的碎片默认也有内容归属 → 一并自动打任务名标签(闭环-02) - markerService.addOwnerTaskNameTag(MarkerObjectTypeEnum.FRAGMENT, - String.valueOf(fragment.getId()), fragment.getOwnerTaskNum()); + markerService.addOwnerTaskNameTag( + MarkerObjectTypeEnum.FRAGMENT, String.valueOf(fragment.getId()), fragment.getOwnerTaskNum()); finishConversation(conversation, timing); - log.info("学习引导[{}]产出碎片[{}],默认归属任务[{}]", - guidanceNum, fragment.getId(), conversation.getTaskNum()); + log.info("学习引导[{}]产出碎片[{}],默认归属任务[{}]", guidanceNum, fragment.getId(), conversation.getTaskNum()); return fragment; } @@ -171,23 +168,27 @@ public class GuidanceServiceImpl implements GuidanceService { /** 结束这次引导:记下复习耗时(与回忆对比同一口径),不产出碎片 */ private void finishConversation(ReviewGuidanceConversationEntity conversation, ReviewTiming timing) { - ReviewGuidanceConversationEntity patch = new ReviewGuidanceConversationEntity(); - patch.setId(conversation.getId()); - patch.setFinished(true); - patch.setFinishedTime(LocalDateTime.now()); - patch.setReviewDurationSeconds(ReviewDurationTool.resolveSeconds( - timing == null ? null : timing.startedAt(), - timing == null ? null : timing.lastInteractionAt(), - timing == null ? null : timing.durationSeconds(), - LocalDateTime.now())); - guidanceMapper.updateById(patch); + guidanceMapper.update( + new ReviewGuidanceConversationEntity(), + Wrappers.lambdaUpdate() + .eq(ReviewGuidanceConversationEntity::getId, conversation.getId()) + .set(ReviewGuidanceConversationEntity::getFinished, true) + .set(ReviewGuidanceConversationEntity::getFinishedTime, LocalDateTime.now()) + .set( + ReviewGuidanceConversationEntity::getReviewDurationSeconds, + ReviewDurationTool.resolveSeconds( + timing == null ? null : timing.startedAt(), + timing == null ? null : timing.lastInteractionAt(), + timing == null ? null : timing.durationSeconds(), + LocalDateTime.now()))); } private void updateTurns(Integer id, String payload) { - ReviewGuidanceConversationEntity patch = new ReviewGuidanceConversationEntity(); - patch.setId(id); - patch.setTurnsPayload(payload); - guidanceMapper.updateById(patch); + guidanceMapper.update( + new ReviewGuidanceConversationEntity(), + Wrappers.lambdaUpdate() + .eq(ReviewGuidanceConversationEntity::getId, id) + .set(ReviewGuidanceConversationEntity::getTurnsPayload, payload)); } private List> readTurns(ReviewGuidanceConversationEntity conversation) { @@ -196,8 +197,7 @@ public class GuidanceServiceImpl implements GuidanceService { return new ArrayList<>(); } try { - return new ArrayList<>(objectMapper.readValue(payload, new TypeReference>>() { - })); + return new ArrayList<>(objectMapper.readValue(payload, new TypeReference>>() {})); } catch (Exception e) { log.warn("学习引导[{}]的对话轮次解析失败,按空历史继续", conversation.getGuidanceNum()); return new ArrayList<>(); diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/LoginServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/LoginServiceImpl.java index c14715f..52d8030 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/LoginServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/LoginServiceImpl.java @@ -11,7 +11,7 @@ public class LoginServiceImpl implements LoginService { @Override public String login(String userId) throws AppException { StpUtil.login(userId); - //todo Token只在此处使用了,属于后续优化点 + // todo Token只在此处使用了,属于后续优化点 return StpUtil.getTokenInfo().getTokenValue(); } 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 98c0f36..96fd9a5 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/MarkerServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/MarkerServiceImpl.java @@ -3,7 +3,6 @@ package com.guo.learningprogresstracker.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.guo.learningprogresstracker.dto.MarkerUsage; import com.guo.learningprogresstracker.entity.MarkerEntity; -import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.entity.UserTagEntity; import com.guo.learningprogresstracker.enums.MarkerKindEnum; @@ -17,21 +16,20 @@ 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 com.guo.learningprogresstracker.service.recall.RecallPrivacyService; +import com.guo.learningprogresstracker.service.review.TagDictionaryService; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; 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.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.List; -import java.util.stream.Collectors; - /** * 统一标记服务实现(标记-01)。 */ @@ -40,14 +38,13 @@ import java.util.stream.Collectors; @RequiredArgsConstructor public class MarkerServiceImpl implements MarkerService { - /** 用户标签名的长度上限,与表结构一致 */ - private static final int MAX_MARKER_NAME_LENGTH = 100; - private final MarkerMapper markerMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final TasksMapper tasksMapper; private final UserTagMapper userTagMapper; private final ReviewTagMindMapService reviewTagMindMapService; + private final RecallPrivacyService recallPrivacyService; + private final TagDictionaryService tagDictionaryService; @Override public List listByObject(MarkerObjectTypeEnum objectType, String objectNum) { @@ -63,7 +60,8 @@ public class MarkerServiceImpl implements MarkerService { } @Override - public Map> listByObjects(MarkerObjectTypeEnum objectType, Collection objectNums) { + public Map> listByObjects( + MarkerObjectTypeEnum objectType, Collection objectNums) { if (objectType == null || objectNums == null || objectNums.isEmpty()) { return Collections.emptyMap(); } @@ -72,29 +70,29 @@ public class MarkerServiceImpl implements MarkerService { .in(MarkerEntity::getObjectNum, objectNums) .orderByAsc(MarkerEntity::getKind) .orderByAsc(MarkerEntity::getId)); - return markers.stream().collect(Collectors.groupingBy( - MarkerEntity::getObjectNum, LinkedHashMap::new, Collectors.toList())); + return markers.stream() + .collect(Collectors.groupingBy(MarkerEntity::getObjectNum, LinkedHashMap::new, Collectors.toList())); } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public MarkerEntity addUserTag(MarkerObjectTypeEnum objectType, String objectNum, String markerName) throws ErrorParameterException, NotFindEntitiesException { - String name = normalizeTagName(markerName); + String name = tagDictionaryService.normalizeTagName(markerName); String num = normalizeObjectNum(objectNum, objectType); // 幂等:同一对象上同名同类同值的标记只保留一条。 // 查的时候要带上已逻辑删除的行:唯一键不含 deleted,被删掉的行仍占着这个键, // 直接 insert 会撞唯一键(移除标签后再打同名标签、或删掉自动任务名标签后重新归类都会走到)。 - MarkerEntity existing = markerMapper.selectAnyByObjectAndName( - objectType.name(), num, MarkerKindEnum.USER.name(), name); + MarkerEntity existing = + markerMapper.selectAnyByObjectAndName(objectType.name(), num, MarkerKindEnum.USER.name(), name); if (existing != null) { if (existing.getDeleted() == null || existing.getDeleted() == 0) { - ensureDictionaryEntry(name); + tagDictionaryService.ensureDictionaryEntry(name); return existing; } markerMapper.revive(existing.getId()); - ensureDictionaryEntry(name); + tagDictionaryService.ensureDictionaryEntry(name); // 碎片多了一个标签 → 相关标签导图置「待更新」(闭环-04,不自动重建) markTagMindMapsStale(objectType, List.of(name)); return markerMapper.selectById(existing.getId()); @@ -109,29 +107,32 @@ public class MarkerServiceImpl implements MarkerService { marker.setMarkerValue(null); markerMapper.insert(marker); // 打标签时输入的新名字自动补进字典(闭环-03) - ensureDictionaryEntry(name); + tagDictionaryService.ensureDictionaryEntry(name); // 碎片多了一个标签 → 相关标签导图置「待更新」(闭环-04,不自动重建) markTagMindMapsStale(objectType, List.of(name)); return marker; } @Override + @Transactional(rollbackFor = Exception.class) public void deleteMarker(Integer id) throws ErrorParameterException, NotFindEntitiesException { MarkerEntity existing = requireMarker(id); if (existing.isSystemMarker()) { log.warn("系统标记[{}]不允许用户删除", existing.getMarkerName()); throw new ErrorParameterException("这是系统标记,不能删除"); } + recallPrivacyService.begin(); markerMapper.deleteById(existing.getId()); + recallPrivacyService.tagsChanged(); // 碎片少了一个标签 → 相关标签导图置「待更新」(闭环-04,不自动重建) markTagMindMapsStale(MarkerObjectTypeEnum.parse(existing.getObjectType()), List.of(existing.getMarkerName())); } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public int renameUserTag(String oldName, String newName) throws ErrorParameterException { - String from = normalizeTagName(oldName); - String to = normalizeTagName(newName); + String from = tagDictionaryService.normalizeTagName(oldName); + String to = tagDictionaryService.normalizeTagName(newName); if (from.equals(to)) { return 0; } @@ -144,6 +145,7 @@ public class MarkerServiceImpl implements MarkerService { throw new ErrorParameterException("这个标签不存在"); } + recallPrivacyService.tagRenamed(from); int renamed = 0; for (MarkerEntity marker : targets) { // 目标标签已存在于同一对象时,这条改名后的记录会与既有记录重复,直接清掉 @@ -156,10 +158,11 @@ public class MarkerServiceImpl implements MarkerService { markerMapper.deleteById(marker.getId()); continue; } - MarkerEntity patch = new MarkerEntity(); - patch.setId(marker.getId()); - patch.setMarkerName(to); - markerMapper.updateById(patch); + markerMapper.update( + new MarkerEntity(), + Wrappers.lambdaUpdate() + .eq(MarkerEntity::getId, marker.getId()) + .set(MarkerEntity::getMarkerName, to)); renamed++; } log.info("标签[{}]重命名为[{}],影响 {} 条标记", from, to, renamed); @@ -169,12 +172,13 @@ public class MarkerServiceImpl implements MarkerService { } @Override - public List findObjectNumsByMarker(MarkerObjectTypeEnum objectType, String markerName, String markerValue, - String kind) { + public List findObjectNumsByMarker( + MarkerObjectTypeEnum objectType, String markerName, String markerValue, String kind) { if (objectType == null || !StringUtils.hasText(markerName)) { return Collections.emptyList(); } - return markerMapper.selectList(Wrappers.lambdaQuery() + return markerMapper + .selectList(Wrappers.lambdaQuery() .eq(MarkerEntity::getObjectType, objectType.name()) .eq(MarkerEntity::getMarkerName, markerName.trim()) .eq(StringUtils.hasText(markerValue), MarkerEntity::getMarkerValue, markerValue) @@ -195,6 +199,17 @@ public class MarkerServiceImpl implements MarkerService { return markerMapper.selectUserTagUsage(createdBy); } + @Override + public List listUserTagUsage(MarkerObjectTypeEnum objectType) { + if (objectType == null) { + return listUserTagUsage(); + } + String createdBy = currentUser(); + return StringUtils.hasText(createdBy) + ? markerMapper.selectUserTagUsageByObjectType(createdBy, objectType.name()) + : Collections.emptyList(); + } + @Override public void addSystemMarker(MarkerObjectTypeEnum objectType, String objectNum, SystemMarkerEnum marker) { if (objectType == null || !StringUtils.hasText(objectNum) || marker == null) { @@ -219,6 +234,7 @@ public class MarkerServiceImpl implements MarkerService { } @Override + @Transactional(rollbackFor = Exception.class) public void addOwnerTaskNameTag(MarkerObjectTypeEnum objectType, String objectNum, String taskNum) { if (objectType == null || !StringUtils.hasText(objectNum) || !StringUtils.hasText(taskNum)) { return; @@ -227,125 +243,54 @@ public class MarkerServiceImpl implements MarkerService { .eq(TaskEntity::getTaskNum, taskNum.trim()) .last("LIMIT 1")); if (task == null || !StringUtils.hasText(task.getTaskName())) { - // 任务已被删除或没有名字时不打标;归属本身不受影响 - return; + throw new IllegalStateException("归属任务已不可用或任务名为空"); } try { // 走用户标签:可改名、可删除,任务之后改名也不回溯改写这条历史标签 addUserTag(objectType, objectNum, task.getTaskName()); } catch (ErrorParameterException | NotFindEntitiesException e) { - // 任务名超过标签长度上限等情况下只跳过打标,不让归属操作失败 - log.warn("对象[{}/{}]自动打任务名标签失败:{}", objectType, objectNum, e.getMessage()); + throw new IllegalStateException("任务名标签保存失败", e); } } @Override public List listDictionaryTags() { - return userTagMapper.selectList(Wrappers.lambdaQuery() - .orderByAsc(UserTagEntity::getTagName) - .orderByAsc(UserTagEntity::getId)); + return tagDictionaryService.listDictionaryTags(); } @Override - @Transactional public UserTagEntity createDictionaryTag(String tagName) throws ErrorParameterException { - String display = normalizeTagName(tagName); - String normalized = normalizeTagKey(display); - UserTagEntity existing = userTagMapper.selectAnyByNormalizedName(normalized); - if (existing != null) { - if (existing.getDeleted() == null || existing.getDeleted() == 0) { - // 已在字典里,幂等返回 - return existing; - } - // 曾有同名项被删除:复用(复活)旧行,避免重新插入撞唯一键 - userTagMapper.revive(existing.getId(), display); - return userTagMapper.selectById(existing.getId()); - } - UserTagEntity entity = new UserTagEntity(); - entity.setTagName(display); - entity.setNormalizedName(normalized); - userTagMapper.insert(entity); - return entity; + return tagDictionaryService.createDictionaryTag(tagName); } @Override - @Transactional public UserTagEntity renameDictionaryTag(Integer id, String newName) throws ErrorParameterException, NotFindEntitiesException { - UserTagEntity current = requireDictionaryTag(id); - String display = normalizeTagName(newName); - String normalized = normalizeTagKey(display); - - if (normalized.equals(current.getNormalizedName())) { - // 只是大小写/空白不同:更新展示名即可 - if (!display.equals(current.getTagName())) { - UserTagEntity patch = new UserTagEntity(); - patch.setId(current.getId()); - patch.setTagName(display); - userTagMapper.updateById(patch); - } - return userTagMapper.selectById(current.getId()); - } - - UserTagEntity target = userTagMapper.selectAnyByNormalizedName(normalized); - if (target != null) { - // 目标名已在字典里(可能是一条被删除的行):合并——保留目标项、删掉当前项 - if (target.getDeleted() != null && target.getDeleted() != 0) { - userTagMapper.revive(target.getId(), display); - } - userTagMapper.deleteById(current.getId()); - log.info("字典标签[{}]改名为[{}],与既有项合并", current.getTagName(), display); - return userTagMapper.selectById(target.getId()); - } - - UserTagEntity patch = new UserTagEntity(); - patch.setId(current.getId()); - patch.setTagName(display); - patch.setNormalizedName(normalized); - userTagMapper.updateById(patch); - log.info("字典标签[{}]改名为[{}]", current.getTagName(), display); - return userTagMapper.selectById(current.getId()); + return tagDictionaryService.renameDictionaryTag(id, newName); } @Override public void deleteDictionaryTag(Integer id) throws NotFindEntitiesException { - UserTagEntity existing = requireDictionaryTag(id); - // 逻辑删除:只影响候选,对象上已经打好的标记不在此表里,不受影响 - userTagMapper.deleteById(existing.getId()); - log.info("字典标签[{}]已删除", existing.getTagName()); + tagDictionaryService.deleteDictionaryTag(id); } @Override public List listTagCandidates(String keyword) { - String kw = keyword == null ? "" : keyword.trim().toLowerCase(Locale.ROOT); - // 归一化名 → 展示名;按归一化去重(大小写不敏感),字典展示名优先 - Map candidates = new LinkedHashMap<>(); - for (UserTagEntity tag : listDictionaryTags()) { - candidates.putIfAbsent(tag.getNormalizedName(), tag.getTagName()); - } - // 已使用过的用户标签(含自动任务名标签) - for (MarkerUsage usage : listUserTagUsage()) { - if (!StringUtils.hasText(usage.getMarkerName())) { - continue; - } - String name = usage.getMarkerName().trim(); - candidates.putIfAbsent(normalizeTagKey(name), name); - } - return candidates.values().stream() - .filter(name -> kw.isEmpty() || name.toLowerCase(Locale.ROOT).contains(kw)) - .sorted() - .collect(Collectors.toList()); + return tagDictionaryService.listTagCandidates(keyword); } @Override + @Transactional(rollbackFor = Exception.class) public void removeAllMarkers(MarkerObjectTypeEnum objectType, String objectNum) { if (objectType == null || !StringUtils.hasText(objectNum)) { return; } + recallPrivacyService.begin(); // 对象即将消失:先记下它的用户标签,才能把相关标签导图置「待更新」(闭环-04) List removedTags = List.of(); if (objectType == MarkerObjectTypeEnum.FRAGMENT) { - removedTags = markerMapper.selectList(Wrappers.lambdaQuery() + removedTags = markerMapper + .selectList(Wrappers.lambdaQuery() .eq(MarkerEntity::getObjectType, objectType.name()) .eq(MarkerEntity::getObjectNum, objectNum.trim()) .eq(MarkerEntity::getKind, MarkerKindEnum.USER.name()) @@ -361,6 +306,7 @@ public class MarkerServiceImpl implements MarkerService { log.info("对象[{}/{}]的 {} 条标记已随对象删除", objectType, objectNum, removed); } markTagMindMapsStale(objectType, removedTags); + recallPrivacyService.tagsChanged(); } /** 碎片标签发生变化时的下游影响:相关标签导图置「待更新」,重建由用户手动触发(闭环-04) */ @@ -380,41 +326,6 @@ public class MarkerServiceImpl implements MarkerService { return existing; } - private UserTagEntity requireDictionaryTag(Integer id) throws NotFindEntitiesException { - UserTagEntity existing = id == null ? null : userTagMapper.selectById(id); - if (existing == null) { - log.warn("未能找到标签字典项id[{}]", id); - throw new NotFindEntitiesException("这个标签不存在或已被删除"); - } - return existing; - } - - /** 归一化标签名:去首尾空白 + 小写;用于字典去重与候选过滤(中文不受影响,英文大小写不敏感) */ - private String normalizeTagKey(String tagName) { - return tagName.trim().toLowerCase(Locale.ROOT); - } - - /** 打标签时输入的新名字自动补进字典(闭环-03);失败只记日志,不影响打标本身 */ - private void ensureDictionaryEntry(String tagName) { - try { - createDictionaryTag(tagName); - } catch (ErrorParameterException e) { - log.warn("标签[{}]加入字典失败:{}", tagName, e.getMessage()); - } - } - - /** 标签名规范化:去首尾空白并限制长度 */ - private String normalizeTagName(String markerName) throws ErrorParameterException { - if (!StringUtils.hasText(markerName)) { - throw new ErrorParameterException("标签名不能为空"); - } - String name = markerName.trim(); - if (name.length() > MAX_MARKER_NAME_LENGTH) { - throw new ErrorParameterException("标签名太长了,请控制在 " + MAX_MARKER_NAME_LENGTH + " 个字符以内"); - } - return name; - } - /** * 校验标记对象存在,并规范化对象标识。 *

碎片的对象标识由数字 id 转成字符串,保证与查询时一致。

diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/PriorityWeightsServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/PriorityWeightsServiceImpl.java index 95c8172..012894c 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/PriorityWeightsServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/PriorityWeightsServiceImpl.java @@ -9,13 +9,12 @@ import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.mapper.UserPriorityWeightsMapper; import com.guo.learningprogresstracker.service.PriorityWeightsService; import com.guo.learningprogresstracker.utils.CalculatedPriorityTool; +import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.List; - /** * 优先级权重配置服务实现 */ @@ -37,7 +36,7 @@ public class PriorityWeightsServiceImpl implements PriorityWeightsService { } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public UserPriorityWeightsEntity saveWeights(UserPriorityWeightsEntity weights) throws ErrorParameterException { validate(weights); @@ -72,11 +71,12 @@ public class PriorityWeightsServiceImpl implements PriorityWeightsService { private void validate(UserPriorityWeightsEntity weights) throws ErrorParameterException { double[] values = { - orZero(weights.getUrgencyWeight()), - orZero(weights.getImportanceWeight()), - orZero(weights.getContentDifficultyWeight()), - orZero(weights.getFutureValueWeight()), - orZero(weights.getSubjectivePriorityWeight())}; + orZero(weights.getUrgencyWeight()), + orZero(weights.getImportanceWeight()), + orZero(weights.getContentDifficultyWeight()), + orZero(weights.getFutureValueWeight()), + orZero(weights.getSubjectivePriorityWeight()) + }; double sum = 0; for (double v : values) { if (v < 0 || v > 1) { diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java deleted file mode 100644 index c1d4c3e..0000000 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/RecallCompareAiTaskHandler.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.guo.learningprogresstracker.service.impl; - -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; -import com.guo.learningprogresstracker.dto.ReviewTiming; -import com.guo.learningprogresstracker.entity.AiTaskEntity; -import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; -import com.guo.learningprogresstracker.exception.NotFindEntitiesException; -import com.guo.learningprogresstracker.exception.OperationFailedException; -import com.guo.learningprogresstracker.service.StandardMindMapService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import java.util.Map; - -/** - * 回忆对比任务(AI-02):把用户回忆大纲与标准导图对比并落回忆记录。 - * - *

这条链路原先在 {@code @Transactional} 里同步等待 AI 最长 10 分钟,会占满数据库连接池; - * 现在跑在 AI 任务执行器里,等待期间不持有任何请求期事务。

- */ -@Slf4j -@Component -@RequiredArgsConstructor -public class RecallCompareAiTaskHandler implements AiTaskHandler { - - private final StandardMindMapService standardMindMapService; - - @Override - public AiTaskTypeEnum type() { - return AiTaskTypeEnum.RECALL_COMPARE; - } - - @Override - public Map execute(AiTaskEntity task, Map params) { - String recallOutline = AiTaskParams.asString(params, "recallOutline"); - if (!StringUtils.hasText(recallOutline)) { - throw new AiTaskFailedException("请先填写回忆大纲"); - } - String focusPath = AiTaskParams.asString(params, "focusPath"); - ReviewTiming timing = new ReviewTiming( - AiTaskParams.asLocalDateTime(params, "reviewStartedAt"), - AiTaskParams.asLocalDateTime(params, "reviewLastInteractionAt"), - AiTaskParams.asInteger(params, "reviewDurationSeconds")); - - try { - RecallCompareOutcome outcome = standardMindMapService.recallCompare( - task.getTargetNum(), recallOutline, focusPath, timing); - return outcome.toPayload(); - } catch (NotFindEntitiesException e) { - throw new AiTaskFailedException(e.getMessage()); - } catch (OperationFailedException e) { - throw new AiTaskFailedException(e.getMessage()); - } - } -} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java index c4bc4e5..92c5f5e 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java @@ -1,339 +1,101 @@ package com.guo.learningprogresstracker.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.guo.learningprogresstracker.dto.IdRange; import com.guo.learningprogresstracker.dto.ReviewFeedItem; +import com.guo.learningprogresstracker.dto.ReviewSortPreference; import com.guo.learningprogresstracker.dto.ReviewSummary; import com.guo.learningprogresstracker.dto.ReviewTaskStats; import com.guo.learningprogresstracker.dto.StudyReportDetail; -import com.guo.learningprogresstracker.dto.TaskRecallRatio; -import com.guo.learningprogresstracker.dto.TaskContentCount; -import com.guo.learningprogresstracker.dto.TaskReviewDuration; -import com.guo.learningprogresstracker.dto.TaskSessionStats; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import com.guo.learningprogresstracker.entity.UserReviewPreferencesEntity; +import com.guo.learningprogresstracker.dto.request.ReviewFeedbackRequest; +import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.entity.StudySessionsEntity; import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.entity.UserReviewPreferencesEntity; import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum; import com.guo.learningprogresstracker.enums.ReviewSortPresetEnum; -import com.guo.learningprogresstracker.dto.ReviewSortPreference; -import com.guo.learningprogresstracker.dto.request.ReviewFeedbackRequest; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; -import com.guo.learningprogresstracker.mapper.ReviewRecallRecordMapper; import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.StudyReportsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.mapper.UserReviewPreferencesMapper; -import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest; import com.guo.learningprogresstracker.service.ReviewService; import com.guo.learningprogresstracker.service.StudyExpectationsService; import com.guo.learningprogresstracker.service.StudyReportFragmentsService; +import com.guo.learningprogresstracker.service.recall.RecallPrivacyService; +import com.guo.learningprogresstracker.service.review.ReviewFeedService; +import com.guo.learningprogresstracker.service.review.ReviewStatsService; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.*; -import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.Collectors; -import java.util.stream.Stream; - /** * 复习模块 Service 实现 + * + *

本类保留报告与碎片自身的读写(详情、修改、删除、反馈、接触、排序偏好), + * feed 的组织交给 {@link ReviewFeedService},统计口径交给 {@link ReviewStatsService}。

*/ @Slf4j @Service @RequiredArgsConstructor public class ReviewServiceImpl implements ReviewService { - private static final int DEFAULT_LIMIT = 30; - private static final int MAX_LIMIT = 100; - private static final String RANDOM_MODE = "random"; - private static final String SMART_MODE = "smart"; - private static final int SMART_CANDIDATE_MULTIPLIER = 5; - private static final String SOURCE_REPORT = "REPORT"; - private static final String SOURCE_FRAGMENT = "FRAGMENT"; /** 待归类分组在内部的键名(不会作为任务编号出现在响应里,响应里 taskNum 为 null) */ private static final String PENDING_OWNERSHIP_KEY = "__PENDING__"; - /** Feed 条目只返回这么长的摘要;全文由详情接口按需拉取(复习-05) */ - private static final int FEED_SUMMARY_MAX_LENGTH = 200; - /** 时间效应封顶天数 */ - private static final int AGE_CEILING_DAYS = 90; - /** 「稍后再看」的权重倍数(提高出现概率) */ - private static final double REVISIT_FACTOR = 1.6; - /** 「已掌握」的权重倍数:降低但不归零,保留文档要求的随机性 */ - private static final double MASTERED_FACTOR = 0.3; private final StudyReportsMapper studyReportsMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final StudyReportFragmentsService studyReportFragmentsService; private final StudySessionsMapper studySessionsMapper; private final TasksMapper tasksMapper; - private final ReviewRecallRecordMapper reviewRecallRecordMapper; private final StudyExpectationsService studyExpectationsService; private final UserReviewPreferencesMapper userReviewPreferencesMapper; + private final RecallPrivacyService recallPrivacyService; + private final ReviewFeedService reviewFeedService; + private final ReviewStatsService reviewStatsService; @Override public List getReviewFeed(int limit, String mode) { - int safeLimit = normalizeLimit(limit); - if (SMART_MODE.equalsIgnoreCase(mode)) { - return getSmartFeed(safeLimit); - } - boolean random = RANDOM_MODE.equalsIgnoreCase(mode); - - List fragments = random - ? randomFragments(safeLimit) - : studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() - .orderByDesc(StudyReportFragmentsEntity::getCreatedTime) - .last("LIMIT " + safeLimit)); - - List items = mergeAndConvert(List.of(), fragments); - if (random) { - Collections.shuffle(items); - } - return items.stream().limit(safeLimit).collect(Collectors.toList()); - } - - /** - * 随机取样知识碎片(复习-03)。 - * - *

不使用 {@code ORDER BY RAND()}:那在 MySQL 上是全表随机排序,一次 Feed 请求会触发两次。 - * 改为「随机起点 + 顺序取窗口」:先取主键区间,随机选一个起点,再按 id 顺序取够数量; - * 不足时从头回绕补齐(id 与创建时间同向,回绕等价于取更早的内容)。删除造成的 id 空洞会让 - * 靠后的内容被略微偏重,对「偶遇式」的 Feed 来说可以接受。

- */ - private List randomFragments(int limit) { - IdRange range = studyReportFragmentsMapper.selectIdRange(); - if (range == null || range.isEmpty()) { - return Collections.emptyList(); - } - - long start = range.getMinId() - + (long) (ThreadLocalRandom.current().nextDouble() * range.span()); - - // 用 LinkedHashMap 去重:回绕补齐时可能取到与首轮相同的行 - Map picked = new LinkedHashMap<>(); - collectFrom(start, limit, picked); - if (picked.size() < limit) { - collectFrom(range.getMinId(), limit - picked.size(), picked); - } - return new ArrayList<>(picked.values()); - } - - /** 从 startId 起按 id 顺序取至多 count 条,按主键去重后并入 picked */ - private void collectFrom(long startId, int count, Map picked) { - if (count <= 0) { - return; - } - List window = studyReportFragmentsMapper.selectList( - Wrappers.lambdaQuery() - .ge(StudyReportFragmentsEntity::getId, startId) - .orderByAsc(StudyReportFragmentsEntity::getId) - .last("LIMIT " + count)); - for (StudyReportFragmentsEntity fragment : window) { - picked.putIfAbsent(fragment.getId(), fragment); - } - } - - /** - * 智能模式:加权随机采样,让更需要复习的内容有更高概率出现。 - * 权重 = 时间衰减(越久未见权重越高) × 任务回忆掌握度(覆盖率越低权重越高)。 - * 仍保持随机性,只是"随机得不那么均匀"——符合复习模块无压力、偶遇式的设计理念。 - */ - private List getSmartFeed(int safeLimit) { - int candidateLimit = Math.min(safeLimit * SMART_CANDIDATE_MULTIPLIER, 500); - - List fragments = randomFragments(candidateLimit); - - List candidates = mergeAndConvert(List.of(), fragments); - if (candidates.size() <= safeLimit) { - Collections.shuffle(candidates); - return candidates; - } - - // 各任务最近一次回忆对比的覆盖率(没有记录视为 0 = 最需要复习) - Map taskRecallRatio = latestRecallRatioByTask( - candidates.stream().map(ReviewFeedItem::getTaskNum) - .filter(Objects::nonNull).collect(Collectors.toSet())); - - LocalDateTime now = LocalDateTime.now(); - // 排序信号强度由用户的档位决定(复习-01) - ReviewSortPresetEnum preset = loadSortPreset(); - List weights = new ArrayList<>(candidates.size()); - for (ReviewFeedItem item : candidates) { - weights.add(reviewNeedWeight(item, taskRecallRatio, now, preset)); - } - return weightedSample(candidates, weights, safeLimit); - } - - /** - * 单条内容的复习需求权重:三个信号相乘。 - * - *
    - *
  1. 多久没接触:从「最近接触时间」算起(没有则用创建时间),90 天封顶。
  2. - *
  3. 任务掌握度:最近一次回忆覆盖率越低权重越高。
  4. - *
  5. 反馈动作:「稍后再看」提高权重;「已掌握」降低但不归零——文档要求保留随机性, - * 「每条内容都有机会出现」。
  6. - *
- * - *

前两个信号的相对强度由用户的排序档位决定(复习-01)。

- */ - private double reviewNeedWeight(ReviewFeedItem item, Map taskRecallRatio, - LocalDateTime now, ReviewSortPresetEnum preset) { - // 信号一:时间效应。以「最近接触时间」为准,这样展开看过的内容会重新变「新」 - LocalDateTime basis = item.getLastReviewedTime() != null ? item.getLastReviewedTime() : item.getCreatedTime(); - double ageDays = basis == null ? 30 - : Math.max(0, java.time.Duration.between(basis, now).toDays()); - double ageProgress = Math.min(ageDays, AGE_CEILING_DAYS) / AGE_CEILING_DAYS; - double ageFactor = (1 - preset.getAgeInfluence()) + ageProgress * preset.getAgeInfluence(); - - // 信号二:任务掌握度 - double ratio = item.getTaskNum() == null ? 0 - : taskRecallRatio.getOrDefault(item.getTaskNum(), 0D); - double masteryFactor = 1.0 - ratio * preset.getMasteryInfluence(); - - // 信号三:反馈动作。「稍后再看」是明确的「想再看」,优先于「已掌握」 - double feedbackFactor = 1.0; - if (Boolean.TRUE.equals(item.getRevisit())) { - feedbackFactor = REVISIT_FACTOR; - } else if (Boolean.TRUE.equals(item.getMastered())) { - feedbackFactor = MASTERED_FACTOR; - } - - return ageFactor * masteryFactor * feedbackFactor; - } - - /** 查询每个任务最近一次回忆对比的覆盖率 */ - private Map latestRecallRatioByTask(Set taskNums) { - if (taskNums.isEmpty()) { - return Collections.emptyMap(); - } - // 复习-04:在 SQL 侧按任务分组取最新一条,只带回 任务编号 + 覆盖率 - Map result = new HashMap<>(); - for (TaskRecallRatio row : reviewRecallRecordMapper.selectLatestRatioByTask(taskNums)) { - result.put(row.getTaskNum(), row.getRecallRatio() == null ? 0D : row.getRecallRatio()); - } - return result; - } - - /** 按权重不放回采样 */ - private List weightedSample(List items, List weights, int count) { - List pool = new ArrayList<>(items); - List poolWeights = new ArrayList<>(weights); - List selected = new ArrayList<>(count); - Random random = new Random(); - - while (selected.size() < count && !pool.isEmpty()) { - double total = poolWeights.stream().mapToDouble(Double::doubleValue).sum(); - double r = random.nextDouble() * total; - double cumulative = 0; - int chosen = pool.size() - 1; - for (int i = 0; i < pool.size(); i++) { - cumulative += poolWeights.get(i); - if (r <= cumulative) { - chosen = i; - break; - } - } - selected.add(pool.remove(chosen)); - poolWeights.remove(chosen); - } - return selected; + return reviewFeedService.getReviewFeed(limit, mode); } @Override public ReviewSummary summary() { - // 口径必须与 /review/tasks 的列表一致(列表逐页相加 == 这里的汇总): - // 报告按「报告 → 会话 → 任务」归属,碎片按内容归属(owner_task_num)统计。 - // 不能用裸表的 selectCount:那样「学习残片」会把待归类碎片也算进来, - // 与列表逐页相加的结果对不上(待归类在总览里有独立区块展示)。 - return new ReviewSummary( - tasksMapper.selectCount(null), - studyReportsMapper.countOwnedReports(), - studyReportFragmentsMapper.countOwnedFragments()); + return reviewStatsService.summary(); } @Override public Page getReviewTaskStats(int pageNum, int pageSize, String markerName) { - // 点标签即筛选:过滤下推到 SQL(EXISTS 子查询),由数据库一次算出命中任务并分页; - // 不再「先查全部命中对象号、再拼 IN 回查」——命中量大时 IN 会膨胀。 - IPage taskPage; - if (StringUtils.hasText(markerName)) { - taskPage = tasksMapper.selectPageByMarker(new Page<>(pageNum, pageSize), markerName.trim()); - } else { - taskPage = tasksMapper.selectPage(new Page<>(pageNum, pageSize), - Wrappers.lambdaQuery() - .orderByDesc(TaskEntity::getCalculatedPriority) - // 优先级相同的任务之间要有稳定次序,否则翻页会重复或漏掉 - .orderByDesc(TaskEntity::getId)); - } - List stats = taskPage.getRecords().stream() - .map(this::newTaskStats) - .collect(Collectors.toList()); - // 聚合只算这一页的任务,不再对全部任务做 IN 聚合 - fillReviewTaskStats(stats); - - Page result = new Page<>(taskPage.getCurrent(), taskPage.getSize(), taskPage.getTotal()); - result.setRecords(stats); - return result; + return reviewStatsService.getReviewTaskStats(pageNum, pageSize, markerName); } @Override public ReviewTaskStats getReviewTaskStats(String taskNum) { - TaskEntity task = tasksMapper.selectList( - Wrappers.lambdaQuery() - .eq(TaskEntity::getTaskNum, taskNum) - .last("LIMIT 1")) - .stream() - .findFirst() - .orElse(null); - - ReviewTaskStats stats = newTaskStats(taskNum, task == null ? null : task.getTaskName()); - fillReviewTaskStats(Collections.singletonList(stats)); - return stats; + return reviewStatsService.getReviewTaskStats(taskNum); } @Override public List getTaskReview(String taskNum) { - // 报告按会话生成:取属于该任务的会话所产生的报告 - List sessionNums = studySessionsMapper.selectList( - Wrappers.lambdaQuery() - .eq(StudySessionsEntity::getTaskNum, taskNum) - .select(StudySessionsEntity::getSessionNum)) - .stream() - .map(StudySessionsEntity::getSessionNum) - .collect(Collectors.toList()); - - List reports = sessionNums.isEmpty() ? List.of() - : studyReportsMapper.selectList( - Wrappers.lambdaQuery() - .in(StudyReportsEntity::getSessionNum, sessionNums) - .orderByDesc(StudyReportsEntity::getCreatedTime)); - - // 知识碎片按内容归属:只看它属于谁,不看它产生于哪次会话(归属-01) - List fragments = studyReportFragmentsMapper.selectList( - Wrappers.lambdaQuery() - .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) - .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)); - - return mergeAndConvert(reports, fragments); + return reviewFeedService.getTaskReview(taskNum); } @Override public StudyReportsEntity getReportDetail(int id) throws NotFindEntitiesException { - return Optional.ofNullable(studyReportsMapper.selectById(id)) - .orElseThrow(() -> { - log.warn("学习报告[{}]不存在", id); - return new NotFindEntitiesException("这份学习报告不存在或已被删除"); - }); + return Optional.ofNullable(studyReportsMapper.selectById(id)).orElseThrow(() -> { + log.warn("学习报告[{}]不存在", id); + return new NotFindEntitiesException("这份学习报告不存在或已被删除"); + }); } @Override @@ -355,8 +117,9 @@ public class ReviewServiceImpl implements ReviewService { .ifPresent(e -> detail.setSessionExpectation(e.getDescription())); // 第四部分不落库:按会话产生的碎片 + 它们的**当前**内容归属实时聚合 - List fragments = studyReportFragmentsMapper.selectList( - Wrappers.lambdaQuery() + List fragments = + studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() + .eq(StudyReportFragmentsEntity::getContextType, FragmentContextTypeEnum.SESSION.name()) .eq(StudyReportFragmentsEntity::getContextNum, report.getSessionNum()) .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); @@ -369,8 +132,7 @@ public class ReviewServiceImpl implements ReviewService { created.setTaskNum(StringUtils.hasText(owner) ? owner : null); created.setTaskName(StringUtils.hasText(owner) ? loadTaskName(owner) : null); // 旁支 = 归属不是本会话所属任务的内容 - created.setBranch(!StringUtils.hasText(owner) - || !Objects.equals(owner, detail.getSessionTaskNum())); + created.setBranch(!StringUtils.hasText(owner) || !Objects.equals(owner, detail.getSessionTaskNum())); return created; }); group.getFragments().add(fragment); @@ -382,20 +144,32 @@ public class ReviewServiceImpl implements ReviewService { @Override public void updateReport(int id, UpdateStudyReportRequest request) throws NotFindEntitiesException { StudyReportsEntity existing = getReportDetail(id); - StudyReportsEntity patch = new StudyReportsEntity(); - patch.setId(existing.getId()); - patch.setSessionSummary(request.getSessionSummary()); - patch.setExpectationVerdict(request.getExpectationVerdict()); - patch.setFreeSummary(request.getFreeSummary()); - studyReportsMapper.updateById(patch); + studyReportsMapper.update( + new StudyReportsEntity(), + Wrappers.lambdaUpdate() + .eq(StudyReportsEntity::getId, existing.getId()) + .set( + request.getSessionSummary() != null, + StudyReportsEntity::getSessionSummary, + request.getSessionSummary()) + .set( + request.getExpectationVerdict() != null, + StudyReportsEntity::getExpectationVerdict, + request.getExpectationVerdict()) + .set( + request.getFreeSummary() != null, + StudyReportsEntity::getFreeSummary, + request.getFreeSummary())); // 报告-02:报告内容作为导图参考上下文,改动后相关导图置「待更新」 studyReportFragmentsService.markMindMapsStaleForSession(existing.getSessionNum()); log.info("学习报告[{}]已修改", id); } @Override + @org.springframework.transaction.annotation.Transactional public void deleteReport(int id) throws NotFindEntitiesException { StudyReportsEntity existing = getReportDetail(id); + recallPrivacyService.sourceDeleted("REPORT", Integer.toString(id)); // 软删除。刻意不连带删除同一会话的知识碎片:碎片是独立原料,可能已被归类到其他任务 studyReportsMapper.deleteById(existing.getId()); // 报告-02:报告不再作为参考上下文,相关导图置「待更新」 @@ -408,21 +182,22 @@ public class ReviewServiceImpl implements ReviewService { public ReviewFeedbackRequest submitFeedback(Integer fragmentId, ReviewFeedbackRequest request) throws NotFindEntitiesException { StudyReportFragmentsEntity existing = getFragmentForUpdate(fragmentId); - StudyReportFragmentsEntity patch = new StudyReportFragmentsEntity(); - patch.setId(fragmentId); - boolean changed = false; - if (request.getMastered() != null) { - patch.setMastered(request.getMastered()); - changed = true; - } - if (request.getRevisit() != null) { - patch.setRevisit(request.getRevisit()); - changed = true; - } - if (changed) { + boolean feedbackChanged = request.getMastered() != null || request.getRevisit() != null; + if (feedbackChanged) { // 反馈动作同时算一次接触:用户刚刚看过这条内容 - patch.setLastReviewedTime(LocalDateTime.now()); - studyReportFragmentsMapper.updateById(patch); + studyReportFragmentsMapper.update( + new StudyReportFragmentsEntity(), + Wrappers.lambdaUpdate() + .eq(StudyReportFragmentsEntity::getId, fragmentId) + .set( + request.getMastered() != null, + StudyReportFragmentsEntity::getMastered, + request.getMastered()) + .set( + request.getRevisit() != null, + StudyReportFragmentsEntity::getRevisit, + request.getRevisit()) + .set(StudyReportFragmentsEntity::getLastReviewedTime, LocalDateTime.now())); } ReviewFeedbackRequest result = new ReviewFeedbackRequest(); result.setMastered(request.getMastered() != null ? request.getMastered() : existing.getMastered()); @@ -433,10 +208,11 @@ public class ReviewServiceImpl implements ReviewService { @Override public void touchFragment(Integer fragmentId) throws NotFindEntitiesException { getFragmentForUpdate(fragmentId); - StudyReportFragmentsEntity patch = new StudyReportFragmentsEntity(); - patch.setId(fragmentId); - patch.setLastReviewedTime(LocalDateTime.now()); - studyReportFragmentsMapper.updateById(patch); + studyReportFragmentsMapper.update( + new StudyReportFragmentsEntity(), + Wrappers.lambdaUpdate() + .eq(StudyReportFragmentsEntity::getId, fragmentId) + .set(StudyReportFragmentsEntity::getLastReviewedTime, LocalDateTime.now())); } /** 反馈与接触都要先确认碎片存在(属于当前用户由租户拦截器保证) */ @@ -451,7 +227,7 @@ public class ReviewServiceImpl implements ReviewService { @Override public ReviewSortPreference getSortPreference() { - return toPreference(loadSortPreset()); + return toPreference(reviewFeedService.loadSortPreset()); } @Override @@ -464,24 +240,16 @@ public class ReviewServiceImpl implements ReviewService { created.setSortPreset(parsed.name()); userReviewPreferencesMapper.insert(created); } else { - UserReviewPreferencesEntity patch = new UserReviewPreferencesEntity(); - patch.setId(existing.getId()); - patch.setSortPreset(parsed.name()); - userReviewPreferencesMapper.updateById(patch); + userReviewPreferencesMapper.update( + new UserReviewPreferencesEntity(), + Wrappers.lambdaUpdate() + .eq(UserReviewPreferencesEntity::getId, existing.getId()) + .set(UserReviewPreferencesEntity::getSortPreset, parsed.name())); } log.info("复习排序偏好已更新为[{}]", parsed); return toPreference(parsed); } - /** 读取当前用户的排序档位;未设置或存坏时回落默认 */ - private ReviewSortPresetEnum loadSortPreset() { - UserReviewPreferencesEntity preference = userReviewPreferencesMapper.selectOne( - Wrappers.lambdaQuery().last("LIMIT 1")); - return preference == null - ? ReviewSortPresetEnum.DEFAULT - : ReviewSortPresetEnum.parse(preference.getSortPreset()); - } - private static ReviewSortPreference toPreference(ReviewSortPresetEnum preset) { return new ReviewSortPreference(preset.name(), preset.getDescription()); } @@ -490,7 +258,8 @@ public class ReviewServiceImpl implements ReviewService { if (!StringUtils.hasText(taskNum)) { return null; } - return tasksMapper.selectOne(Wrappers.lambdaQuery() + return tasksMapper + .selectOne(Wrappers.lambdaQuery() .eq(TaskEntity::getTaskNum, taskNum) .select(TaskEntity::getTaskName) .last("LIMIT 1")) @@ -499,232 +268,17 @@ public class ReviewServiceImpl implements ReviewService { @Override public StudyReportFragmentsEntity getFragmentDetail(int id) throws NotFindEntitiesException { - return Optional.ofNullable(studyReportFragmentsMapper.selectById(id)) - .orElseThrow(() -> { - log.warn("学习残片[{}]不存在", id); - return new NotFindEntitiesException("这条学习残片不存在或已被删除"); - }); - } - - /** - * 将报告和残片合并转换为 ReviewFeedItem 列表,按创建时间倒序排列 - */ - private List mergeAndConvert(List reports, - List fragments) { - // 报告的任务取自它所属的会话(报告按会话生成) - Set reportSessionNums = reports.stream() - .map(StudyReportsEntity::getSessionNum) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Map sessionToTaskMap = reportSessionNums.isEmpty() - ? Collections.emptyMap() - : studySessionsMapper.selectList( - Wrappers.lambdaQuery() - .in(StudySessionsEntity::getSessionNum, reportSessionNums) - .select(StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum)) - .stream() - .collect(Collectors.toMap( - StudySessionsEntity::getSessionNum, - StudySessionsEntity::getTaskNum, - (a, b) -> a)); - - // 碎片的任务取自它自己的内容归属 - Set taskNums = new HashSet<>(sessionToTaskMap.values()); - fragments.stream() - .map(StudyReportFragmentsEntity::getOwnerTaskNum) - .filter(StringUtils::hasText) - .forEach(taskNums::add); - taskNums.removeIf(num -> !StringUtils.hasText(num)); - - Map taskNameMap = taskNums.isEmpty() ? Collections.emptyMap() - : tasksMapper.selectList( - Wrappers.lambdaQuery() - .in(TaskEntity::getTaskNum, taskNums) - .select(TaskEntity::getTaskNum, TaskEntity::getTaskName)) - .stream() - .collect(Collectors.toMap( - TaskEntity::getTaskNum, - task -> task.getTaskName() == null ? "" : task.getTaskName(), - (a, b) -> a)); - - List reportItems = reports.stream().map(r -> { - ReviewFeedItem item = new ReviewFeedItem(); - item.setId(r.getId()); - item.setSourceType(SOURCE_REPORT); - applySummary(item, reportDisplayText(r)); - item.setCreatedTime(r.getCreatedTime()); - item.setContextType(FragmentContextTypeEnum.SESSION.name()); - item.setContextNum(r.getSessionNum()); - String taskNum = sessionToTaskMap.get(r.getSessionNum()); - item.setTaskNum(taskNum); - item.setTaskName(taskNum != null ? taskNameMap.get(taskNum) : null); - return item; - }).collect(Collectors.toList()); - - List fragmentItems = fragments.stream().map(f -> { - ReviewFeedItem item = new ReviewFeedItem(); - item.setId(f.getId()); - item.setSourceType(SOURCE_FRAGMENT); - applySummary(item, f.getContent()); - item.setCreatedTime(f.getCreatedTime()); - item.setContextType(f.getContextType()); - item.setContextNum(f.getContextNum()); - // 内容归属:为空即「待归类」,前端据此打标并提供就地归类入口 - item.setPendingOwnership(f.isPendingOwnership()); - // 反馈状态与最近接触时间只参与排序计算,不用于列表展示(复习-02:不产生状态展示) - item.setMastered(f.getMastered()); - item.setRevisit(f.getRevisit()); - item.setLastReviewedTime(f.getLastReviewedTime()); - item.setTaskNum(f.getOwnerTaskNum()); - item.setTaskName(StringUtils.hasText(f.getOwnerTaskNum()) - ? taskNameMap.get(f.getOwnerTaskNum()) : null); - return item; - }).collect(Collectors.toList()); - - return Stream.concat(reportItems.stream(), fragmentItems.stream()) - .sorted(Comparator.comparing(ReviewFeedItem::getCreatedTime, - Comparator.nullsLast(Comparator.reverseOrder()))) - .collect(Collectors.toList()); - } - - /** - * 把原文放进 Feed 条目:只保留摘要与总长度(复习-05)。 - *

摘要把换行压成空格,避免多行内容在列表里撑高卡片。

- */ - private static void applySummary(ReviewFeedItem item, String rawContent) { - String full = rawContent == null ? "" : rawContent; - item.setContentLength(full.length()); - if (full.length() <= FEED_SUMMARY_MAX_LENGTH) { - item.setContent(full); - item.setContentTruncated(false); - return; - } - String summary = full.substring(0, FEED_SUMMARY_MAX_LENGTH) - .replaceAll("\\s+", " ") - .trim(); - item.setContent(summary); - item.setContentTruncated(true); - } - - /** - * 报告在列表/Feed 中的展示文本:结构化报告由三段组成,这里按段拼接。 - */ - private static String reportDisplayText(StudyReportsEntity report) { - StringBuilder text = new StringBuilder(); - appendSection(text, "会话摘要", report.getSessionSummary()); - appendSection(text, "预期达成判断", report.getExpectationVerdict()); - appendSection(text, "自由总结", report.getFreeSummary()); - return text.length() == 0 ? "" : text.toString().trim(); - } - - private static void appendSection(StringBuilder text, String title, String body) { - if (body == null || body.isBlank()) { - return; - } - if (text.length() > 0) { - text.append("\n\n"); - } - text.append("【").append(title).append("】\n").append(body.trim()); - } - - private ReviewTaskStats newTaskStats(TaskEntity task) { - return newTaskStats(task.getTaskNum(), task.getTaskName()); - } - - private ReviewTaskStats newTaskStats(String taskNum, String taskName) { - ReviewTaskStats stats = new ReviewTaskStats(); - stats.setTaskNum(taskNum); - stats.setTaskName(taskName); - return stats; - } - - private int normalizeLimit(int limit) { - if (limit <= 0) { - return DEFAULT_LIMIT; - } - return Math.min(limit, MAX_LIMIT); + return Optional.ofNullable(studyReportFragmentsMapper.selectById(id)).orElseThrow(() -> { + log.warn("学习残片[{}]不存在", id); + return new NotFindEntitiesException("这条学习残片不存在或已被删除"); + }); } private void ensureTaskExists(String taskNum) throws NotFindEntitiesException { - if (!StringUtils.hasText(taskNum) || !tasksMapper.exists( - Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { + if (!StringUtils.hasText(taskNum) + || !tasksMapper.exists(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { log.warn("任务[{}]不存在", taskNum); throw new NotFindEntitiesException("这个任务不存在或已被删除"); } } - - /** - * 填充任务维度统计(数据-02):三类聚合(会话统计、报告数、碎片数)全部下推到 SQL, - * 每次查询只返回「任务数」量级的行,不随历史会话/内容条数线性增长。 - */ - private void fillReviewTaskStats(List statsList) { - Map statsByTaskNum = statsList.stream() - .filter(item -> StringUtils.hasText(item.getTaskNum())) - .collect(Collectors.toMap( - ReviewTaskStats::getTaskNum, - item -> item, - (a, b) -> a, - LinkedHashMap::new)); - - if (statsByTaskNum.isEmpty()) { - return; - } - - Set taskNums = statsByTaskNum.keySet(); - LocalDateTime todayStart = LocalDate.now().atStartOfDay(); - LocalDateTime weekStart = LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay(); - - for (TaskSessionStats row : studySessionsMapper.sumStudyStatsByTask(taskNums, todayStart, weekStart)) { - ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); - if (stats == null) { - continue; - } - long sessionCount = row.getSessionCount() == null ? 0L : row.getSessionCount(); - stats.setSessionCount(sessionCount); - stats.setEffectiveTime(nullToZero(row.getEffectiveTime())); - stats.setTodayEffectiveTime(nullToZero(row.getTodayEffectiveTime())); - stats.setWeekEffectiveTime(nullToZero(row.getWeekEffectiveTime())); - if (sessionCount > 0) { - stats.setAvgEffectiveTime(stats.getEffectiveTime() / sessionCount); - stats.setAvgEffectivenessRatio(nullToZero(row.getEffectivenessRatioSum()) / sessionCount); - } - } - - fillContentCounts(statsByTaskNum, taskNums); - fillReviewDuration(statsByTaskNum); - } - - /** 报告数与碎片数:同样在 SQL 侧按内容归属分组计数 */ - private void fillContentCounts(Map statsByTaskNum, Set taskNums) { - for (TaskContentCount row : studyReportsMapper.countReportsByTask(taskNums)) { - ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); - if (stats != null) { - stats.setReportCount(row.getContentCount() == null ? 0L : row.getContentCount()); - } - } - for (TaskContentCount row : studyReportFragmentsMapper.countFragmentsByTask(taskNums)) { - ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); - if (stats != null) { - stats.setFragmentCount(row.getContentCount() == null ? 0L : row.getContentCount()); - } - } - } - - private static double nullToZero(Double value) { - return value == null ? 0D : value; - } - - /** - * 按任务汇总复习行为累计耗时(复习-07)。聚合在 SQL 侧完成,只把任务数量的行拉回内存, - * 不随回忆记录条数增长;结果由 {@code TaskReviewDuration} 承载,不走 Map。 - */ - private void fillReviewDuration(Map statsByTaskNum) { - List rows = reviewRecallRecordMapper.sumReviewDurationByTask(statsByTaskNum.keySet()); - for (TaskReviewDuration row : rows) { - ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); - if (stats != null && row.getReviewDurationSeconds() != null) { - stats.setReviewDurationSeconds(row.getReviewDurationSeconds()); - } - } - } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java index 88e4e5a..61ff22d 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewTagMindMapServiceImpl.java @@ -4,51 +4,43 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.dto.FragmentTagMatch; -import com.guo.learningprogresstracker.dto.MindMapReportContext; -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; -import com.guo.learningprogresstracker.dto.ReviewTiming; import com.guo.learningprogresstracker.dto.TagMindMapSummary; import com.guo.learningprogresstracker.dto.TagMindMapView; import com.guo.learningprogresstracker.dto.TagScope; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.TaskEntity; -import com.guo.learningprogresstracker.enums.ReviewScopeTypeEnum; 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.ReviewRecallRecordMapper; import com.guo.learningprogresstracker.mapper.ReviewTagMindMapMapper; import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.service.ReviewTagMindMapService; -import com.guo.learningprogresstracker.service.StandardMindMapService; -import com.guo.learningprogresstracker.utils.CompareResult; +import com.guo.learningprogresstracker.service.ai.MindMapOutlineGenerator; +import com.guo.learningprogresstracker.service.ai.MindMapReportContextLoader; +import com.guo.learningprogresstracker.utils.MindMapMatchTool; import com.guo.learningprogresstracker.utils.MindMapNode; import com.guo.learningprogresstracker.utils.MindMapTreeTool; -import com.guo.learningprogresstracker.utils.ReviewDurationTool; 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; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; /** * 标签思维导图服务实现(闭环-04)。 * - *

取材、生成、对比三条链路都刻意与任务导图共用口径:素材来自带这些标签的碎片(软删除的不取材), - * 生成走 {@link MindMapOutlineGenerator}(AI 优先、内置规则降级),对比走 - * {@link StandardMindMapService#compareWithRecall}(AI 语义对比、失败降级文本匹配)。

+ *

取材来自带这些标签的碎片,生成走 {@link MindMapOutlineGenerator}。 + * 复习提示与查漏由独立的自由回忆服务处理。

*/ @Slf4j @Service @@ -60,13 +52,11 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { private static final String GENERATOR_VERSION = "1.0"; /** 与标记、标签字典的列宽一致 */ - private static final int MAX_TAG_NAME_LENGTH = 100; + private static final int MAX_TAG_NAME_LENGTH = 255; private final ReviewTagMindMapMapper tagMindMapMapper; - private final ReviewRecallRecordMapper recallRecordMapper; private final MarkerMapper markerMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; - private final StandardMindMapService standardMindMapService; private final MindMapOutlineGenerator outlineGenerator; private final MindMapReportContextLoader reportContextLoader; private final ObjectMapper objectMapper; @@ -99,8 +89,11 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { 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); + return new TagScope( + TagScopeTool.scopeKey(canonicalTags, combineMode), + canonicalTags, + TagScopeTool.normalizedTags(canonicalTags), + combineMode); } // ============ 读取 ============ @@ -112,17 +105,9 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { view.setTags(scope.tags()); view.setMode(scope.mode().name()); view.setMap(queryByScopeKey(scope.scopeKey())); - view.setLatestRecallRecord(latestRecallRecord(scope.scopeKey())); return view; } - @Override - public List listRecallRecords(TagScope scope) { - return recallRecordMapper.selectList(Wrappers.lambdaQuery() - .eq(ReviewRecallRecordEntity::getScopeKey, scope.scopeKey()) - .orderByDesc(ReviewRecallRecordEntity::getCreatedTime)); - } - // ============ 列表 ============ @Override @@ -161,7 +146,7 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { // ============ 用户编辑 ============ @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public ReviewTagMindMapEntity updateByOutline(TagScope scope, String outline) { ReviewTagMindMapEntity existing = queryByScopeKey(scope.scopeKey()); boolean create = existing == null; @@ -209,7 +194,7 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { // 合并新旧树:保留用户编辑过的节点,追加新节点 MindMapNode oldRoot = MindMapTreeTool.fromJson(existing.getContent(), objectMapper); MindMapNode newRoot = MindMapTreeTool.fromJson(fresh.getContent(), objectMapper); - MindMapNode merged = MindMapTreeTool.mergeTrees(oldRoot, newRoot); + MindMapNode merged = MindMapMatchTool.mergeTrees(oldRoot, newRoot); existing.setContent(MindMapTreeTool.toJson(merged, objectMapper)); existing.setOutline(MindMapTreeTool.toFullOutline(merged)); @@ -223,101 +208,34 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { return existing; } - // ============ 回忆对比 ============ - - @Override - public RecallCompareOutcome recallCompare(TagScope scope, String recallOutline, String focusPath, - ReviewTiming timing) throws OperationFailedException { - // 1. 取该范围的标签导图;缺失时按需生成(可能调用 AI,故整个方法不持有事务) - ReviewTagMindMapEntity base = queryByScopeKey(scope.scopeKey()); - if (base == null) { - base = doGenerate(scope); - } - - // 2. 解析基准树;指定起点时只对比该子树 - MindMapNode standardRoot = MindMapTreeTool.fromJson(base.getContent(), objectMapper); - MindMapNode compareRoot = standardRoot; - if (StringUtils.hasText(focusPath)) { - MindMapNode subtree = MindMapTreeTool.extractSubtree(standardRoot, focusPath); - if (subtree == null) { - log.warn("focusPath 未匹配到节点,使用全量标签导图: scopeKey={}, path={}", scope.scopeKey(), focusPath); - } else { - compareRoot = subtree; - } - } - - // 3. 执行对比(AI 语义对比优先,失败降级文本匹配):与任务导图共用同一套口径 - CompareResult result = standardMindMapService.compareWithRecall(scope.displayName(), compareRoot, recallOutline); - - // 4. 序列化对比结果 - String resultJson; - try { - resultJson = objectMapper.writeValueAsString(result); - } catch (Exception e) { - log.error("标签范围[{}]对比结果序列化失败", scope.scopeKey(), e); - throw new OperationFailedException("对比结果解析失败了,请稍后再试"); - } - - // 5. 保存回忆记录:范围=标签集合 + 取数模式,任务列为空(任务范围的统计口径因此不受影响) - ReviewRecallRecordEntity record = new ReviewRecallRecordEntity(); - record.setTaskNum(null); - record.setScopeType(ReviewScopeTypeEnum.TAG.name()); - record.setScopeKey(scope.scopeKey()); - record.setScopeTags(TagScopeTool.toStoredTags(scope.tags())); - record.setScopeMode(scope.mode().name()); - record.setStandardMapId(base.getId()); - record.setFocusPath(StringUtils.hasText(focusPath) ? focusPath : null); - record.setRecallContent(recallOutline); - record.setCompareResult(resultJson); - record.setRecallRatio(result.getRecallRatio()); - record.setMatchedCount(result.getMatchedCount()); - record.setMissedCount(result.getMissedCount()); - record.setExtraCount(result.getExtraCount()); - record.setReviewDurationSeconds(ReviewDurationTool.resolveSeconds( - timing == null ? null : timing.startedAt(), - timing == null ? null : timing.lastInteractionAt(), - timing == null ? null : timing.durationSeconds(), - LocalDateTime.now())); - recallRecordMapper.insert(record); - - log.info("标签范围回忆对比: scopeKey={}, tags={}, mode={}, recallRatio={}, matched={}, missed={}, extra={}, 复习耗时={}秒", - scope.scopeKey(), scope.displayName(), scope.mode(), result.getRecallRatio(), - result.getMatchedCount(), result.getMissedCount(), result.getExtraCount(), - record.getReviewDurationSeconds()); - - return new RecallCompareOutcome(base.getId(), record.getId(), result.getRecallRatio(), - result.getMatchedCount(), result.getMissedCount(), result.getExtraCount()); - } - // ============ 素材变化 ============ @Override - @Transactional + @Transactional(rollbackFor = Exception.class) 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)); + Wrappers.lambdaQuery().eq(ReviewTagMindMapEntity::getNeedsUpdate, false)); int marked = 0; for (ReviewTagMindMapEntity map : maps) { - Set mapTags = Set.copyOf( - TagScopeTool.normalizedTags(TagScopeTool.parseStoredTags(map.getTagNames()))); + 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); + tagMindMapMapper.update( + new ReviewTagMindMapEntity(), + Wrappers.lambdaUpdate() + .eq(ReviewTagMindMapEntity::getId, map.getId()) + .set(ReviewTagMindMapEntity::getNeedsUpdate, true) + .set(ReviewTagMindMapEntity::getNeedsUpdateTime, LocalDateTime.now())); marked++; } if (marked > 0) { - log.info("标签[{}]的素材发生变化,{} 张标签导图已置为待更新(重建仍由用户手动触发)", - String.join("、", changed), marked); + log.info("标签[{}]的素材发生变化,{} 张标签导图已置为待更新(重建仍由用户手动触发)", String.join("、", changed), marked); } } @@ -334,8 +252,8 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { // 这里用一个不落库的临时 TaskEntity 承载它们,从而沿用既有的碎片 → 大纲生成链路 TaskEntity scopeTask = new TaskEntity(); scopeTask.setTaskName(scope.displayName()); - scopeTask.setTaskDescription("按标签复习:" + scope.displayName() - + "(" + scope.mode().getDescription() + "),共取材 " + fragments.size() + " 条知识碎片"); + scopeTask.setTaskDescription("按标签复习:" + scope.displayName() + "(" + + scope.mode().getDescription() + "),共取材 " + fragments.size() + " 条知识碎片"); MindMapOutlineGenerator.GeneratedOutline generated = outlineGenerator.generate(scopeTask, fragments, List.of(), reportContextLoader.load(fragments)); @@ -350,8 +268,8 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { 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.setSummary("共 " + MindMapTreeTool.countNodes(root) + " 个节点,最大层级 " + MindMapTreeTool.maxDepth(root) + + ",取材 " + fragments.size() + " 条碎片"); entity.setGenerator(generated.generatorName()); entity.setGeneratorVersion(GENERATOR_VERSION); entity.setSourceFragmentCount(fragments.size()); @@ -382,13 +300,6 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { .last("LIMIT 1")); } - private ReviewRecallRecordEntity latestRecallRecord(String scopeKey) { - return recallRecordMapper.selectOne(Wrappers.lambdaQuery() - .eq(ReviewRecallRecordEntity::getScopeKey, scopeKey) - .orderByDesc(ReviewRecallRecordEntity::getId) - .last("LIMIT 1")); - } - /** * 取数:带这些标签的知识碎片。并集取「带任一标签」,交集取「同时带全部标签」; * 软删除的碎片由 {@code @TableLogic} 自动排除。 @@ -396,7 +307,8 @@ public class ReviewTagMindMapServiceImpl implements ReviewTagMindMapService { private List loadFragments(TagScope scope) { List matches = markerMapper.countUserTagsPerFragment(scope.normalizedTags()); int requiredTagCount = scope.mode() == TagCombineModeEnum.INTERSECT - ? scope.normalizedTags().size() : 1; + ? scope.normalizedTags().size() + : 1; List fragmentIds = new ArrayList<>(); for (FragmentTagMatch match : matches) { 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 874b8a9..15fe2e4 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImpl.java @@ -1,57 +1,49 @@ package com.guo.learningprogresstracker.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.dto.MindMapReportContext; -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; -import com.guo.learningprogresstracker.dto.ReviewTiming; -import com.guo.learningprogresstracker.entity.*; -import com.guo.learningprogresstracker.enums.ReviewScopeTypeEnum; +import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.TaskApplicationEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; -import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.mapper.ReviewStandardMindMapMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.TaskApplicationMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.service.StandardMindMapService; -import com.guo.learningprogresstracker.utils.CompareResult; +import com.guo.learningprogresstracker.service.ai.MindMapOutlineGenerator; +import com.guo.learningprogresstracker.service.ai.MindMapReportContextLoader; +import com.guo.learningprogresstracker.utils.MindMapMatchTool; import com.guo.learningprogresstracker.utils.MindMapNode; import com.guo.learningprogresstracker.utils.MindMapTreeTool; -import com.guo.learningprogresstracker.utils.ReviewDurationTool; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; 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.*; -import java.util.stream.Collectors; - -/** - * 标准思维导图服务实现 - */ +/** Task standard mind maps remain available to the learning screen. */ @Slf4j @Service @RequiredArgsConstructor public class StandardMindMapServiceImpl implements StandardMindMapService { - private final ReviewStandardMindMapMapper standardMindMapMapper; - private final ReviewRecallRecordMapper recallRecordMapper; private final TasksMapper tasksMapper; private final TaskApplicationMapper taskApplicationMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; - private final MindMapOutlineGenerator outlineGenerator; private final MindMapReportContextLoader reportContextLoader; private final ObjectMapper objectMapper; - private final AiServiceClient aiServiceClient; - private static final String GENERATOR_BUILTIN = "BUILTIN"; private static final String GENERATOR_USER = "USER"; private static final String GENERATOR_USER_MERGE = "USER_MERGE"; - private static final String MATCH_STATUS_MATCHED = "MATCHED"; - private static final String MATCH_STATUS_MISSED = "MISSED"; - - // ============ 查询与生成 ============ @Override public ReviewStandardMindMapEntity getExisting(String taskNum) throws NotFindEntitiesException { @@ -60,42 +52,38 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { } @Override - public ReviewStandardMindMapEntity regenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException { + public ReviewStandardMindMapEntity regenerate(String taskNum) + throws NotFindEntitiesException, OperationFailedException { ensureTaskExists(taskNum); - // 并发生成由 ai_tasks 的进行中任务判定拦截(AI-04),不再依赖 JVM 内存锁 return doGenerate(taskNum); } @Override - public ReviewStandardMindMapEntity incrementalGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException { + public ReviewStandardMindMapEntity incrementalGenerate(String taskNum) + throws NotFindEntitiesException, OperationFailedException { ensureTaskExists(taskNum); ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum); if (existing == null) { - log.warn("任务[{}]标准思维导图尚不存在,无法增量更新", taskNum); throw new NotFindEntitiesException("还没有生成过标准思维导图,请先完整生成一次哦"); } - - // 生成(可能调用 AI)不放在事务里:等待 AI 期间不应占用数据库连接(AI-01) ReviewStandardMindMapEntity fresh = doGenerate(taskNum); - - // 合并新旧树:保留用户编辑过的节点,追加新节点 MindMapNode oldRoot = MindMapTreeTool.fromJson(existing.getContent(), objectMapper); MindMapNode newRoot = MindMapTreeTool.fromJson(fresh.getContent(), objectMapper); - MindMapNode merged = MindMapTreeTool.mergeTrees(oldRoot, newRoot); - + MindMapNode merged = MindMapMatchTool.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()); standardMindMapMapper.updateById(existing); return existing; } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public ReviewStandardMindMapEntity updateByOutline(String taskNum, String outline) throws NotFindEntitiesException { ensureTaskExists(taskNum); ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum); @@ -103,19 +91,14 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { existing = new ReviewStandardMindMapEntity(); existing.setTaskNum(taskNum); } - - // 解析大纲为树节点 MindMapNode root = MindMapTreeTool.parseOutline(outline); - String contentJson = MindMapTreeTool.toJson(root, objectMapper); - existing.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图"); - existing.setContent(contentJson); + 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 (existing.getId() == null) { standardMindMapMapper.insert(existing); } else { @@ -124,355 +107,70 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { return existing; } - // ============ 回忆对比 ============ - @Override - public RecallCompareOutcome recallCompare(String taskNum, String recallOutline, String focusPath, - ReviewTiming timing) - throws NotFindEntitiesException, OperationFailedException { - ensureTaskExists(taskNum); - - // 1. 取标准导图;缺失时按需生成(可能调用 AI,故整个方法不持有事务) - ReviewStandardMindMapEntity standard = queryByTaskNum(taskNum); - if (standard == null) { - standard = doGenerate(taskNum); - } - - // 2. 解析标准树(用户回忆大纲在对比入口里解析,两条复习范围共用同一段逻辑) - MindMapNode standardRoot = MindMapTreeTool.fromJson(standard.getContent(), objectMapper); - - // 2b. 若指定了起点节点路径,提取该子树作为对比基准 - MindMapNode compareRoot = standardRoot; - if (focusPath != null && !focusPath.isBlank()) { - compareRoot = MindMapTreeTool.extractSubtree(standardRoot, focusPath); - if (compareRoot == null) { - log.warn("focusPath 未匹配到节点,使用全量标准导图: path={}", focusPath); - compareRoot = standardRoot; - } - } - - // 3. 执行对比(优先 AI 语义对比,失败时降级为内置算法)——与标签导图共用同一套对比口径 - CompareResult result = compareWithRecall(resolveScopeName(taskNum), compareRoot, recallOutline); - - // 4. 序列化对比结果 - String resultJson; - try { - resultJson = objectMapper.writeValueAsString(result); - } catch (Exception e) { - log.error("任务[{}]对比结果序列化失败", taskNum, e); - throw new OperationFailedException("对比结果解析失败了,请稍后再试"); - } - - // 5. 保存回忆记录 - ReviewRecallRecordEntity record = new ReviewRecallRecordEntity(); - record.setTaskNum(taskNum); - // 任务范围的复习范围列:任务导图;标签范围的行由标签导图服务自己写 - record.setScopeType(ReviewScopeTypeEnum.TASK.name()); - record.setStandardMapId(standard.getId()); - record.setFocusPath(focusPath != null && !focusPath.isBlank() ? focusPath : null); - record.setRecallContent(recallOutline); - record.setCompareResult(resultJson); - record.setRecallRatio(result.getRecallRatio()); - record.setMatchedCount(result.getMatchedCount()); - record.setMissedCount(result.getMissedCount()); - record.setExtraCount(result.getExtraCount()); - record.setReviewDurationSeconds(ReviewDurationTool.resolveSeconds( - timing == null ? null : timing.startedAt(), - timing == null ? null : timing.lastInteractionAt(), - timing == null ? null : timing.durationSeconds(), - LocalDateTime.now())); - recallRecordMapper.insert(record); - - log.info("回忆对比: taskNum={}, recallRatio={}, matched={}, missed={}, extra={}, 复习耗时={}秒", - taskNum, result.getRecallRatio(), result.getMatchedCount(), - result.getMissedCount(), result.getExtraCount(), record.getReviewDurationSeconds()); - - return new RecallCompareOutcome(standard.getId(), record.getId(), result.getRecallRatio(), - result.getMatchedCount(), result.getMissedCount(), result.getExtraCount()); - } - - // ============ 节点查找 ============ - - @Override - public Map findNode(String taskNum, String content) throws NotFindEntitiesException, OperationFailedException { + public Map findNode(String taskNum, String content) throws NotFindEntitiesException { ensureTaskExists(taskNum); ReviewStandardMindMapEntity standard = queryByTaskNum(taskNum); - if (standard == null) { - // 还没有标准导图时无从匹配;由调用方决定是否先发起生成任务 - Map empty = new LinkedHashMap<>(); - empty.put("path", ""); - empty.put("nodeTitle", ""); - empty.put("score", 0.0); - return empty; - } - MindMapNode root = MindMapTreeTool.fromJson(standard.getContent(), objectMapper); - - MindMapNode closest = MindMapTreeTool.findClosestNode(root, content); Map result = new LinkedHashMap<>(); - if (closest != null) { - String path = MindMapTreeTool.getPath(root, closest.getTitle()); - result.put("path", path); - result.put("nodeTitle", closest.getTitle()); - result.put("score", MindMapTreeTool.similarityScore(closest.getTitle(), content)); - } else { + if (standard == null) { result.put("path", ""); result.put("nodeTitle", ""); result.put("score", 0.0); + return result; + } + MindMapNode root = MindMapTreeTool.fromJson(standard.getContent(), objectMapper); + MindMapNode closest = MindMapMatchTool.findClosestNode(root, content); + if (closest == null) { + result.put("path", ""); + result.put("nodeTitle", ""); + result.put("score", 0.0); + } else { + result.put("path", MindMapMatchTool.getPath(root, closest.getTitle())); + result.put("nodeTitle", closest.getTitle()); + result.put("score", MindMapMatchTool.similarityScore(closest.getTitle(), content)); } 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(); - } - - // ============ 对比算法核心 ============ - - /** - * 两颗树的节点级对比算法。 - */ - CompareResult compareTrees(MindMapNode standardRoot, MindMapNode recallRoot) { - CompareResult result = new CompareResult(); - - // 展平标准树 - List standardFlat = MindMapTreeTool.flatten(standardRoot); - // 展平回忆树(排除根节点本身) - List recallFlat = MindMapTreeTool.flatten(recallRoot).stream() - .filter(n -> n != recallRoot) - .collect(Collectors.toList()); - - // 构建回忆节点标题 → 节点映射(标准化后) - Map recallTitleMap = new LinkedHashMap<>(); - for (MindMapNode node : recallFlat) { - recallTitleMap.merge(normalize(node.getTitle()), node, (a, b) -> a); - } - - // 标注标准树 - int matched = 0, missed = 0; - for (MindMapNode node : standardFlat) { - if (node == standardRoot) continue; // 跳过根节点 - String key = normalize(node.getTitle()); - boolean found = recallTitleMap.containsKey(key); - if (found) { - node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : "")); - matched++; - } else { - // 尝试模糊匹配 - found = fuzzyMatch(node.getTitle(), recallTitleMap); - if (found) { - node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : "")); - matched++; - } else { - node.setNotes(MATCH_STATUS_MISSED + "|" + (node.getNotes() != null ? node.getNotes() : "")); - missed++; - } - } - } - - // 找出额外节点(用户在回忆中新增的、标准树中没有的) - Set standardNormTitles = standardFlat.stream() - .map(n -> normalize(n.getTitle())) - .collect(Collectors.toSet()); - - List extraNodes = new ArrayList<>(); - for (MindMapNode node : recallFlat) { - String key = normalize(node.getTitle()); - if (!standardNormTitles.contains(key)) { - CompareResult.FlatNode flat = new CompareResult.FlatNode(); - flat.setTitle(node.getTitle()); - flat.setPath(node.getTitle()); // 简化路径 - extraNodes.add(flat); - } - } - - int total = matched + missed; - result.setMatchedTree(standardRoot); - result.setExtraNodes(extraNodes); - result.setMatchedCount(matched); - result.setMissedCount(missed); - result.setExtraCount(extraNodes.size()); - result.setRecallRatio(total > 0 ? (double) matched / total : 0); - return result; - } - - /** - * 从 AI 返回的平铺匹配列表构建 CompareResult,并将 MATCHED/MISSED 标注回标准树。 - *

AI 只输出哪些节点匹配/遗漏,树结构标注由本方法确定性完成,避免 LLM 输出不可靠的嵌套 JSON。

- */ - private CompareResult buildCompareResultFromAI(JsonNode aiJson, MindMapNode standardRoot) { - CompareResult result = new CompareResult(); - - // 1. 读取 AI 返回的匹配对 → 构建 standardNorm → matchFlag - Set matchedStandardTitles = new HashSet<>(); - JsonNode matchesArr = aiJson.path("matches"); - if (matchesArr.isArray()) { - for (JsonNode m : matchesArr) { - String stdTitle = m.path("standardTitle").asText(null); - if (stdTitle != null) { - matchedStandardTitles.add(normalize(stdTitle)); - } - } - } - - // 2. 读取遗漏列表 - Set missedTitles = new HashSet<>(); - JsonNode missedArr = aiJson.path("missedTitles"); - if (missedArr.isArray()) { - for (JsonNode t : missedArr) { - String title = t.asText(null); - if (title != null) missedTitles.add(normalize(title)); - } - } - - // 3. 标注标准树的每个非根节点 - List standardFlat = MindMapTreeTool.flatten(standardRoot); - int matched = 0, missed = 0; - for (MindMapNode node : standardFlat) { - if (node == standardRoot) continue; - String key = normalize(node.getTitle()); - if (matchedStandardTitles.contains(key)) { - node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : "")); - matched++; - } else { - node.setNotes(MATCH_STATUS_MISSED + "|" + (node.getNotes() != null ? node.getNotes() : "")); - missed++; - } - } - - // 4. 读取 extraNodes(兼容字符串数组和对象数组两种格式) - List extras = new ArrayList<>(); - JsonNode extrasArr = aiJson.path("extraNodes"); - if (extrasArr.isArray()) { - for (JsonNode e : extrasArr) { - CompareResult.FlatNode fn = new CompareResult.FlatNode(); - if (e.isTextual()) { - // 字符串格式 ["知识点D1", "知识点D2"] - fn.setTitle(e.asText("")); - fn.setPath(""); - } else { - // 对象格式 [{ title: "...", path: "..." }] - fn.setTitle(e.path("title").asText("")); - fn.setPath(e.path("path").asText("")); - } - extras.add(fn); - } - } - - // 5. 组装结果 - result.setMatchedTree(standardRoot); - result.setExtraNodes(extras); - result.setMatchedCount(matched); - result.setMissedCount(missed); - result.setExtraCount(extras.size()); - int total = matched + missed; - result.setRecallRatio(total > 0 ? (double) matched / total : 0); - result.setEvaluation(aiJson.path("evaluation").asText(null)); - return result; - } - - // ============ 回忆记录查询 ============ - - @Override - public List listRecallRecords(String taskNum) throws NotFindEntitiesException { - ensureTaskExists(taskNum); - return recallRecordMapper.selectList( - Wrappers.lambdaQuery() - .eq(ReviewRecallRecordEntity::getTaskNum, taskNum) - .orderByDesc(ReviewRecallRecordEntity::getCreatedTime)); - } - - @Override - public ReviewRecallRecordEntity getRecallRecord(Integer recordId) throws NotFindEntitiesException { - return Optional.ofNullable(recallRecordMapper.selectById(recordId)) - .orElseThrow(() -> { - log.warn("回忆记录[{}]不存在", recordId); - return new NotFindEntitiesException("这条回忆记录不存在或已被删除"); - }); - } - - // ============ 内部方法 ============ - private ReviewStandardMindMapEntity doGenerate(String taskNum) throws OperationFailedException { - TaskEntity task = tasksMapper.selectOne( - Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum).last("LIMIT 1")); - + TaskEntity task = tasksMapper.selectOne(Wrappers.lambdaQuery() + .eq(TaskEntity::getTaskNum, taskNum) + .last("LIMIT 1")); if (task == null) { - log.warn("任务[{}]不存在,无法生成思维导图", taskNum); throw new OperationFailedException("这个任务不存在或已被删除"); } - - // 素材按**内容归属**取:该任务名下的知识碎片(归属-01)。 - // 不再按「任务的会话里的报告」取,否则学 A 时记录的旁支知识会错误地进入 A 的导图。 - List fragments = studyReportFragmentsMapper.selectList( - Wrappers.lambdaQuery() + List fragments = + studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); List applications = taskApplicationMapper.selectList( Wrappers.lambdaQuery().eq(TaskApplicationEntity::getTaskNum, taskNum)); - if (fragments.isEmpty()) { - log.warn("任务[{}]没有归属到它的知识碎片,无法生成思维导图", taskNum); throw new OperationFailedException("这个任务还没开始学习哦,学习后产生知识碎片后再来吧"); } - - // 「碎片 → 缩进大纲」生成链路(AI 优先、内置规则降级)与标签导图共用同一套口径; - // 报告-02:把碎片同源会话的报告作为参考上下文带上,让 AI 提取总结里由碎片拼接出的新定义/观点 List reports = reportContextLoader.load(fragments); MindMapOutlineGenerator.GeneratedOutline generated = outlineGenerator.generate(task, fragments, applications, reports); - MindMapNode root = generated.root(); - String contentJson = MindMapTreeTool.toJson(root, objectMapper); String outline = MindMapTreeTool.toFullOutline(root); int nodeCount = MindMapTreeTool.countNodes(root); - int depth = MindMapTreeTool.maxDepth(root); - ReviewStandardMindMapEntity entity = queryByTaskNum(taskNum); boolean create = entity == null; if (create) { entity = new ReviewStandardMindMapEntity(); entity.setTaskNum(taskNum); } - entity.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图"); - entity.setContent(contentJson); + entity.setContent(MindMapTreeTool.toJson(root, objectMapper)); entity.setOutline(outline); - entity.setSummary("共 " + nodeCount + " 个节点,最大层级 " + depth); + entity.setSummary("共 " + nodeCount + " 个节点,最大层级 " + MindMapTreeTool.maxDepth(root)); entity.setGenerator(generated.generatorName()); entity.setGeneratorVersion("1.0"); entity.setSourceReportCount(0); entity.setSourceFragmentCount(fragments.size()); entity.setGeneratedTime(LocalDateTime.now()); - // 重建完成后清除「待更新」标记 entity.setNeedsUpdate(false); entity.setNeedsUpdateTime(null); - if (create) { standardMindMapMapper.insert(entity); } else { @@ -482,63 +180,16 @@ public class StandardMindMapServiceImpl implements StandardMindMapService { } private void ensureTaskExists(String taskNum) throws NotFindEntitiesException { - if (!StringUtils.hasText(taskNum) || !tasksMapper.exists( - Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { + if (!StringUtils.hasText(taskNum) + || !tasksMapper.exists(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { log.warn("任务[{}]不存在", taskNum); throw new NotFindEntitiesException("这个任务不存在或已被删除"); } } private ReviewStandardMindMapEntity queryByTaskNum(String taskNum) { - return standardMindMapMapper.selectOne( - Wrappers.lambdaQuery() - .eq(ReviewStandardMindMapEntity::getTaskNum, taskNum) - .last("LIMIT 1")); - } - - // ============ 标题归一化 ============ - - /** - * 标准化标题用于对比:去空格、去标点、转小写。 - */ - static String normalize(String s) { - if (s == null) return ""; - // 先移除内部对比标记前缀,再清理标点 - String result = s.replaceAll("^(?:MATCHED|MISSED)\\|", ""); - result = result.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", ""); - return result.toLowerCase(Locale.ROOT).trim(); - } - - /** - * 模糊匹配:计算字符 bigram Jaccard 相似度 - */ - static boolean fuzzyMatch(String title, Map recallTitleMap) { - if (title == null || title.isBlank()) return false; - String norm = normalize(title); - Set bigrams = bigramSet(norm); - if (bigrams.isEmpty()) return false; - - for (String recallKey : recallTitleMap.keySet()) { - Set recallBigrams = bigramSet(recallKey); - if (recallBigrams.isEmpty()) continue; - // Jaccard - Set intersection = new HashSet<>(bigrams); - intersection.retainAll(recallBigrams); - Set union = new HashSet<>(bigrams); - union.addAll(recallBigrams); - double similarity = (double) intersection.size() / union.size(); - if (similarity >= 0.6) { - return true; - } - } - return false; - } - - static Set bigramSet(String s) { - Set set = new HashSet<>(); - for (int i = 0; i < s.length() - 1; i++) { - set.add(s.substring(i, i + 2)); - } - return set; + return standardMindMapMapper.selectOne(Wrappers.lambdaQuery() + .eq(ReviewStandardMindMapEntity::getTaskNum, taskNum) + .last("LIMIT 1")); } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/StudyExpectationsServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/StudyExpectationsServiceImpl.java index 52ce8d2..c73ee5c 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/StudyExpectationsServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/StudyExpectationsServiceImpl.java @@ -23,10 +23,10 @@ public class StudyExpectationsServiceImpl implements StudyExpectationsService { private final StudySessionsMapper studySessionsMapper; @Override - public StudyExpectationsEntity upsertExpectation(String sessionNum, String description) throws ErrorParameterException { + public StudyExpectationsEntity upsertExpectation(String sessionNum, String description) + throws ErrorParameterException { boolean sessionExists = studySessionsMapper.exists( - Wrappers.lambdaQuery() - .eq(StudySessionsEntity::getSessionNum, sessionNum)); + Wrappers.lambdaQuery().eq(StudySessionsEntity::getSessionNum, sessionNum)); if (!sessionExists) { log.warn("学习会话[{}]不存在", sessionNum); throw new ErrorParameterException("这次学习会话不存在或已结束"); @@ -47,16 +47,14 @@ public class StudyExpectationsServiceImpl implements StudyExpectationsService { @Override public StudyExpectationsEntity getBySessionNum(String sessionNum) { - return studyExpectationsMapper.selectOne( - Wrappers.lambdaQuery() - .eq(StudyExpectationsEntity::getSessionNum, sessionNum) - .last("LIMIT 1")); + return studyExpectationsMapper.selectOne(Wrappers.lambdaQuery() + .eq(StudyExpectationsEntity::getSessionNum, sessionNum) + .last("LIMIT 1")); } @Override public void deleteBySessionNum(String sessionNum) { studyExpectationsMapper.delete( - Wrappers.lambdaQuery() - .eq(StudyExpectationsEntity::getSessionNum, sessionNum)); + Wrappers.lambdaQuery().eq(StudyExpectationsEntity::getSessionNum, sessionNum)); } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImpl.java index be4247e..6fb8178 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImpl.java @@ -4,34 +4,34 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; import com.guo.learningprogresstracker.dto.request.UpdateFragmentsRequest; -import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import com.guo.learningprogresstracker.entity.MarkerEntity; +import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudySessionsEntity; import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum; import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; -import com.guo.learningprogresstracker.mapStruct.FragmentsConvert; import com.guo.learningprogresstracker.mapper.ReviewStandardMindMapMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.mapstruct.FragmentsConvert; import com.guo.learningprogresstracker.service.MarkerService; import com.guo.learningprogresstracker.service.ReviewTagMindMapService; import com.guo.learningprogresstracker.service.StudyReportFragmentsService; -import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; -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 com.guo.learningprogresstracker.service.recall.RecallPrivacyService; import java.time.LocalDateTime; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; /** * 知识碎片服务(归属-01)。 @@ -44,22 +44,22 @@ import java.util.Set; @Service @RequiredArgsConstructor public class StudyReportFragmentsServiceImpl extends ServiceImpl - implements StudyReportFragmentsService { + implements StudyReportFragmentsService { private final StudySessionsMapper studySessionsMapper; private final TasksMapper tasksMapper; private final ReviewStandardMindMapMapper reviewStandardMindMapMapper; private final MarkerService markerService; + private final RecallPrivacyService recallPrivacyService; private final ReviewTagMindMapService reviewTagMindMapService; @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public void createFragments(CreateFragmentsRequest request) throws NotFindEntitiesException { StudyReportFragmentsEntity entity = FragmentsConvert.MAPPER.toFragmentsEntity(request); - StudySessionsEntity session = studySessionsMapper.selectOne( - Wrappers.lambdaQuery() - .eq(StudySessionsEntity::getSessionNum, entity.getContextNum())); + StudySessionsEntity session = studySessionsMapper.selectOne(Wrappers.lambdaQuery() + .eq(StudySessionsEntity::getSessionNum, entity.getContextNum())); if (session == null) { log.warn("未能找到学习会话sessionNum[{}]", entity.getContextNum()); throw new NotFindEntitiesException("这次学习会话不存在或已结束"); @@ -78,6 +78,7 @@ public class StudyReportFragmentsServiceImpl extends ServiceImpllambdaUpdate() + .eq(StudyReportFragmentsEntity::getId, id) + .set(request.getContent() != null, StudyReportFragmentsEntity::getContent, request.getContent()) + .set(resolvedOwner != null, StudyReportFragmentsEntity::getOwnerTaskNum, resolvedOwner)); // 本次把碎片归入某个任务(含「升格为新任务」的归类)→ 补打任务名标签(闭环-02) - if (resolvedOwner != null) { + if (resolvedOwner != null && !Objects.equals(existing.getOwnerTaskNum(), resolvedOwner)) { markerService.addOwnerTaskNameTag(MarkerObjectTypeEnum.FRAGMENT, String.valueOf(id), resolvedOwner); } } @Override + @Transactional(rollbackFor = Exception.class) public void assignOwnership(Integer id, String ownerTaskNum) throws NotFindEntitiesException { StudyReportFragmentsEntity existing = this.getById(id); if (existing == null) { @@ -113,10 +116,11 @@ public class StudyReportFragmentsServiceImpl extends ServiceImpllambdaUpdate() + .eq(StudyReportFragmentsEntity::getId, id) + .set(StudyReportFragmentsEntity::getOwnerTaskNum, resolved)); // 归属改变后,原任务与新任务的导图都需要重建(由用户手动触发) markMindMapStale(previous); @@ -129,12 +133,14 @@ public class StudyReportFragmentsServiceImpl extends ServiceImpl getFragmentsBySession(String sessionNum) { - return this.list( - Wrappers.lambdaQuery() - .eq(StudyReportFragmentsEntity::getContextType, FragmentContextTypeEnum.SESSION.name()) - .eq(StudyReportFragmentsEntity::getContextNum, sessionNum) - .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); + return this.list(Wrappers.lambdaQuery() + .eq(StudyReportFragmentsEntity::getContextType, FragmentContextTypeEnum.SESSION.name()) + .eq(StudyReportFragmentsEntity::getContextNum, sessionNum) + .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); } @Override public List getPendingOwnershipFragments() { - return this.list( - Wrappers.lambdaQuery() - .and(w -> w.isNull(StudyReportFragmentsEntity::getOwnerTaskNum) - .or().eq(StudyReportFragmentsEntity::getOwnerTaskNum, "")) - .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)); + return this.list(Wrappers.lambdaQuery() + .and(w -> w.isNull(StudyReportFragmentsEntity::getOwnerTaskNum) + .or() + .eq(StudyReportFragmentsEntity::getOwnerTaskNum, "")) + .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)); } @Override public long countPendingOwnershipFragments() { - return this.count( - Wrappers.lambdaQuery() - .and(w -> w.isNull(StudyReportFragmentsEntity::getOwnerTaskNum) - .or().eq(StudyReportFragmentsEntity::getOwnerTaskNum, ""))); + return this.count(Wrappers.lambdaQuery() + .and(w -> w.isNull(StudyReportFragmentsEntity::getOwnerTaskNum) + .or() + .eq(StudyReportFragmentsEntity::getOwnerTaskNum, ""))); } /** @@ -201,7 +206,7 @@ public class StudyReportFragmentsServiceImpl extends ServiceImpl> markers = markerService.listByObjects(MarkerObjectTypeEnum.FRAGMENT, fragmentIds); Set changedTags = new LinkedHashSet<>(); @@ -215,8 +220,7 @@ public class StudyReportFragmentsServiceImpl extends ServiceImpl - implements StudyReportsService{ - -} - - - - + implements StudyReportsService {} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImpl.java index 57f10ea..ce2731d 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImpl.java @@ -15,24 +15,25 @@ import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.enums.StudySessionStateEnum; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; -import com.guo.learningprogresstracker.mapStruct.StudySessionConvert; import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.StudyReportsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapstruct.StudySessionConvert; import com.guo.learningprogresstracker.service.StudyExpectationsService; import com.guo.learningprogresstracker.service.StudyReportFragmentsService; import com.guo.learningprogresstracker.service.StudySessionsService; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; +import com.guo.learningprogresstracker.service.session.StudyReportDraftService; +import com.guo.learningprogresstracker.service.session.StudySessionConvergenceService; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Optional; +import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - /** * 针对表【study_sessions(记录每次学习会话的具体数据)】的数据库操作Service实现 */ @@ -47,9 +48,6 @@ public class StudySessionsServiceImpl extends ServiceImpl { log.warn("[{}]不存在", taskNum); return new NotFindEntitiesException("这个任务不存在或已被删除"); }); + ensureNoConflictingActiveSession(taskNum); + StudySessionsEntity session = this.getOneOpt(Wrappers.lambdaQuery() .eq(StudySessionsEntity::getTaskNum, taskNum) .ne(StudySessionsEntity::getSessionState, StudySessionStateEnum.ENDED.name())) @@ -102,28 +105,33 @@ public class StudySessionsServiceImpl extends ServiceImpl sessionNotFound(sessionNum)); + public void pauseStudySession(String sessionNum, LocalDateTime endTime) + throws ErrorParameterException, ServiceException { + StudySessionsEntity studySessionsEntity = requireSession(sessionNum); if (StudySessionStateEnum.PAUSED.name().equals(studySessionsEntity.getSessionState())) { log.error("会话[" + studySessionsEntity.getSessionNum() + "]重复暂停"); throw new ErrorParameterException("这次学习会话已经暂停了,不用重复暂停哦"); } + if (endTime != null) { + LocalDateTime now = LocalDateTime.now(); + if (endTime.isAfter(now)) { + throw new ErrorParameterException("暂停时间不能晚于当前时间"); + } + if (studySessionsEntity.getLastStartTime() != null + && endTime.isBefore(studySessionsEntity.getLastStartTime())) { + throw new ErrorParameterException("暂停时间不能早于本次学习开始时间"); + } + } studySessionsEntity.calculatePointerPosition(studyTimePolicy); studySessionsEntity.pausedStudySession(endTime, studyTimePolicy); this.updateById(studySessionsEntity); } - @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public String endedStudySession(String sessionNum, ReportSections report) throws ErrorParameterException { - StudySessionsEntity studySessionsEntity = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) - .eq(StudySessionsEntity::getSessionNum, sessionNum)) - .orElseThrow(() -> sessionNotFound(sessionNum)); + StudySessionsEntity studySessionsEntity = requireSession(sessionNum); // 幂等:已结束的会话不再重复结算,也不会重复生成学习报告 if (studySessionsEntity.isEnded()) { @@ -136,9 +144,11 @@ public class StudySessionsServiceImpl extends ServiceImpllambdaUpdate() - .eq(StudySessionsEntity::getId, studySessionsEntity.getId()) - .ne(StudySessionsEntity::getSessionState, StudySessionStateEnum.ENDED.name())); + boolean ended = this.update( + studySessionsEntity, + Wrappers.lambdaUpdate() + .eq(StudySessionsEntity::getId, studySessionsEntity.getId()) + .ne(StudySessionsEntity::getSessionState, StudySessionStateEnum.ENDED.name())); if (!ended) { log.warn("会话[{}]已被其他请求结束,本次不重复生成学习报告", sessionNum); return null; @@ -147,8 +157,8 @@ public class StudySessionsServiceImpl extends ServiceImpl sessionNotFound(sessionNum)); + StudySessionsEntity studySessionsEntity = requireSession(sessionNum); if (StudySessionStateEnum.ENDED.name().equals(studySessionsEntity.getSessionState())) { log.warn("会话[{}]已结束,不能误操作结束", sessionNum); throw new ErrorParameterException("这次学习会话已经结束,不能再误操作结束了"); @@ -175,8 +184,9 @@ public class StudySessionsServiceImpl extends ServiceImpl 0) { log.warn("会话[{}]已产生{}条学习残片,不能误操作结束", sessionNum, fragmentCount); throw new ErrorParameterException("这次学习已经产生了学习残片,不能按误操作结束了哦"); @@ -190,9 +200,9 @@ public class StudySessionsServiceImpl extends ServiceImpl taskNotFound(taskNum)); StudySessionsDto dto = Optional.ofNullable(studyReportsMapper.getNotEndedStudySessionDtoByTaskNum(taskNum)) .orElseThrow(() -> { @@ -204,22 +214,23 @@ public class StudySessionsServiceImpl extends ServiceImpl getAllFragments(String sessionNum) throws ErrorParameterException { - if (this.exists(Wrappers.lambdaQuery(StudySessionsEntity.class) - .eq(StudySessionsEntity::getSessionNum, sessionNum))) { - return studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery(StudyReportFragmentsEntity.class) - .eq(StudyReportFragmentsEntity::getContextNum, sessionNum)) - .stream().map(StudyReportFragmentsEntity::getContent).collect(Collectors.toCollection(ArrayList::new)); - } else { + if (!this.exists( + Wrappers.lambdaQuery(StudySessionsEntity.class).eq(StudySessionsEntity::getSessionNum, sessionNum))) { throw sessionNotFound(sessionNum); } + return studyReportFragmentsMapper + .selectList(Wrappers.lambdaQuery(StudyReportFragmentsEntity.class) + .eq(StudyReportFragmentsEntity::getContextType, "SESSION") + .eq(StudyReportFragmentsEntity::getContextNum, sessionNum)) + .stream() + .map(StudyReportFragmentsEntity::getContent) + .collect(Collectors.toCollection(ArrayList::new)); } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public void continueStudySession(String sessionNum) throws ErrorParameterException, ServiceException { - StudySessionsEntity studySessionsEntity = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) - .eq(StudySessionsEntity::getSessionNum, sessionNum)) - .orElseThrow(() -> sessionNotFound(sessionNum)); + StudySessionsEntity studySessionsEntity = requireSession(sessionNum); if (StudySessionStateEnum.ONGOING.name().equals(studySessionsEntity.getSessionState())) { log.error("会话[" + studySessionsEntity.getSessionNum() + "]重复开始"); throw new ErrorParameterException("这次学习会话已经开始了,不用重复开始哦"); @@ -227,6 +238,7 @@ public class StudySessionsServiceImpl extends ServiceImpl sessionNotFound(sessionNum)); + StudySessionsEntity session = requireSession(sessionNum); return StudySessionConvert.MAPPER.toStudySessionResponse(session); } @@ -250,40 +260,8 @@ public class StudySessionsServiceImpl extends ServiceImpl sessionNotFound(sessionNum)); - - ArrayList fragments = getAllFragments(sessionNum); - if (fragments.isEmpty()) { - return new ReportSections(null, null, null); - } - - String taskName = tasksServiceImpl.getOneOpt( - Wrappers.lambdaQuery(TaskEntity.class).eq(TaskEntity::getTaskNum, session.getTaskNum())) - .map(TaskEntity::getTaskName) - .orElse("学习任务"); - String expectation = Optional.ofNullable(studyExpectationsService.getBySessionNum(sessionNum)) - .map(e -> e.getDescription()) - .orElse(null); - - // AI 可用时由它给出三段草稿;不可用(或失败)时降级为规则拼接: - // 会话摘要 = 碎片条数 + 首条摘要,自由总结留给用户填写,达成判断只在有预期时给一句规则结论。 - return aiServiceClient.aggregateReport(taskName, fragments, expectation) - .orElseGet(() -> ruleBasedReportDraft(fragments, expectation)); - } - - /** - * 规则降级:不依赖 AI 也能给出一份可编辑的草稿。 - *

只做能确定的事——摘要按碎片拼接、达成判断只在存在学习预期时给规则结论, - * 自由总结刻意留空由用户填写(AI 不可用时不应该替他编造卡点与下一步)。

- */ - private ReportSections ruleBasedReportDraft(List fragments, String expectation) { - String summary = String.join("\n", fragments); - String verdict = (expectation == null || expectation.isBlank()) - ? null - : "本次学习记录了 " + fragments.size() + " 条知识碎片,请对照预期自行判断达成情况。"; - return new ReportSections(summary, verdict, null); + StudySessionsEntity session = requireSession(sessionNum); + return studyReportDraftService.buildDraft(session, getAllFragments(sessionNum)); } // ============ 分页查询任务的历史残片/报告 ============ @@ -309,8 +287,10 @@ public class StudySessionsServiceImpl extends ServiceImpl w.like(StudyReportsEntity::getFreeSummary, keyword) - .or().like(StudyReportsEntity::getSessionSummary, keyword) - .or().like(StudyReportsEntity::getExpectationVerdict, keyword)); + .or() + .like(StudyReportsEntity::getSessionSummary, keyword) + .or() + .like(StudyReportsEntity::getExpectationVerdict, keyword)); } Page result = studyReportsMapper.selectPage(pg, wrapper); // 填充每个报告对应会话的预期目标 @@ -334,25 +314,27 @@ public class StudySessionsServiceImpl extends ServiceImpl这是请求级冲突保障;两个并发请求仍可能同时通过检查,数据库未引入任务级锁, + * 因此调用方仍需把本检查视为友好阻断而非跨实例互斥保证。

+ */ + private void ensureNoConflictingActiveSession(String taskNum) throws ErrorParameterException { + if (getActiveSession(taskNum) != null) { + throw new ErrorParameterException("已有其他学习会话未结束,请先处理后再开始新的学习"); + } + } + + /** 按会话编号取会话;不存在或已删除时统一按「不存在或已结束」处理 */ + private StudySessionsEntity requireSession(String sessionNum) throws ErrorParameterException { + return this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) + .eq(StudySessionsEntity::getSessionNum, sessionNum)) + .orElseThrow(() -> sessionNotFound(sessionNum)); + } + private ErrorParameterException sessionNotFound(String sessionNum) { log.warn("会话[{}]不存在", sessionNum); return new ErrorParameterException("这次学习会话不存在或已结束"); @@ -375,54 +376,11 @@ public class StudySessionsServiceImpl extends ServiceImpl staleSessions = this.list(Wrappers.lambdaQuery() - .eq(StudySessionsEntity::getSessionState, StudySessionStateEnum.ONGOING.name()) - .le(StudySessionsEntity::getLastStartTime, cutoff) - .orderByAsc(StudySessionsEntity::getLastStartTime)); - - int converged = 0; - for (StudySessionsEntity session : staleSessions) { - if (convergeOne(session, now)) { - converged++; - } - } - return converged; + return studySessionConvergenceService.convergeStaleSessionsOfCurrentUser(); } @Override public int scanAndConvergeStaleSessions() { - LocalDateTime now = LocalDateTime.now(); - LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes()); - - // 定时任务在请求之外执行,没有登录态,走忽略租户条件的扫描(系统级兜底) - List staleSessions = baseMapper.selectForcePausableSessions(cutoff, SCAN_BATCH_SIZE); - - int converged = 0; - for (StudySessionsEntity session : staleSessions) { - if (convergeOne(session, now)) { - converged++; - } - } - return converged; + return studySessionConvergenceService.scanAndConvergeStaleSessions(); } - - /** - * 收敛单个悬挂会话:先按硬兜底阈值复核,再用「状态仍为 ONGOING」的条件更新写入。 - * - *

条件更新保证惰性收敛与定时扫描并发时只结算一次(与结束会话的幂等处理同一思路), - * 写入按主键定位,所以定时扫描分支可以安全地忽略租户条件。

- * - * @return 是否由本次调用完成收敛 - */ - private boolean convergeOne(StudySessionsEntity session, LocalDateTime now) { - if (!session.forceConverge(now, studyTimePolicy)) { - return false; - } - return baseMapper.convergeStaleSession(session) > 0; - } - } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/TagRecallCompareAiTaskHandler.java b/src/main/java/com/guo/learningprogresstracker/service/impl/TagRecallCompareAiTaskHandler.java deleted file mode 100644 index 5800352..0000000 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/TagRecallCompareAiTaskHandler.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.guo.learningprogresstracker.service.impl; - -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; -import com.guo.learningprogresstracker.dto.ReviewTiming; -import com.guo.learningprogresstracker.dto.TagScope; -import com.guo.learningprogresstracker.entity.AiTaskEntity; -import com.guo.learningprogresstracker.enums.AiTaskTypeEnum; -import com.guo.learningprogresstracker.exception.ErrorParameterException; -import com.guo.learningprogresstracker.exception.OperationFailedException; -import com.guo.learningprogresstracker.service.ReviewTagMindMapService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import java.util.Map; - -/** - * 标签范围回忆对比任务(闭环-04)。 - * - *

任务目标 {@code targetNum} 是标签范围的规范键;范围与回忆内容由参数给出 - * ({@code tags}、{@code combineMode}、{@code recallOutline}、{@code focusPath} 与复习计时字段, - * 后四项与任务范围回忆对比同名同义)。对比落在回忆记录里,范围=标签集合 + 取数模式,任务列为空。

- */ -@Slf4j -@Component -@RequiredArgsConstructor -public class TagRecallCompareAiTaskHandler implements AiTaskHandler { - - private final ReviewTagMindMapService reviewTagMindMapService; - - @Override - public AiTaskTypeEnum type() { - return AiTaskTypeEnum.TAG_RECALL_COMPARE; - } - - @Override - public Map execute(AiTaskEntity task, Map params) { - String recallOutline = AiTaskParams.asString(params, "recallOutline"); - if (!StringUtils.hasText(recallOutline)) { - throw new AiTaskFailedException("请先填写回忆大纲"); - } - - try { - TagScope scope = reviewTagMindMapService.resolveScope( - AiTaskParams.asStringList(params, "tags"), AiTaskParams.asString(params, "combineMode")); - requireScopeMatches(task, scope); - - ReviewTiming timing = new ReviewTiming( - AiTaskParams.asLocalDateTime(params, "reviewStartedAt"), - AiTaskParams.asLocalDateTime(params, "reviewLastInteractionAt"), - AiTaskParams.asInteger(params, "reviewDurationSeconds")); - RecallCompareOutcome outcome = reviewTagMindMapService.recallCompare( - scope, recallOutline, AiTaskParams.asString(params, "focusPath"), timing); - return outcome.toPayload(); - } catch (ErrorParameterException | 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("标签范围和导图标识对不上,请刷新页面后重试"); - } - } -} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/TasksServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/TasksServiceImpl.java index eef331c..5968183 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/TasksServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/TasksServiceImpl.java @@ -16,36 +16,37 @@ import com.guo.learningprogresstracker.entity.TaskEntity; import com.guo.learningprogresstracker.enums.TaskApplicationStatusEnum; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; -import com.guo.learningprogresstracker.mapStruct.RequestConvert; -import com.guo.learningprogresstracker.mapStruct.TaskConvert; import com.guo.learningprogresstracker.mapper.TaskApplicationMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.mapstruct.RequestConvert; +import com.guo.learningprogresstracker.mapstruct.TaskConvert; import com.guo.learningprogresstracker.service.PriorityWeightsService; import com.guo.learningprogresstracker.service.TasksService; -import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.service.recall.RecallPrivacyService; +import com.guo.learningprogresstracker.service.session.TaskDeletionService; import com.guo.learningprogresstracker.utils.CalculatedPriorityTool; import com.guo.learningprogresstracker.utils.GenerateNumTool; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; 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.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - /** * 针对表【tasks(存储学习任务的基本信息,包括优先级的多维度计算)】的数据库操作Service实现 */ @Service @RequiredArgsConstructor @Slf4j -public class TasksServiceImpl extends ServiceImpl - implements TasksService { +public class TasksServiceImpl extends ServiceImpl implements TasksService { private final TasksMapper tasksMapper; private final TaskApplicationMapper taskApplicationMapper; + private final RecallPrivacyService recallPrivacyService; private final TaskDeletionService taskDeletionService; @@ -53,9 +54,9 @@ public class TasksServiceImpl extends ServiceImpl @Override public Page taskList(Integer pageNum, Integer pageSize) { - Page page = tasksMapper.selectPage(new Page(pageNum, pageSize), - Wrappers.lambdaQuery(TaskEntity.class) - .orderByDesc(TaskEntity::getCalculatedPriority)); + Page page = tasksMapper.selectPage( + new Page(pageNum, pageSize), + Wrappers.lambdaQuery(TaskEntity.class).orderByDesc(TaskEntity::getCalculatedPriority)); Page response = TaskConvert.MAPPER.toTaskInfoPage(page); return response; } @@ -63,7 +64,8 @@ public class TasksServiceImpl extends ServiceImpl @Override public List taskOptions() { // 只查两列,不做任何聚合:下拉要的是全部任务,不是一页 - return tasksMapper.selectList(Wrappers.lambdaQuery() + return tasksMapper + .selectList(Wrappers.lambdaQuery() .select(TaskEntity::getTaskNum, TaskEntity::getTaskName) .orderByDesc(TaskEntity::getCalculatedPriority) .orderByDesc(TaskEntity::getId)) @@ -77,15 +79,15 @@ public class TasksServiceImpl extends ServiceImpl public String addTask(TaskRequest taskRequest) throws ErrorParameterException { TaskEntity task = TaskConvert.MAPPER.taskRequestToTaskEntity(taskRequest); - if (this.exists(Wrappers.lambdaQuery(TaskEntity.class) - .eq(TaskEntity::getTaskName, task.getTaskName()))) { + if (this.exists(Wrappers.lambdaQuery(TaskEntity.class).eq(TaskEntity::getTaskName, task.getTaskName()))) { log.warn("任务名[{}]重复", task.getTaskName()); throw new ErrorParameterException("已经有同名任务了,换个任务名称吧"); } task.setTaskNum(GenerateNumTool.generateNum("TASK")); PriorityDto priorityDto = RequestConvert.MAPPER.taskRequestToPriorityDto(taskRequest); - task.setCalculatedPriority(CalculatedPriorityTool.calculatedPriority(priorityDto, priorityWeightsService.getWeights())); + task.setCalculatedPriority( + CalculatedPriorityTool.calculatedPriority(priorityDto, priorityWeightsService.getWeights())); this.save(task); return task.getTaskNum(); } @@ -113,12 +115,13 @@ public class TasksServiceImpl extends ServiceImpl taskEntity.setTaskNum(existingTask.getTaskNum()); // 维度数据可能变化,更新时重算优先级 PriorityDto priorityDto = RequestConvert.MAPPER.taskRequestToPriorityDto(updatedTask); - taskEntity.setCalculatedPriority(CalculatedPriorityTool.calculatedPriority(priorityDto, priorityWeightsService.getWeights())); + taskEntity.setCalculatedPriority( + CalculatedPriorityTool.calculatedPriority(priorityDto, priorityWeightsService.getWeights())); this.updateById(taskEntity); } @Override - @Transactional + @Transactional(rollbackFor = Exception.class) public void deleteTask(String taskId) { TaskEntity existingTask = this.getById(taskId); if (existingTask == null) { @@ -142,15 +145,15 @@ public class TasksServiceImpl extends ServiceImpl @Override public List getApplications(String taskNum) throws NotFindEntitiesException { ensureTaskExists(taskNum); - return taskApplicationMapper.selectList( - Wrappers.lambdaQuery() - .eq(TaskApplicationEntity::getTaskNum, taskNum) - .orderByDesc(TaskApplicationEntity::getLastModifiedTime) - .orderByDesc(TaskApplicationEntity::getCreatedTime)); + return taskApplicationMapper.selectList(Wrappers.lambdaQuery() + .eq(TaskApplicationEntity::getTaskNum, taskNum) + .orderByDesc(TaskApplicationEntity::getLastModifiedTime) + .orderByDesc(TaskApplicationEntity::getCreatedTime)); } @Override - public TaskApplicationEntity createApplication(CreateTaskApplicationRequest request) throws NotFindEntitiesException { + public TaskApplicationEntity createApplication(CreateTaskApplicationRequest request) + throws NotFindEntitiesException { ensureTaskExists(request.getTaskNum()); TaskApplicationEntity entity = new TaskApplicationEntity(); entity.setTaskNum(request.getTaskNum()); @@ -163,7 +166,8 @@ public class TasksServiceImpl extends ServiceImpl } @Override - public TaskApplicationEntity updateApplication(Integer id, UpdateTaskApplicationRequest request) throws NotFindEntitiesException { + public TaskApplicationEntity updateApplication(Integer id, UpdateTaskApplicationRequest request) + throws NotFindEntitiesException { TaskApplicationEntity existing = Optional.ofNullable(taskApplicationMapper.selectById(id)) .orElseThrow(() -> { log.warn("应用场景[{}]不存在", id); @@ -178,18 +182,20 @@ public class TasksServiceImpl extends ServiceImpl } @Override + @org.springframework.transaction.annotation.Transactional public void deleteApplication(Integer id) throws NotFindEntitiesException { TaskApplicationEntity existing = Optional.ofNullable(taskApplicationMapper.selectById(id)) .orElseThrow(() -> { log.warn("应用场景[{}]不存在", id); return new NotFindEntitiesException("这个应用场景不存在或已被删除"); }); + recallPrivacyService.sourceDeleted("APPLICATION", existing.getId().toString()); taskApplicationMapper.deleteById(existing.getId()); } private void ensureTaskExists(String taskNum) throws NotFindEntitiesException { - if (!StringUtils.hasText(taskNum) || !tasksMapper.exists( - Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { + if (!StringUtils.hasText(taskNum) + || !tasksMapper.exists(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { log.warn("任务[{}]不存在", taskNum); throw new NotFindEntitiesException("这个任务不存在或已被删除"); } diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java index b46305f..c4956c8 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java +++ b/src/main/java/com/guo/learningprogresstracker/service/impl/UserServiceImpl.java @@ -4,32 +4,30 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.guo.learningprogresstracker.entity.UserEntity; import com.guo.learningprogresstracker.exception.AppException; -import com.guo.learningprogresstracker.service.UserService; import com.guo.learningprogresstracker.mapper.UserMapper; -import lombok.RequiredArgsConstructor; -import org.mindrot.jbcrypt.BCrypt; -import org.springframework.stereotype.Service; - +import com.guo.learningprogresstracker.service.UserService; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.mindrot.jbcrypt.BCrypt; +import org.springframework.stereotype.Service; /** -* @author guo -* @description 针对表【user(用户信息表)】的数据库操作Service实现 -* @createDate 2024-06-09 15:28:48 -*/ + * @author guo + * @description 针对表【user(用户信息表)】的数据库操作Service实现 + * @createDate 2024-06-09 15:28:48 + */ @Service @RequiredArgsConstructor -public class UserServiceImpl extends ServiceImpl - implements UserService{ +public class UserServiceImpl extends ServiceImpl implements UserService { @Override public String authenticate(String username, String password) throws AppException { - UserEntity userEntity = this.getOneOpt(Wrappers.lambdaQuery() - .eq(UserEntity::getUserName, username)) + UserEntity userEntity = this.getOneOpt( + Wrappers.lambdaQuery().eq(UserEntity::getUserName, username)) .orElseThrow(() -> new AppException("账号或密码错误!")); if (!BCrypt.checkpw(password, userEntity.getUserPassword())) { @@ -55,10 +53,10 @@ public class UserServiceImpl extends ServiceImpl } // 只取 id 与 user_name 两列,避免把密码哈希这类字段拉出来 return list(Wrappers.lambdaQuery() - .select(UserEntity::getId, UserEntity::getUserName) - .in(UserEntity::getId, ids)) + .select(UserEntity::getId, UserEntity::getUserName) + .in(UserEntity::getId, ids)) .stream() - .collect(Collectors.toMap(UserEntity::getId, UserEntity::getUserName, - (first, second) -> first, LinkedHashMap::new)); + .collect(Collectors.toMap( + UserEntity::getId, UserEntity::getUserName, (first, second) -> first, LinkedHashMap::new)); } } diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/RecallExpressionValidator.java b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallExpressionValidator.java new file mode 100644 index 0000000..58af53c --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallExpressionValidator.java @@ -0,0 +1,170 @@ +package com.guo.learningprogresstracker.service.recall; + +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Expression; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ExpressionNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Provenance; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDocument; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Timing; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +/** + * 回忆导图(表达式)的结构校验:节点形状、样式、文本长度,以及出处的可追溯性。 + * + *

出处只认用户自己已经收到的提示与查漏结果,客户端不能凭空构造引用。 + * 计时同理:客户端报上来的分段耗时与交互时间戳都要先自洽,才写回文档。

+ */ +@Component +@RequiredArgsConstructor +public class RecallExpressionValidator { + + private static final int MAX_DEPTH = 32; + private static final int MAX_NODES = 1000; + private static final int MAX_TEXT_LENGTH = 32000; + /** 前端 JS 能精确表示的最大整数,超出即视为客户端计时失真。 */ + private static final long MAX_SAFE_INTEGER_MS = 9007199254740991L; + + private final ReviewRecallStore store; + + public void validate(RecallDocument doc, Expression expression) { + if (expression == null || expression.schemaVersion() != 1 || expression.root() == null) { + invalid(); + } + Set ids = new HashSet<>(); + int[] counts = {0, 0}; + Map> accepted = new HashMap<>(); + collectAcceptedProvenance(doc.getDetail().getExpression().root(), accepted); + validateNode(doc, expression.root(), 1, ids, counts, accepted); + } + + private static void collectAcceptedProvenance(ExpressionNode node, Map> accepted) { + accepted.computeIfAbsent(node.id(), key -> new HashSet<>()).addAll(node.provenance()); + for (ExpressionNode child : node.children()) { + collectAcceptedProvenance(child, accepted); + } + } + + /** Presentation only: two fixed hex colors; arbitrary CSS is never accepted from clients. */ + private static boolean hex(String value) { + return value != null && value.matches("#[0-9a-fA-F]{6}"); + } + + /** 主干只做分发:形状 → 出处 → 子节点。 */ + private void validateNode( + RecallDocument doc, + ExpressionNode n, + int depth, + Set ids, + int[] counts, + Map> accepted) { + checkNodeShape(n, depth, ids, counts); + for (Provenance p : n.provenance()) { + checkNodeProvenance(doc, n, p, accepted); + } + for (ExpressionNode child : n.children()) { + validateNode(doc, child, depth + 1, ids, counts, accepted); + } + } + + /** 节点自身的形状与体量:层级、数量、标识唯一、必填字段、样式取值、文本总长。 */ + private static void checkNodeShape(ExpressionNode n, int depth, Set ids, int[] counts) { + if (n == null || depth > MAX_DEPTH || ++counts[0] > MAX_NODES) { + invalid(); + } + ReviewRecallStore.identifier(n.id()); + if (!ids.add(n.id()) + || n.title() == null + || n.notes() == null + || n.provenance() == null + || n.children() == null) { + invalid(); + } + if (n.style() != null && (!hex(n.style().background()) || !hex(n.style().color()))) { + invalid(); + } + counts[1] += n.title().length() + n.notes().length(); + if (counts[1] > MAX_TEXT_LENGTH) { + invalid(); + } + } + + /** 单条出处:已写过的不再复核,其余必须指向本次回忆中已成功的请求结果。 */ + private void checkNodeProvenance( + RecallDocument doc, ExpressionNode n, Provenance p, Map> accepted) { + if (p == null) { + invalid(); + } + if (accepted.getOrDefault(n.id(), Set.of()).contains(p)) { + return; + } + if (!Set.of("HINT", "FEEDBACK").contains(p.kind() == null ? "" : p.kind()) + || !doc.getDetail().getRecallNum().equals(p.recallNum())) { + invalid(); + } + RecallRequest request = requestResult(doc, p.requestTaskNum()); + boolean matched = "HINT".equals(p.kind()) + ? request.result().hints().stream().anyMatch(i -> i.id().equals(p.itemId())) + : request.result().findings().stream().anyMatch(i -> i.id().equals(p.itemId())); + if (!matched) { + invalid(); + } + } + + private RecallRequest requestResult(RecallDocument doc, String taskNum) { + return store.detail(doc).getRequests().stream() + .filter(r -> r.taskNum().equals(taskNum) && "SUCCEEDED".equals(r.status()) && r.result() != null) + .findFirst() + .orElseThrow(() -> new RecallBusinessException("REFERENCE_UNAVAILABLE", "这份 AI 回应尚不可展示,请等待完成或重新请求")); + } + + /** 校验失败统一走同一个机器码与提示语,客户端据此保留本地输入。 */ + public static void invalid() { + throw invalidException(); + } + + static RecallBusinessException invalidException() { + return new RecallBusinessException("INVALID_INPUT", "这次输入或引用未能核验,请保留内容并重新打开"); + } + + /** 本段时间戳与耗时的自洽校验,返回本段实际耗时(毫秒)。 */ + public static long validateSegmentTiming(Timing timing, long acceptedActiveMs, long acceptedActualMs) { + if (timing == null + || timing.segmentActiveMs() < acceptedActiveMs + || timing.segmentActiveMs() < 0 + || timing.segmentActiveMs() > MAX_SAFE_INTEGER_MS) { + invalid(); + } + Long reportedActualMs = timing.segmentActualMs(); + long segmentActualMs = + reportedActualMs == null ? Math.max(timing.segmentActiveMs(), acceptedActualMs) : reportedActualMs; + if (segmentActualMs < timing.segmentActiveMs() + || segmentActualMs < acceptedActualMs + || segmentActualMs > MAX_SAFE_INTEGER_MS) { + invalid(); + } + return segmentActualMs; + } + + /** 客户端计时不能超过服务端实际流逝时间,也不能把交互时间戳挪到编辑段之外。 */ + public static void validateElapsed(RecallDocument doc, Timing timing, long segmentActualMs) { + long elapsed = Math.max( + 0, + Duration.between(doc.getEpochStartedAt(), Instant.now()).toMillis()) + + 5000; + boolean interactionOutOfRange = timing.lastInteractionAt() != null + && (timing.lastInteractionAt().isAfter(Instant.now().plusSeconds(30)) + || timing.lastInteractionAt() + .isBefore(doc.getEpochStartedAt().minusSeconds(30))); + if (timing.segmentActiveMs() > elapsed || segmentActualMs > elapsed || interactionOutOfRange) { + throw new RecallBusinessException("INVALID_INPUT", "活动计时不一致,请保留输入并恢复新的编辑段"); + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/RecallPrivacyService.java b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallPrivacyService.java new file mode 100644 index 0000000..d905bc0 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallPrivacyService.java @@ -0,0 +1,134 @@ +package com.guo.learningprogresstracker.service.recall; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDocument; +import com.guo.learningprogresstracker.entity.ReviewRecallEntity; +import com.guo.learningprogresstracker.entity.StudyReportsEntity; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.entity.TaskApplicationEntity; +import com.guo.learningprogresstracker.mapper.StudyReportsMapper; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapper.TaskApplicationMapper; +import com.guo.learningprogresstracker.service.ai.RecallJson; +import com.guo.learningprogresstracker.utils.TagScopeTool; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Current reference content is redacted in place; completed AI inputs/results are purged. */ +@Slf4j +@Service +@RequiredArgsConstructor +public class RecallPrivacyService { + private final ReviewRecallStore store; + private final RecallJson json; + private final RecallReferenceLoader loader; + private final StudyReportsMapper reports; + private final StudySessionsMapper sessions; + private final TaskApplicationMapper applications; + + public void begin() { + store.lock(); + } + /** Unreadable old documents are deleted, not hidden; a privacy sweep cannot redact unknown content. */ + private RecallDocument readable(ReviewRecallEntity row) { + try { + return json.readStored(row.getDocumentJson(), RecallDocument.class); + } catch (IllegalStateException | NullPointerException | ClassCastException e) { + // 只处理文档形状不可读;数据库异常继续上抛,隐私清理不能顺带删掉别的记录。 + log.warn("[回忆] 隐私清理删除旧版本或不兼容文档: recallNum={}", row.getRecallNum()); + store.deleteUnreadable(row); + return null; + } + } + + @Transactional(rollbackFor = Exception.class) + public void sourceDeleted(String type, String id) { + store.lock(); + String sourceId = type.toLowerCase(Locale.ROOT) + ":" + id; + for (ReviewRecallEntity row : store.all()) { + RecallDocument doc = readable(row); + if (doc == null) { + continue; + } + boolean found = doc.getReference().sources().stream() + .anyMatch(s -> sourceId.equals(s.sourceId()) && "AVAILABLE".equals(s.status())); + if (!found) { + continue; + } + doc.setReference(store.redactReference(doc.getReference(), Set.of(sourceId), "DELETED")); + store.redactRequests(doc); + store.persist(doc); + } + } + + @Transactional(rollbackFor = Exception.class) + public void taskDeleted(String taskNum) { + store.lock(); + for (ReviewRecallEntity row : store.all()) { + if ("TASK".equals(row.getScopeType()) && taskNum.equals(row.getTaskNum())) { + RecallDocument doc = readable(row); + if (doc != null) { + store.delete(doc); + } + } + } + List nums = sessions + .selectList(Wrappers.lambdaQuery().eq(StudySessionsEntity::getTaskNum, taskNum)) + .stream() + .map(StudySessionsEntity::getSessionNum) + .toList(); + if (!nums.isEmpty()) { + for (StudyReportsEntity report : reports.selectList( + Wrappers.lambdaQuery().in(StudyReportsEntity::getSessionNum, nums))) { + sourceDeleted("REPORT", report.getId().toString()); + } + } + for (TaskApplicationEntity app : applications.selectList( + Wrappers.lambdaQuery().eq(TaskApplicationEntity::getTaskNum, taskNum))) { + sourceDeleted("APPLICATION", app.getId().toString()); + } + } + + @Transactional(rollbackFor = Exception.class) + public void tagRenamed(String oldName) { + store.lock(); + String normalized = TagScopeTool.normalize(oldName); + for (ReviewRecallEntity row : store.all()) { + RecallDocument doc = readable(row); + if (doc == null) { + continue; + } + RecallDetail detail = doc.getDetail(); + if ("TAG".equals(detail.getScope().type()) + && detail.getScope().normalizedTags().contains(normalized) + && "VALID".equals(detail.getScopeStatus())) { + detail.setScopeStatus("INVALID"); + store.persist(doc); + } + } + } + + @Transactional(rollbackFor = Exception.class) + public void tagsChanged() { + store.lock(); + for (ReviewRecallEntity row : store.all()) { + RecallDocument doc = readable(row); + if (doc == null) { + continue; + } + RecallDetail detail = doc.getDetail(); + if ("TAG".equals(detail.getScope().type()) + && "VALID".equals(detail.getScopeStatus()) + && !loader.valid(detail.getScope())) { + detail.setScopeStatus("INVALID"); + store.persist(doc); + } + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/RecallReferenceLoader.java b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallReferenceLoader.java new file mode 100644 index 0000000..c704917 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/RecallReferenceLoader.java @@ -0,0 +1,296 @@ +package com.guo.learningprogresstracker.service.recall; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSource; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceUnit; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeInput; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeSnapshot; +import com.guo.learningprogresstracker.entity.BaseEntity; +import com.guo.learningprogresstracker.entity.MarkerEntity; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.StudyReportsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.enums.TagCombineModeEnum; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import com.guo.learningprogresstracker.mapper.MarkerMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.StudyReportsMapper; +import com.guo.learningprogresstracker.mapper.TaskApplicationMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.utils.TagScopeTool; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class RecallReferenceLoader { + private final TasksMapper tasks; + private final StudyReportFragmentsMapper fragments; + private final StudyReportsMapper reports; + private final TaskApplicationMapper applications; + private final MarkerMapper markers; + + public ScopeSnapshot scope(ScopeInput input) { + if (input == null || input.tags() == null) { + invalid(); + } + Instant now = Instant.now(); + if ("TASK".equals(input.type())) { + if (input.taskNum() == null + || input.taskNum().isBlank() + || !input.tags().isEmpty() + || input.combineMode() != null) { + invalid(); + } + TaskEntity task = + tasks.selectOne(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, input.taskNum())); + if (task == null) { + throw new RecallBusinessException("SCOPE_INVALID", "这个任务已不可用,请重新选择范围"); + } + return new ScopeSnapshot( + "TASK", input.taskNum(), List.of(), List.of(), null, input.taskNum(), task.getTaskName(), now); + } + if (!"TAG".equals(input.type()) || input.taskNum() != null) { + invalid(); + } + String scopeKey = tagScopeKey(input.tags(), input.combineMode()); + List tags = TagScopeTool.canonicalTags(input.tags()); + List normalized = TagScopeTool.normalizedTags(tags); + ScopeSnapshot scope = new ScopeSnapshot( + "TAG", null, tags, normalized, input.combineMode(), scopeKey, String.join(" / ", tags), now); + if (!valid(scope)) { + throw new RecallBusinessException("SCOPE_INVALID", "这些标签已没有可用碎片,请重新选择范围"); + } + return scope; + } + + /** Same input validation and normalization for creation and historical filtering; no current-source lookup. */ + public static String tagScopeKey(List tags, String combineMode) { + if (tags == null + || tags.isEmpty() + || tags.size() > 10 + || !Set.of("UNION", "INTERSECT").contains(combineMode == null ? "" : combineMode)) { + invalid(); + } + for (String tag : tags) { + if (tag == null + || tag.trim().isEmpty() + || tag.trim().length() > 255 + || tag.chars().anyMatch(Character::isISOControl)) { + invalid(); + } + } + return TagScopeTool.scopeKey(tags, TagCombineModeEnum.valueOf(combineMode)); + } + + public boolean valid(ScopeSnapshot scope) { + if ("TASK".equals(scope.type())) { + return tasks.exists(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, scope.taskNum())); + } + Set actual = new HashSet<>(); + Set accessible = new HashSet<>(); + for (StudyReportFragmentsEntity f : fragments.selectList( + Wrappers.lambdaQuery().select(StudyReportFragmentsEntity::getId))) { + accessible.add(f.getId().toString()); + } + for (MarkerEntity marker : actualMarkers()) { + if (accessible.contains(marker.getObjectNum())) { + actual.add(TagScopeTool.normalize(marker.getMarkerName())); + } + } + return actual.containsAll(scope.normalizedTags()); + } + + private List actualMarkers() { + return markers.selectList(Wrappers.lambdaQuery() + .eq(MarkerEntity::getObjectType, "FRAGMENT") + .eq(MarkerEntity::getKind, "USER")); + } + + public List selectedFragments(ScopeSnapshot scope) { + if ("TASK".equals(scope.type())) { + return fragments.selectList(Wrappers.lambdaQuery() + .eq(StudyReportFragmentsEntity::getOwnerTaskNum, scope.taskNum()) + .orderByAsc(StudyReportFragmentsEntity::getId)); + } + Map> matches = new HashMap<>(); + for (MarkerEntity marker : actualMarkers()) { + String key = TagScopeTool.normalize(marker.getMarkerName()); + if (scope.normalizedTags().contains(key)) { + matches.computeIfAbsent(marker.getObjectNum(), k -> new HashSet<>()) + .add(key); + } + } + List ids = matches.entrySet().stream() + .filter(e -> "UNION".equals(scope.combineMode()) + || e.getValue().size() == scope.normalizedTags().size()) + .map(e -> parseId(e.getKey())) + .filter(Objects::nonNull) + .toList(); + return ids.isEmpty() + ? List.of() + : fragments.selectList(Wrappers.lambdaQuery() + .in(StudyReportFragmentsEntity::getId, ids) + .orderByAsc(StudyReportFragmentsEntity::getId)); + } + + public ReferenceSnapshot snapshot(ScopeSnapshot scope) { + List sources = new ArrayList<>(); + for (StudyReportFragmentsEntity f : selectedFragments(scope)) { + sources.add(source( + "FRAGMENT", + f.getId().toString(), + "知识碎片", + text(f.getContent()), + f, + new SourceContext("PRIMARY", f.getContextType(), f.getContextNum(), List.of()))); + } + List units = new ArrayList<>(); + for (ReferenceSource s : sources) { + units.addAll(units(s)); + } + return new ReferenceSnapshot( + units.isEmpty() ? "EMPTY" : "AVAILABLE", sources, units, List.of("资料可能有遗漏或相互冲突,不作为标准答案。")); + } + + /** 复习参考资料只取知识碎片;旧文档里冻结的学习报告与应用场景来源不计入摘要与分页。 */ + public static List knowledgeSources(List sources) { + if (sources == null) { + return List.of(); + } + return sources.stream().filter(s -> "FRAGMENT".equals(s.type())).toList(); + } + + public static String reportContent(StudyReportsEntity r) { + return "会话摘要\n" + text(r.getSessionSummary()) + "\n预期达成判断\n" + text(r.getExpectationVerdict()) + "\n自由总结\n" + + text(r.getFreeSummary()); + } + + private static String text(String value) { + return value == null ? "" : value; + } + + /** 来源在本次回忆里的位置:角色、上下文、以及相关的其他来源。 */ + public record SourceContext(String role, String contextType, String contextNum, List related) {} + + public static ReferenceSource source( + String type, String id, String title, String content, BaseEntity entity, SourceContext context) { + return new ReferenceSource( + type.toLowerCase(Locale.ROOT) + ":" + id, + type, + id, + title, + content, + context.role(), + context.contextType(), + context.contextNum(), + context.related(), + "AVAILABLE"); + } + /** Java offsets are UTF16; paragraph windows never split a surrogate pair. */ + public static List units(ReferenceSource s) { + List units = new ArrayList<>(); + String text = s.content(); + int start = 0; + while (start < text.length()) { + int newline = text.indexOf('\n', start); + int paragraphEnd = newline < 0 ? text.length() : newline + 1; + while (start < paragraphEnd) { + int end = Math.min(start + 1000, paragraphEnd); + if (end < text.length() + && Character.isHighSurrogate(text.charAt(end - 1)) + && Character.isLowSurrogate(text.charAt(end))) { + end--; + } + String part = text.substring(start, end); + if (!part.isBlank()) { + units.add(new ReferenceUnit( + s.sourceId() + ":" + start, s.sourceId(), start, end, part, s.role(), "AVAILABLE")); + } + start = end; + } + } + return units; + } + + public boolean accessible(ReferenceSource source) { + return accessible(source.type(), source.entityId()); + } + + public boolean accessible(String type, String entityId) { + Integer id = parseId(entityId); + if (id == null) { + return false; + } + return switch (type) { + case "FRAGMENT" -> fragments.selectById(id) != null; + case "REPORT" -> reports.selectById(id) != null; + case "APPLICATION" -> applications.selectById(id) != null; + default -> false; + }; + } + + public ReferenceSource entry(String type, String id) { + Integer key = parseId(id); + if (key == null) { + throw new RecallBusinessException("NOT_FOUND", "这份内容已不可用,请重新打开入口"); + } + if ("FRAGMENT".equals(type)) { + StudyReportFragmentsEntity f = fragments.selectById(key); + if (f != null) { + return source( + type, + id, + "知识碎片", + text(f.getContent()), + f, + new SourceContext("CONTEXT", f.getContextType(), f.getContextNum(), List.of())); + } + } + if ("REPORT".equals(type)) { + StudyReportsEntity r = reports.selectById(key); + if (r != null) { + return source( + type, + id, + "学习报告", + reportContent(r), + r, + new SourceContext("CONTEXT", "SESSION", r.getSessionNum(), List.of())); + } + } + throw new RecallBusinessException("NOT_FOUND", "这份内容已不可用,请重新打开入口"); + } + + public void touch(ReferenceSource s) { + if ("FRAGMENT".equals(s.type())) { + fragments.update( + null, + Wrappers.lambdaUpdate() + .eq(StudyReportFragmentsEntity::getId, parseId(s.entityId())) + .set(StudyReportFragmentsEntity::getLastReviewedTime, java.time.LocalDateTime.now())); + } + } + + private static Integer parseId(String text) { + try { + return Integer.valueOf(text); + } catch (RuntimeException e) { + return null; + } + } + + private static void invalid() { + throw new RecallBusinessException("INVALID_INPUT", "请检查所选任务或标签范围"); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java new file mode 100644 index 0000000..0fc3b1f --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallService.java @@ -0,0 +1,374 @@ +package com.guo.learningprogresstracker.service.recall; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.CreateRecallRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.EndRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Entry; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Expression; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ExpressionNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDocument; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallPage; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallSummary; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceContent; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferencePage; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSource; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSourceSummary; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSummary; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ResumeRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.SaveDraftRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ScopeSnapshot; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.Timing; +import com.guo.learningprogresstracker.entity.ReviewRecallEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallReceiptEntity; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import com.guo.learningprogresstracker.mapper.ReviewRecallMapper; +import com.guo.learningprogresstracker.mapstruct.RecallConvert; +import com.guo.learningprogresstracker.service.ai.RecallJson; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ReviewRecallService { + private final ReviewRecallStore store; + private final RecallReferenceLoader loader; + private final ReviewRecallMapper recalls; + private final RecallConvert convert; + private final RecallJson json; + private final RecallExpressionValidator validator; + + @Transactional(rollbackFor = Exception.class) + public RecallDetail create(CreateRecallRequest r) { + store.lock(); + ReviewRecallStore.identifier(r.editorId()); + ReviewRecallReceiptEntity receipt = store.replay("", "CREATE", r.clientRequestId(), r); + if (receipt != null) { + return store.detail(store.load(receipt.getRecallNum())); + } + if (r.scope() == null || !"TAG".equals(r.scope().type())) { + throw new RecallBusinessException("INVALID_INPUT", "新复习请选择碎片上的标签范围"); + } + ScopeSnapshot scope = loader.scope(r.scope()); + Expression expression = previousExpression(scope); + ReferenceSnapshot reference = loader.snapshot(scope); + RecallDetail d = new RecallDetail(); + Instant now = Instant.now(); + d.setRecallNum("RECALL-" + UUID.randomUUID()); + d.setStatus("ACTIVE"); + d.setScope(scope); + d.setScopeStatus("VALID"); + d.setActiveDurationMs(0); + d.setActualDurationMs(0L); + d.setCreatedAt(now); + d.setUpdatedAt(now); + d.setEditorId(r.editorId()); + d.setWriteToken(UUID.randomUUID().toString()); + d.setExpression(expression); + d.setReference(referenceSummary(reference)); + d.setRequests(new ArrayList<>()); + if (r.entry() != null) { + entry(r.entry()); + } + RecallDocument doc = new RecallDocument(); + doc.setDetail(d); + doc.setReference(reference); + doc.setEpochStartedAt(now); + doc.setAcceptedSegmentMs(0); + doc.setAcceptedSegmentActualMs(0L); + store.insert(doc); + store.receipt(d.getRecallNum(), "CREATE", r.clientRequestId(), r, null); + return store.detail(doc); + } + + private Expression previousExpression(ScopeSnapshot scope) { + ReviewRecallEntity previous = recalls.selectOne(Wrappers.lambdaQuery() + .eq(ReviewRecallEntity::getScopeType, "TAG") + .eq(ReviewRecallEntity::getScopeKey, scope.scopeKey()) + .eq(ReviewRecallEntity::getStatus, "ENDED") + .orderByDesc(ReviewRecallEntity::getLastModifiedTime) + .orderByDesc(ReviewRecallEntity::getId) + .last("LIMIT 1")); + if (previous == null || previous.getDocumentJson() == null) { + return emptyExpression(); + } + try { + return new Expression( + 1, + carryContent(store.load(previous.getRecallNum()) + .getDetail() + .getExpression() + .root())); + } catch (RecallBusinessException e) { + if (!"STORED_DATA_INVALID".equals(e.getData().reason())) { + throw e; + } + return emptyExpression(); + } + } + /** Carried maps contain personal text, without an ever-growing chain of prior help identifiers. */ + private static ExpressionNode carryContent(ExpressionNode node) { + return new ExpressionNode( + node.id(), + node.title(), + node.notes(), + List.of(), + node.style(), + node.children().stream().map(ReviewRecallService::carryContent).toList()); + } + + private static Expression emptyExpression() { + return new Expression(1, new ExpressionNode("root", "", "", List.of(), null, List.of())); + } + + private void entry(Entry entry) { + if (!Set.of("DIRECT", "FEED", "FRAGMENT", "REPORT", "LEGACY") + .contains(entry.type() == null ? "" : entry.type())) { + RecallExpressionValidator.invalid(); + } + if ("DIRECT".equals(entry.type()) || "LEGACY".equals(entry.type())) { + if (entry.sourceType() != null || entry.entityId() != null) { + RecallExpressionValidator.invalid(); + } + return; + } + ReferenceSource source = loader.entry(entry.sourceType(), entry.entityId()); + if (("FRAGMENT".equals(entry.type()) || "FEED".equals(entry.type())) && !"FRAGMENT".equals(source.type())) { + RecallExpressionValidator.invalid(); + } + if ("REPORT".equals(entry.type()) && !"REPORT".equals(source.type())) { + RecallExpressionValidator.invalid(); + } + loader.touch(source); + } + + private static ReferenceSummary referenceSummary(ReferenceSnapshot reference) { + return new ReferenceSummary( + reference.status(), + RecallReferenceLoader.knowledgeSources(reference.sources()).size(), + reference.limitations()); + } + + @Transactional(rollbackFor = Exception.class) + public RecallDetail get(String num) { + store.lock(); + return store.detail(store.load(num)); + } + + @Transactional(rollbackFor = Exception.class) + public RecallPage list( + int pageNum, + int pageSize, + String status, + String scopeType, + String taskNum, + List tags, + String combineMode) { + List tagFilter = tags == null || tags.isEmpty() ? null : tags; + validateListQuery(pageNum, pageSize, status, scopeType, taskNum); + validateTagQuery(scopeType, tagFilter, combineMode); + String scopeKey = tagFilter == null ? null : RecallReferenceLoader.tagScopeKey(tagFilter, combineMode); + store.lock(); + var query = Wrappers.lambdaQuery() + .eq(status != null, ReviewRecallEntity::getStatus, status) + .eq(scopeType != null, ReviewRecallEntity::getScopeType, scopeType) + .eq(taskNum != null, ReviewRecallEntity::getTaskNum, taskNum) + .eq(scopeKey != null, ReviewRecallEntity::getScopeKey, scopeKey); + long count = recalls.selectCount(query); + List rows = new ArrayList<>(); + long removed = 0; + Page page = recalls.selectPage( + new Page<>(pageNum, pageSize), + query.orderByDesc(ReviewRecallEntity::getLastModifiedTime).orderByDesc(ReviewRecallEntity::getId)); + for (ReviewRecallEntity row : page.getRecords()) { + try { + rows.add(convert.toSummary(store.detail(store.load(row.getRecallNum())))); + } catch (RecallBusinessException e) { + if (!"STORED_DATA_INVALID".equals(e.getData().reason())) { + throw e; + } + removed++; + log.warn("[回忆] 列表已删除旧版本或不兼容文档: recallNum={}", row.getRecallNum()); + } + } + return new RecallPage(pageNum, pageSize, Math.max(0, count - removed), rows); + } + + private static void validateListQuery(int pageNum, int pageSize, String status, String scopeType, String taskNum) { + if (pageNum < 1 + || pageSize < 1 + || pageSize > 100 + || (status != null && !Set.of("ACTIVE", "ENDED").contains(status)) + || (scopeType != null && !Set.of("TASK", "TAG").contains(scopeType)) + || (taskNum != null && !"TASK".equals(scopeType))) { + RecallExpressionValidator.invalid(); + } + } + + private static void validateTagQuery(String scopeType, List tags, String combineMode) { + if ((tags != null || combineMode != null) && !"TAG".equals(scopeType)) { + RecallExpressionValidator.invalid(); + } + if ((tags == null) != (combineMode == null)) { + RecallExpressionValidator.invalid(); + } + } + + @Transactional(rollbackFor = Exception.class) + public RecallDetail resume(String num, ResumeRequest r) { + store.lock(); + RecallDocument doc = store.load(num); + RecallDetail d = doc.getDetail(); + if (store.replay(num, "RESUME", r.clientRequestId(), r) != null) { + return store.detail(doc); + } + ReviewRecallStore.identifier(r.editorId()); + if (!"ACTIVE".equals(d.getStatus())) { + RecallExpressionValidator.invalid(); + } + if (!Objects.equals(d.getWriteToken(), r.writeToken())) { + ReviewRecallStore.conflict("REVISION_CONFLICT", "草稿已有更新,请保留本地输入并重新打开"); + } + d.setEditorId(r.editorId()); + doc.setEpochStartedAt(Instant.now()); + doc.setAcceptedSegmentMs(0); + doc.setAcceptedSegmentActualMs(0L); + store.rotateWriteToken(d); + store.persist(doc); + store.receipt(num, "RESUME", r.clientRequestId(), r, null); + return store.detail(doc); + } + + @Transactional(rollbackFor = Exception.class) + public RecallDetail draft(String num, SaveDraftRequest r) { + store.lock(); + RecallDocument doc = store.load(num); + ReviewRecallStore.identifier(r.clientRequestId()); + String payloadHash = RecallJson.hash(json.write(r)); + if (Objects.equals(doc.getLastDraftRequestId(), r.clientRequestId())) { + if (!Objects.equals(doc.getLastDraftPayloadHash(), payloadHash)) { + throw new RecallBusinessException("REQUEST_ID_CONFLICT", "这次提交编号已用于其他内容,请保留输入并重新提交"); + } + return store.detail(doc); + } + store.guard(doc.getDetail(), r.editorId(), r.writeToken()); + saveExpression(doc, r.expression()); + timing(doc, r.timing()); + store.rotateWriteToken(doc.getDetail()); + doc.setLastDraftRequestId(r.clientRequestId()); + doc.setLastDraftPayloadHash(payloadHash); + store.persist(doc); + return store.detail(doc); + } + + @Transactional(rollbackFor = Exception.class) + public RecallDetail end(String num, EndRequest r) { + return mutate(num, "END", r.clientRequestId(), r, r.editorId(), r.writeToken(), doc -> { + saveExpression(doc, r.expression()); + timing(doc, r.timing()); + doc.getDetail().setStatus("ENDED"); + doc.getDetail().setEndedAt(Instant.now()); + }); + } + + private RecallDetail mutate( + String num, + String op, + String id, + Object payload, + String editor, + String writeToken, + Consumer mutation) { + store.lock(); + RecallDocument doc = store.load(num); + if (store.replay(num, op, id, payload) != null) { + return store.detail(doc); + } + store.guard(doc.getDetail(), editor, writeToken); + mutation.accept(doc); + store.rotateWriteToken(doc.getDetail()); + store.persist(doc); + store.receipt(num, op, id, payload, null); + return store.detail(doc); + } + + private void saveExpression(RecallDocument doc, Expression expression) { + validateExpression(doc, expression); + doc.getDetail().setExpression(expression); + } + + public void validateExpression(RecallDocument doc, Expression expression) { + validator.validate(doc, expression); + } + + public void timing(RecallDocument doc, Timing timing) { + long acceptedActiveMs = doc.getAcceptedSegmentMs(); + long acceptedActualMs = doc.getAcceptedSegmentActualMs() == null ? 0 : doc.getAcceptedSegmentActualMs(); + long segmentActualMs = + RecallExpressionValidator.validateSegmentTiming(timing, acceptedActiveMs, acceptedActualMs); + RecallExpressionValidator.validateElapsed(doc, timing, segmentActualMs); + RecallDetail detail = doc.getDetail(); + long committedActual = detail.getActualDurationMs() == null ? 0 : detail.getActualDurationMs(); + detail.setActiveDurationMs( + Math.addExact(detail.getActiveDurationMs(), timing.segmentActiveMs() - acceptedActiveMs)); + detail.setActualDurationMs(Math.addExact(committedActual, segmentActualMs - acceptedActualMs)); + doc.setAcceptedSegmentMs(timing.segmentActiveMs()); + doc.setAcceptedSegmentActualMs(segmentActualMs); + } + + @Transactional(rollbackFor = Exception.class) + public ReferencePage references(String num, int pageNum, int pageSize) { + if (pageNum < 1 || pageSize < 1 || pageSize > 50) { + RecallExpressionValidator.invalid(); + } + store.lock(); + RecallDocument doc = store.load(num); + List sources = + RecallReferenceLoader.knowledgeSources(doc.getReference().sources()); + int start = Math.min(sources.size(), (pageNum - 1) * pageSize); + int end = Math.min(sources.size(), start + pageSize); + List items = sources.subList(start, end).stream() + .map(s -> + new ReferenceSourceSummary(s.sourceId(), s.title(), preview(s.content()), s.role(), s.status())) + .toList(); + return new ReferencePage(pageNum, pageSize, sources.size(), items); + } + + private static String preview(String content) { + if (content == null) { + return ""; + } + int end = content.offsetByCodePoints(0, Math.min(content.codePointCount(0, content.length()), 220)); + return content.substring(0, end); + } + + @Transactional(rollbackFor = Exception.class) + public ReferenceContent source(String num, String sourceId) { + store.lock(); + ReferenceSnapshot ref = store.load(num).getReference(); + ReferenceSource source = ref.sources().stream() + .filter(s -> s.sourceId().equals(sourceId)) + .findFirst() + .orElseThrow(() -> new RecallBusinessException("REFERENCE_UNAVAILABLE", "这份来源不在本次资料中,请重新打开回忆")); + return new ReferenceContent( + source.sourceId(), source.title(), source.content(), source.role(), source.status()); + } + + @Transactional(rollbackFor = Exception.class) + public void delete(String num) { + store.lock(); + store.delete(store.load(num)); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java new file mode 100644 index 0000000..9be5deb --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/recall/ReviewRecallStore.java @@ -0,0 +1,371 @@ +package com.guo.learningprogresstracker.service.recall; + +import cn.dev33.satoken.stp.StpUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.common.TenantContext; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallAiResult; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDetail; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallDocument; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.RecallRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSnapshot; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSource; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceSummary; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.ReferenceUnit; +import com.guo.learningprogresstracker.entity.AiTaskEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallReceiptEntity; +import com.guo.learningprogresstracker.entity.ReviewRecallRequestEntity; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import com.guo.learningprogresstracker.mapper.AiTaskMapper; +import com.guo.learningprogresstracker.mapper.ReviewRecallMapper; +import com.guo.learningprogresstracker.mapper.ReviewRecallReceiptMapper; +import com.guo.learningprogresstracker.mapper.ReviewRecallRequestMapper; +import com.guo.learningprogresstracker.service.ai.RecallAiClient; +import com.guo.learningprogresstracker.service.ai.RecallJson; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Short database transactions serialize current recall writes and privacy redaction per owner. */ +@Slf4j +@Component +@RequiredArgsConstructor +public class ReviewRecallStore { + private final ReviewRecallMapper recalls; + private final ReviewRecallReceiptMapper receipts; + private final ReviewRecallRequestMapper requests; + private final AiTaskMapper aiTasks; + private final RecallJson json; + private final RecallReferenceLoader references; + private final RecallAiClient client; + + public static String user() { + return TenantContext.get() != null ? TenantContext.get().loginId() : StpUtil.getLoginIdAsString(); + } + + public void lock() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Recall lock requires a transaction"); + } + recalls.ensureOwnerLock(user()); + if (recalls.lockUser(user()) == null) { + throw new RecallBusinessException("NOT_FOUND", "请重新登录后继续"); + } + } + + public ReviewRecallEntity entity(String num) { + ReviewRecallEntity e = + recalls.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallEntity::getRecallNum, num)); + if (e == null || e.getDocumentJson() == null) { + throw new RecallBusinessException("NOT_FOUND", "这次回忆已不可用,请从历史或范围入口重新打开"); + } + return e; + } + + public RecallDocument load(String num) { + ReviewRecallEntity row = entity(num); + try { + RecallDocument d = json.readStored(row.getDocumentJson(), RecallDocument.class); + reconcile(d); + return d; + } catch (IllegalStateException | NullPointerException | ClassCastException e) { + // 只把「文档形状读不出来」当作损坏并删行;数据库或事务异常照常上抛,不能连带删掉用户数据。 + log.warn("[回忆] 旧版本或不兼容文档已删除: recallNum={}", num); + deleteUnreadable(row); + throw new RecallBusinessException("STORED_DATA_INVALID", "这次回忆的数据来自旧版本,已删除;请重新开始。"); + } + } + + /** Breaking schema changes delete unreadable rows instead of hiding or preserving them. */ + public void deleteUnreadable(ReviewRecallEntity row) { + List linked = requests.selectList(Wrappers.lambdaQuery() + .eq(ReviewRecallRequestEntity::getRecallNum, row.getRecallNum())); + for (ReviewRecallRequestEntity request : linked) { + if (request.getTaskNum() != null) { + invalidateTask(request.getTaskNum()); + } + requests.deleteById(request.getId()); + } + receipts.delete(Wrappers.lambdaQuery() + .eq(ReviewRecallReceiptEntity::getRecallNum, row.getRecallNum())); + recalls.update( + null, + Wrappers.lambdaUpdate() + .eq(ReviewRecallEntity::getRecallNum, row.getRecallNum()) + .set(ReviewRecallEntity::getDocumentJson, null) + .set(ReviewRecallEntity::getDeleted, 1)); + } + + public void insert(RecallDocument d) { + ReviewRecallEntity e = new ReviewRecallEntity(); + setEntity(e, d); + recalls.insert(e); + } + + public void persist(RecallDocument d) { + ReviewRecallEntity e = entity(d.getDetail().getRecallNum()); + setEntity(e, d); + recalls.updateById(e); + } + + private void setEntity(ReviewRecallEntity e, RecallDocument d) { + RecallDetail v = d.getDetail(); + e.setRecallNum(v.getRecallNum()); + e.setScopeType(v.getScope().type()); + e.setTaskNum(v.getScope().taskNum()); + e.setScopeKey(v.getScope().scopeKey()); + e.setStatus(v.getStatus()); + e.setActiveDurationMs(v.getActiveDurationMs()); + e.setDocumentJson(json.write(d)); + e.setLastModifiedTime(LocalDateTime.ofInstant(v.getUpdatedAt(), ZoneOffset.UTC)); + } + + public RecallDetail detail(RecallDocument doc) { + RecallDetail v = doc.getDetail(); + ReferenceSnapshot reference = doc.getReference(); + v.setReference(new ReferenceSummary( + reference.status(), + RecallReferenceLoader.knowledgeSources(reference.sources()).size(), + reference.limitations())); + v.setRequests(v.getRequests().stream() + .map(r -> { + ReviewRecallRequestEntity association = request(r.taskNum()); + AiTaskEntity task = task(r.taskNum()); + String status = association == null || Integer.valueOf(1).equals(association.getRedacted()) + ? "FAILED" + : task == null ? "FAILED" : task.getStatus(); + String code = association == null || Integer.valueOf(1).equals(association.getRedacted()) + ? "SOURCE_REDACTED" + : task == null ? "AI_UNAVAILABLE" : task.getErrorCode(); + String message = task == null ? "这次 AI 结果已不可用" : task.getErrorMessage(); + RecallAiResult result = null; + if (task != null && "SUCCEEDED".equals(status)) { + try { + result = json.readStored(task.getResultPayload(), RecallAiResult.class); + } catch (RuntimeException ex) { + status = "FAILED"; + code = "AI_UNAVAILABLE"; + message = "这次 AI 结果是旧版本格式,暂时无法展示;请重新请求。"; + } + } + return new RecallRequest( + r.requestId(), + r.taskNum(), + r.type(), + r.hintForm(), + r.promptVersion(), + status, + code, + message, + r.submittedAt(), + task == null || task.getFinishedTime() == null + ? null + : task.getFinishedTime() + .atZone(ZoneId.systemDefault()) + .toInstant(), + result); + }) + .toList()); + return v; + } + + public AiTaskEntity task(String num) { + return aiTasks.selectOne(Wrappers.lambdaQuery().eq(AiTaskEntity::getTaskNum, num)); + } + + public ReviewRecallRequestEntity request(String taskNum) { + return requests.selectOne( + Wrappers.lambdaQuery().eq(ReviewRecallRequestEntity::getTaskNum, taskNum)); + } + + public void guard(RecallDetail d, String editorId, String writeToken) { + if (!"ACTIVE".equals(d.getStatus())) { + throw new RecallBusinessException("INVALID_INPUT", "这次回忆已经结束,只能回看;请开始新的回忆"); + } + if (!Objects.equals(d.getEditorId(), editorId)) { + throw new RecallBusinessException("EDITOR_REPLACED", "另一页已接管编辑,请保留本地输入并重新恢复"); + } + if (!Objects.equals(d.getWriteToken(), writeToken)) { + throw new RecallBusinessException("REVISION_CONFLICT", "草稿已有更新,请保留本地副本并重新打开"); + } + } + + public void validScope(RecallDocument d) { + if (!"VALID".equals(d.getDetail().getScopeStatus())) { + throw new RecallBusinessException("SCOPE_INVALID", "原范围已失效;表达仍可保存,请重选范围开始新的回忆"); + } + } + + public ReviewRecallReceiptEntity replay(String num, String op, String id, Object payload) { + identifier(id); + String key = RecallJson.hash(json.write(List.of(user(), num, op, id))); + ReviewRecallReceiptEntity receipt = receipts.selectOne( + Wrappers.lambdaQuery().eq(ReviewRecallReceiptEntity::getReceiptKey, key)); + if (receipt != null && !receipt.getPayloadHash().equals(RecallJson.hash(json.write(payload)))) { + throw new RecallBusinessException("REQUEST_ID_CONFLICT", "这次提交编号已用于其他内容,请保留输入并重新提交"); + } + return receipt; + } + + public void receipt(String num, String op, String id, Object payload, String taskNum) { + ReviewRecallReceiptEntity r = new ReviewRecallReceiptEntity(); + r.setReceiptKey(RecallJson.hash(json.write(List.of(user(), "CREATE".equals(op) ? "" : num, op, id)))); + r.setPayloadHash(RecallJson.hash(json.write(payload))); + r.setRecallNum(num); + r.setTaskNum(taskNum); + receipts.insert(r); + } + + public static void identifier(String s) { + if (s == null || s.isBlank() || s.length() > 64) { + throw new RecallBusinessException("INVALID_INPUT", "提交标识不完整,请保留输入并重新打开页面"); + } + } + + public static void conflict(String code, String message) { + throw new RecallBusinessException(code, message); + } + + public void rotateWriteToken(RecallDetail d) { + d.setWriteToken(UUID.randomUUID().toString()); + d.setUpdatedAt(Instant.now()); + } + + /** Redact the single current source set and every result that depended on it. */ + public void reconcile(RecallDocument doc) { + RecallDetail d = doc.getDetail(); + boolean changed = false; + if ("VALID".equals(d.getScopeStatus()) && !references.valid(d.getScope())) { + d.setScopeStatus("INVALID"); + changed = true; + } + Set missing = new HashSet<>(); + for (ReferenceSource source : doc.getReference().sources()) { + if ("AVAILABLE".equals(source.status()) && !references.accessible(source)) { + missing.add(source.sourceId()); + } + } + if (!missing.isEmpty()) { + doc.setReference(redactReference(doc.getReference(), missing, "ACCESS_REVOKED")); + redactRequests(doc); + changed = true; + } + if (changed) { + persist(doc); + } + } + + public ReferenceSnapshot redactReference(ReferenceSnapshot reference, Set sourceIds, String status) { + return new ReferenceSnapshot( + "REDACTED", + reference.sources().stream() + .map(s -> sourceIds.contains(s.sourceId()) + ? new ReferenceSource( + s.sourceId(), + s.type(), + s.entityId(), + "来源已清除", + null, + s.role(), + s.contextType(), + s.contextNum(), + s.relatedFragmentSourceIds(), + status) + : s) + .toList(), + reference.units().stream() + .map(u -> sourceIds.contains(u.sourceId()) + ? new ReferenceUnit( + u.unitId(), u.sourceId(), u.start(), u.end(), null, u.role(), "REDACTED") + : u) + .toList(), + reference.limitations()); + } + + public void redactRequests(RecallDocument doc) { + for (RecallRequest request : doc.getDetail().getRequests()) { + invalidateTask(request.taskNum()); + } + doc.getDetail() + .setRequests(doc.getDetail().getRequests().stream() + .map(r -> new RecallRequest( + r.requestId(), + r.taskNum(), + r.type(), + r.hintForm(), + r.promptVersion(), + "FAILED", + "SOURCE_REDACTED", + "资料已清除,这次 AI 结果不再展示", + r.submittedAt(), + Instant.now(), + null)) + .toList()); + } + + public void invalidateTask(String taskNum) { + ReviewRecallRequestEntity req = request(taskNum); + if (req != null) { + requests.update( + null, + Wrappers.lambdaUpdate() + .eq(ReviewRecallRequestEntity::getId, req.getId()) + .set(ReviewRecallRequestEntity::getRedacted, 1) + .set(ReviewRecallRequestEntity::getParamsJson, null)); + if (req.getRemoteTaskId() != null) { + purgeAfterCommit(req.getRemoteTaskId()); + } + } + aiTasks.update( + null, + Wrappers.lambdaUpdate() + .eq(AiTaskEntity::getTaskNum, taskNum) + .in(AiTaskEntity::getAiType, "RECALL_HINT", "RECALL_CHECK") + .set(AiTaskEntity::getStatus, "FAILED") + .set(AiTaskEntity::getRequestPayload, null) + .set(AiTaskEntity::getResultPayload, null) + .set(AiTaskEntity::getErrorCode, "SOURCE_REDACTED") + .set(AiTaskEntity::getErrorMessage, "资料已清除,这次 AI 结果不再展示") + .set(AiTaskEntity::getFinishedTime, LocalDateTime.now())); + } + + public void purgeAfterCommit(String remoteId) { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + client.purge(remoteId); + } + }); + } else { + client.purge(remoteId); + } + } + + public void delete(RecallDocument doc) { + for (RecallRequest r : doc.getDetail().getRequests()) { + invalidateTask(r.taskNum()); + } + recalls.update( + null, + Wrappers.lambdaUpdate() + .eq(ReviewRecallEntity::getRecallNum, doc.getDetail().getRecallNum()) + .set(ReviewRecallEntity::getDocumentJson, null) + .set(ReviewRecallEntity::getDeleted, 1)); + } + + public List all() { + return recalls.selectList(Wrappers.lambdaQuery()); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/review/ReviewFeedService.java b/src/main/java/com/guo/learningprogresstracker/service/review/ReviewFeedService.java new file mode 100644 index 0000000..2199e2f --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/review/ReviewFeedService.java @@ -0,0 +1,373 @@ +package com.guo.learningprogresstracker.service.review; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.guo.learningprogresstracker.dto.IdRange; +import com.guo.learningprogresstracker.dto.ReviewFeedItem; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.StudyReportsEntity; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.entity.UserReviewPreferencesEntity; +import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum; +import com.guo.learningprogresstracker.enums.ReviewSortPresetEnum; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.StudyReportsMapper; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.mapper.UserReviewPreferencesMapper; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * 复习 feed 的组织与取样(复习-01 / 复习-03 / 复习-05)。 + * + *

只负责「拿哪些内容、按什么顺序给」:报告与碎片的合并、摘要截断、随机/智能两种取样。 + * 统计口径不在这里,见 {@link ReviewStatsService}。

+ */ +@Component +@RequiredArgsConstructor +public class ReviewFeedService { + + private static final int DEFAULT_LIMIT = 30; + private static final int MAX_LIMIT = 100; + private static final String RANDOM_MODE = "random"; + private static final String SMART_MODE = "smart"; + private static final int SMART_CANDIDATE_MULTIPLIER = 5; + private static final String SOURCE_REPORT = "REPORT"; + private static final String SOURCE_FRAGMENT = "FRAGMENT"; + /** Feed 条目只返回这么长的摘要;全文由详情接口按需拉取(复习-05) */ + private static final int FEED_SUMMARY_MAX_LENGTH = 200; + /** 时间效应封顶天数 */ + private static final int AGE_CEILING_DAYS = 90; + /** 「稍后再看」的权重倍数(提高出现概率) */ + private static final double REVISIT_FACTOR = 1.6; + /** 「已掌握」的权重倍数:降低但不归零,保留文档要求的随机性 */ + private static final double MASTERED_FACTOR = 0.3; + + private final StudyReportsMapper studyReportsMapper; + private final StudyReportFragmentsMapper studyReportFragmentsMapper; + private final StudySessionsMapper studySessionsMapper; + private final TasksMapper tasksMapper; + private final UserReviewPreferencesMapper userReviewPreferencesMapper; + + public List getReviewFeed(int limit, String mode) { + int safeLimit = normalizeLimit(limit); + if (SMART_MODE.equalsIgnoreCase(mode)) { + return getSmartFeed(safeLimit); + } + boolean random = RANDOM_MODE.equalsIgnoreCase(mode); + + List fragments = random + ? randomFragments(safeLimit) + : studyReportFragmentsMapper + .selectPage( + new Page<>(1, safeLimit), + Wrappers.lambdaQuery() + .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)) + .getRecords(); + + List items = mergeAndConvert(List.of(), fragments); + if (random) { + Collections.shuffle(items); + } + return items.stream().limit(safeLimit).collect(Collectors.toList()); + } + + /** + * 随机取样知识碎片(复习-03)。 + * + *

不使用 {@code ORDER BY RAND()}:那在 MySQL 上是全表随机排序,一次 Feed 请求会触发两次。 + * 改为「随机起点 + 顺序取窗口」:先取主键区间,随机选一个起点,再按 id 顺序取够数量; + * 不足时从头回绕补齐(id 与创建时间同向,回绕等价于取更早的内容)。删除造成的 id 空洞会让 + * 靠后的内容被略微偏重,对「偶遇式」的 Feed 来说可以接受。

+ */ + private List randomFragments(int limit) { + IdRange range = studyReportFragmentsMapper.selectIdRange(); + if (range == null || range.isEmpty()) { + return Collections.emptyList(); + } + + long start = range.getMinId() + (long) (ThreadLocalRandom.current().nextDouble() * range.span()); + + // 用 LinkedHashMap 去重:回绕补齐时可能取到与首轮相同的行 + Map picked = new LinkedHashMap<>(); + collectFrom(start, limit, picked); + if (picked.size() < limit) { + collectFrom(range.getMinId(), limit - picked.size(), picked); + } + return new ArrayList<>(picked.values()); + } + + /** 从 startId 起按 id 顺序取至多 count 条,按主键去重后并入 picked */ + private void collectFrom(long startId, int count, Map picked) { + if (count <= 0) { + return; + } + List window = studyReportFragmentsMapper + .selectPage( + new Page<>(1, count), + Wrappers.lambdaQuery() + .ge(StudyReportFragmentsEntity::getId, startId) + .orderByAsc(StudyReportFragmentsEntity::getId)) + .getRecords(); + for (StudyReportFragmentsEntity fragment : window) { + picked.putIfAbsent(fragment.getId(), fragment); + } + } + + /** + * 智能模式:加权随机采样,让更需要复习的内容有更高概率出现。 + * 权重只使用时间与用户明确碎片反馈,不消费旧结构覆盖率。 + * 仍保持随机性,只是"随机得不那么均匀"——符合复习模块无压力、偶遇式的设计理念。 + */ + private List getSmartFeed(int safeLimit) { + int candidateLimit = Math.min(safeLimit * SMART_CANDIDATE_MULTIPLIER, 500); + + List fragments = randomFragments(candidateLimit); + + List candidates = mergeAndConvert(List.of(), fragments); + if (candidates.size() <= safeLimit) { + Collections.shuffle(candidates); + return candidates; + } + + LocalDateTime now = LocalDateTime.now(); + // 排序信号强度由用户的档位决定(复习-01) + ReviewSortPresetEnum preset = loadSortPreset(); + List weights = new ArrayList<>(candidates.size()); + for (ReviewFeedItem item : candidates) { + weights.add(reviewNeedWeight(item, now, preset)); + } + return weightedSample(candidates, weights, safeLimit); + } + + /** 时间效应 × 用户明确碎片反馈;不推导任务掌握度。 */ + private double reviewNeedWeight(ReviewFeedItem item, LocalDateTime now, ReviewSortPresetEnum preset) { + // 信号一:时间效应。以「最近接触时间」为准,这样展开看过的内容会重新变「新」 + LocalDateTime basis = item.getLastReviewedTime() != null ? item.getLastReviewedTime() : item.getCreatedTime(); + double ageDays = basis == null + ? 30 + : Math.max(0, java.time.Duration.between(basis, now).toDays()); + double ageProgress = Math.min(ageDays, AGE_CEILING_DAYS) / AGE_CEILING_DAYS; + double ageFactor = (1 - preset.getAgeInfluence()) + ageProgress * preset.getAgeInfluence(); + + // 反馈动作。「稍后再看」是明确的「想再看」,优先于「已掌握」 + double feedbackFactor = 1.0; + if (Boolean.TRUE.equals(item.getRevisit())) { + feedbackFactor = REVISIT_FACTOR; + } else if (Boolean.TRUE.equals(item.getMastered())) { + feedbackFactor = MASTERED_FACTOR; + } + + return ageFactor * feedbackFactor; + } + + /** 按权重不放回采样 */ + private List weightedSample(List items, List weights, int count) { + List pool = new ArrayList<>(items); + List poolWeights = new ArrayList<>(weights); + List selected = new ArrayList<>(count); + Random random = new Random(); + + while (selected.size() < count && !pool.isEmpty()) { + double total = poolWeights.stream().mapToDouble(Double::doubleValue).sum(); + double r = random.nextDouble() * total; + double cumulative = 0; + int chosen = pool.size() - 1; + for (int i = 0; i < pool.size(); i++) { + cumulative += poolWeights.get(i); + if (r <= cumulative) { + chosen = i; + break; + } + } + selected.add(pool.remove(chosen)); + poolWeights.remove(chosen); + } + return selected; + } + + /** + * 获取指定任务下的所有报告和残片 + */ + public List getTaskReview(String taskNum) { + // 报告按会话生成:取属于该任务的会话所产生的报告 + List sessionNums = studySessionsMapper + .selectList(Wrappers.lambdaQuery() + .eq(StudySessionsEntity::getTaskNum, taskNum) + .select(StudySessionsEntity::getSessionNum)) + .stream() + .map(StudySessionsEntity::getSessionNum) + .collect(Collectors.toList()); + + List reports = sessionNums.isEmpty() + ? List.of() + : studyReportsMapper.selectList(Wrappers.lambdaQuery() + .in(StudyReportsEntity::getSessionNum, sessionNums) + .orderByDesc(StudyReportsEntity::getCreatedTime)); + + // 知识碎片按内容归属:只看它属于谁,不看它产生于哪次会话(归属-01) + List fragments = + studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() + .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) + .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)); + + return mergeAndConvert(reports, fragments); + } + + /** + * 将报告和残片合并转换为 ReviewFeedItem 列表,按创建时间倒序排列 + */ + private List mergeAndConvert( + List reports, List fragments) { + // 报告的任务取自它所属的会话(报告按会话生成) + Set reportSessionNums = reports.stream() + .map(StudyReportsEntity::getSessionNum) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + Map sessionToTaskMap = reportSessionNums.isEmpty() + ? Collections.emptyMap() + : studySessionsMapper + .selectList(Wrappers.lambdaQuery() + .in(StudySessionsEntity::getSessionNum, reportSessionNums) + .select(StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum)) + .stream() + .collect(Collectors.toMap( + StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum, (a, b) -> a)); + + // 碎片的任务取自它自己的内容归属 + Set taskNums = new HashSet<>(sessionToTaskMap.values()); + fragments.stream() + .map(StudyReportFragmentsEntity::getOwnerTaskNum) + .filter(StringUtils::hasText) + .forEach(taskNums::add); + taskNums.removeIf(num -> !StringUtils.hasText(num)); + + Map taskNameMap = taskNums.isEmpty() + ? Collections.emptyMap() + : tasksMapper + .selectList(Wrappers.lambdaQuery() + .in(TaskEntity::getTaskNum, taskNums) + .select(TaskEntity::getTaskNum, TaskEntity::getTaskName)) + .stream() + .collect(Collectors.toMap( + TaskEntity::getTaskNum, + task -> task.getTaskName() == null ? "" : task.getTaskName(), + (a, b) -> a)); + + List reportItems = reports.stream() + .map(r -> { + ReviewFeedItem item = new ReviewFeedItem(); + item.setId(r.getId()); + item.setSourceType(SOURCE_REPORT); + applySummary(item, reportDisplayText(r)); + item.setCreatedTime(r.getCreatedTime()); + item.setContextType(FragmentContextTypeEnum.SESSION.name()); + item.setContextNum(r.getSessionNum()); + String taskNum = sessionToTaskMap.get(r.getSessionNum()); + item.setTaskNum(taskNum); + item.setTaskName(taskNum != null ? taskNameMap.get(taskNum) : null); + return item; + }) + .collect(Collectors.toList()); + + List fragmentItems = fragments.stream() + .map(f -> { + ReviewFeedItem item = new ReviewFeedItem(); + item.setId(f.getId()); + item.setSourceType(SOURCE_FRAGMENT); + applySummary(item, f.getContent()); + item.setCreatedTime(f.getCreatedTime()); + item.setContextType(f.getContextType()); + item.setContextNum(f.getContextNum()); + // 内容归属:为空即「待归类」,前端据此打标并提供就地归类入口 + item.setPendingOwnership(f.isPendingOwnership()); + // 反馈状态与最近接触时间只参与排序计算,不用于列表展示(复习-02:不产生状态展示) + item.setMastered(f.getMastered()); + item.setRevisit(f.getRevisit()); + item.setLastReviewedTime(f.getLastReviewedTime()); + item.setTaskNum(f.getOwnerTaskNum()); + item.setTaskName( + StringUtils.hasText(f.getOwnerTaskNum()) ? taskNameMap.get(f.getOwnerTaskNum()) : null); + return item; + }) + .collect(Collectors.toList()); + + return Stream.concat(reportItems.stream(), fragmentItems.stream()) + .sorted(Comparator.comparing( + ReviewFeedItem::getCreatedTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .collect(Collectors.toList()); + } + + /** + * 把原文放进 Feed 条目:只保留摘要与总长度(复习-05)。 + *

摘要把换行压成空格,避免多行内容在列表里撑高卡片。

+ */ + private static void applySummary(ReviewFeedItem item, String rawContent) { + String full = rawContent == null ? "" : rawContent; + item.setContentLength(full.length()); + if (full.length() <= FEED_SUMMARY_MAX_LENGTH) { + item.setContent(full); + item.setContentTruncated(false); + return; + } + String summary = full.substring(0, FEED_SUMMARY_MAX_LENGTH) + .replaceAll("\\s+", " ") + .trim(); + item.setContent(summary); + item.setContentTruncated(true); + } + + /** + * 报告在列表/Feed 中的展示文本:结构化报告由三段组成,这里按段拼接。 + */ + private static String reportDisplayText(StudyReportsEntity report) { + StringBuilder text = new StringBuilder(); + appendSection(text, "会话摘要", report.getSessionSummary()); + appendSection(text, "预期达成判断", report.getExpectationVerdict()); + appendSection(text, "自由总结", report.getFreeSummary()); + return text.length() == 0 ? "" : text.toString().trim(); + } + + private static void appendSection(StringBuilder text, String title, String body) { + if (body == null || body.isBlank()) { + return; + } + if (text.length() > 0) { + text.append("\n\n"); + } + text.append("【").append(title).append("】\n").append(body.trim()); + } + + private int normalizeLimit(int limit) { + if (limit <= 0) { + return DEFAULT_LIMIT; + } + return Math.min(limit, MAX_LIMIT); + } + + /** 读取当前用户的排序档位;未设置或存坏时回落默认(复习-01) */ + public ReviewSortPresetEnum loadSortPreset() { + UserReviewPreferencesEntity preference = userReviewPreferencesMapper.selectOne( + Wrappers.lambdaQuery().last("LIMIT 1")); + return preference == null + ? ReviewSortPresetEnum.DEFAULT + : ReviewSortPresetEnum.parse(preference.getSortPreset()); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/review/ReviewStatsService.java b/src/main/java/com/guo/learningprogresstracker/service/review/ReviewStatsService.java new file mode 100644 index 0000000..2e28161 --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/review/ReviewStatsService.java @@ -0,0 +1,172 @@ +package com.guo.learningprogresstracker.service.review; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.guo.learningprogresstracker.dto.ReviewSummary; +import com.guo.learningprogresstracker.dto.ReviewTaskStats; +import com.guo.learningprogresstracker.dto.TaskContentCount; +import com.guo.learningprogresstracker.dto.TaskSessionStats; +import com.guo.learningprogresstracker.dto.recall.TaskRecallDuration; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.mapper.ReviewRecallMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.StudyReportsMapper; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * 复习统计数据(总览与任务维度)。 + * + *

口径与 feed 列表一致:报告按「报告 → 会话 → 任务」归属,碎片按内容归属(归属-01)。 + * 聚合一律下推到 SQL(数据-02),返回行数与任务数同阶。

+ */ +@Component +@RequiredArgsConstructor +public class ReviewStatsService { + + private final StudyReportsMapper studyReportsMapper; + private final StudyReportFragmentsMapper studyReportFragmentsMapper; + private final StudySessionsMapper studySessionsMapper; + private final TasksMapper tasksMapper; + private final ReviewRecallMapper newRecallMapper; + + public ReviewSummary summary() { + // 口径必须与 /review/tasks 的列表一致(列表逐页相加 == 这里的汇总): + // 报告按「报告 → 会话 → 任务」归属,碎片按内容归属(owner_task_num)统计。 + // 不能用裸表的 selectCount:那样「学习残片」会把待归类碎片也算进来, + // 与列表逐页相加的结果对不上(待归类在总览里有独立区块展示)。 + return new ReviewSummary( + tasksMapper.selectCount(null), + studyReportsMapper.countOwnedReports(), + studyReportFragmentsMapper.countOwnedFragments()); + } + + public Page getReviewTaskStats(int pageNum, int pageSize, String markerName) { + // 点标签即筛选:过滤下推到 SQL(EXISTS 子查询),由数据库一次算出命中任务并分页; + // 不再「先查全部命中对象号、再拼 IN 回查」——命中量大时 IN 会膨胀。 + IPage taskPage; + if (StringUtils.hasText(markerName)) { + taskPage = tasksMapper.selectPageByMarker(new Page<>(pageNum, pageSize), markerName.trim()); + } else { + taskPage = tasksMapper.selectPage( + new Page<>(pageNum, pageSize), + Wrappers.lambdaQuery() + .orderByDesc(TaskEntity::getCalculatedPriority) + // 优先级相同的任务之间要有稳定次序,否则翻页会重复或漏掉 + .orderByDesc(TaskEntity::getId)); + } + List stats = + taskPage.getRecords().stream().map(this::newTaskStats).collect(Collectors.toList()); + // 聚合只算这一页的任务,不再对全部任务做 IN 聚合 + fillReviewTaskStats(stats); + + Page result = new Page<>(taskPage.getCurrent(), taskPage.getSize(), taskPage.getTotal()); + result.setRecords(stats); + return result; + } + + public ReviewTaskStats getReviewTaskStats(String taskNum) { + TaskEntity task = tasksMapper + .selectList(Wrappers.lambdaQuery() + .eq(TaskEntity::getTaskNum, taskNum) + .last("LIMIT 1")) + .stream() + .findFirst() + .orElse(null); + + ReviewTaskStats stats = newTaskStats(taskNum, task == null ? null : task.getTaskName()); + fillReviewTaskStats(Collections.singletonList(stats)); + return stats; + } + + /** + * 填充任务维度统计(数据-02):三类聚合(会话统计、报告数、碎片数)全部下推到 SQL, + * 每次查询只返回「任务数」量级的行,不随历史会话/内容条数线性增长。 + */ + private void fillReviewTaskStats(List statsList) { + Map statsByTaskNum = statsList.stream() + .filter(item -> StringUtils.hasText(item.getTaskNum())) + .collect(Collectors.toMap(ReviewTaskStats::getTaskNum, item -> item, (a, b) -> a, LinkedHashMap::new)); + + if (statsByTaskNum.isEmpty()) { + return; + } + + Set taskNums = statsByTaskNum.keySet(); + LocalDateTime todayStart = LocalDate.now().atStartOfDay(); + LocalDateTime weekStart = LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay(); + + for (TaskSessionStats row : studySessionsMapper.sumStudyStatsByTask(taskNums, todayStart, weekStart)) { + ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); + if (stats == null) { + continue; + } + long sessionCount = row.getSessionCount() == null ? 0L : row.getSessionCount(); + stats.setSessionCount(sessionCount); + stats.setEffectiveTime(nullToZero(row.getEffectiveTime())); + stats.setTodayEffectiveTime(nullToZero(row.getTodayEffectiveTime())); + stats.setWeekEffectiveTime(nullToZero(row.getWeekEffectiveTime())); + if (sessionCount > 0) { + stats.setAvgEffectiveTime(stats.getEffectiveTime() / sessionCount); + stats.setAvgEffectivenessRatio(nullToZero(row.getEffectivenessRatioSum()) / sessionCount); + } + } + + fillContentCounts(statsByTaskNum, taskNums); + fillReviewDuration(statsByTaskNum); + } + + /** 报告数与碎片数:同样在 SQL 侧按内容归属分组计数 */ + private void fillContentCounts(Map statsByTaskNum, Set taskNums) { + for (TaskContentCount row : studyReportsMapper.countReportsByTask(taskNums)) { + ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); + if (stats != null) { + stats.setReportCount(row.getContentCount() == null ? 0L : row.getContentCount()); + } + } + for (TaskContentCount row : studyReportFragmentsMapper.countFragmentsByTask(taskNums)) { + ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); + if (stats != null) { + stats.setFragmentCount(row.getContentCount() == null ? 0L : row.getContentCount()); + } + } + } + + private static double nullToZero(Double value) { + return value == null ? 0D : value; + } + + /** Current free recall duration is aggregated from the single-current-draft table. */ + private void fillReviewDuration(Map statsByTaskNum) { + for (TaskRecallDuration row : newRecallMapper.sumTaskDuration()) { + ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); + if (stats != null && row.getActiveDurationMs() != null) { + stats.setReviewDurationSeconds(stats.getReviewDurationSeconds() + row.getActiveDurationMs() / 1000); + } + } + } + + private ReviewTaskStats newTaskStats(TaskEntity task) { + return newTaskStats(task.getTaskNum(), task.getTaskName()); + } + + private ReviewTaskStats newTaskStats(String taskNum, String taskName) { + ReviewTaskStats stats = new ReviewTaskStats(); + stats.setTaskNum(taskNum); + stats.setTaskName(taskName); + return stats; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/review/TagDictionaryService.java b/src/main/java/com/guo/learningprogresstracker/service/review/TagDictionaryService.java new file mode 100644 index 0000000..af6022c --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/review/TagDictionaryService.java @@ -0,0 +1,182 @@ +package com.guo.learningprogresstracker.service.review; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.MarkerUsage; +import com.guo.learningprogresstracker.entity.UserTagEntity; +import com.guo.learningprogresstracker.exception.ErrorParameterException; +import com.guo.learningprogresstracker.exception.NotFindEntitiesException; +import com.guo.learningprogresstracker.mapper.MarkerMapper; +import com.guo.learningprogresstracker.mapper.UserTagMapper; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +/** + * 用户标签字典(闭环-03):字典项自身的增删改查,以及打标签时的候选来源。 + * + *

字典只管「有哪些标签名」;对象上打了哪些标记属于 {@link MarkerServiceImpl}。 + * 两者共用的标签名规范化也放在这里,避免同一个名字在两处各写一套规则。

+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class TagDictionaryService { + + /** 用户标签名的长度上限,与表结构一致 */ + private static final int MAX_MARKER_NAME_LENGTH = 255; + + private final UserTagMapper userTagMapper; + private final MarkerMapper markerMapper; + + public List listDictionaryTags() { + return userTagMapper.selectList(Wrappers.lambdaQuery() + .orderByAsc(UserTagEntity::getTagName) + .orderByAsc(UserTagEntity::getId)); + } + + @Transactional(rollbackFor = Exception.class) + public UserTagEntity createDictionaryTag(String tagName) throws ErrorParameterException { + String display = normalizeTagName(tagName); + String normalized = normalizeTagKey(display); + UserTagEntity existing = userTagMapper.selectAnyByNormalizedName(normalized); + if (existing != null) { + if (existing.getDeleted() == null || existing.getDeleted() == 0) { + // 已在字典里,幂等返回 + return existing; + } + // 曾有同名项被删除:复用(复活)旧行,避免重新插入撞唯一键 + userTagMapper.revive(existing.getId(), display); + return userTagMapper.selectById(existing.getId()); + } + UserTagEntity entity = new UserTagEntity(); + entity.setTagName(display); + entity.setNormalizedName(normalized); + userTagMapper.insert(entity); + return entity; + } + + @Transactional(rollbackFor = Exception.class) + public UserTagEntity renameDictionaryTag(Integer id, String newName) + throws ErrorParameterException, NotFindEntitiesException { + UserTagEntity current = requireDictionaryTag(id); + String display = normalizeTagName(newName); + String normalized = normalizeTagKey(display); + + if (normalized.equals(current.getNormalizedName())) { + // 只是大小写/空白不同:更新展示名即可 + if (!display.equals(current.getTagName())) { + userTagMapper.update( + new UserTagEntity(), + Wrappers.lambdaUpdate() + .eq(UserTagEntity::getId, current.getId()) + .set(UserTagEntity::getTagName, display)); + } + return userTagMapper.selectById(current.getId()); + } + + UserTagEntity target = userTagMapper.selectAnyByNormalizedName(normalized); + if (target != null) { + // 目标名已在字典里(可能是一条被删除的行):合并——保留目标项、删掉当前项 + if (target.getDeleted() != null && target.getDeleted() != 0) { + userTagMapper.revive(target.getId(), display); + } + userTagMapper.deleteById(current.getId()); + log.info("字典标签[{}]改名为[{}],与既有项合并", current.getTagName(), display); + return userTagMapper.selectById(target.getId()); + } + + userTagMapper.update( + new UserTagEntity(), + Wrappers.lambdaUpdate() + .eq(UserTagEntity::getId, current.getId()) + .set(UserTagEntity::getTagName, display) + .set(UserTagEntity::getNormalizedName, normalized)); + log.info("字典标签[{}]改名为[{}]", current.getTagName(), display); + return userTagMapper.selectById(current.getId()); + } + + public void deleteDictionaryTag(Integer id) throws NotFindEntitiesException { + UserTagEntity existing = requireDictionaryTag(id); + // 逻辑删除:只影响候选,对象上已经打好的标记不在此表里,不受影响 + userTagMapper.deleteById(existing.getId()); + log.info("字典标签[{}]已删除", existing.getTagName()); + } + + public List listTagCandidates(String keyword) { + String kw = keyword == null ? "" : keyword.trim().toLowerCase(Locale.ROOT); + // 归一化名 → 展示名;按归一化去重(大小写不敏感),字典展示名优先 + Map candidates = new LinkedHashMap<>(); + for (UserTagEntity tag : listDictionaryTags()) { + candidates.putIfAbsent(tag.getNormalizedName(), tag.getTagName()); + } + // 已使用过的用户标签(含自动任务名标签) + for (MarkerUsage usage : listUsedUserTags()) { + if (!StringUtils.hasText(usage.getMarkerName())) { + continue; + } + String name = usage.getMarkerName().trim(); + candidates.putIfAbsent(normalizeTagKey(name), name); + } + return candidates.values().stream() + .filter(name -> kw.isEmpty() || name.toLowerCase(Locale.ROOT).contains(kw)) + .sorted() + .collect(Collectors.toList()); + } + + /** 打标签与字典写入属于同一次操作,失败交给外层事务回滚。 */ + public void ensureDictionaryEntry(String tagName) { + try { + createDictionaryTag(tagName); + } catch (ErrorParameterException e) { + throw new IllegalStateException("标签字典保存失败", e); + } + } + + /** 标签名规范化:去首尾空白并限制长度 */ + public String normalizeTagName(String markerName) throws ErrorParameterException { + if (!StringUtils.hasText(markerName)) { + throw new ErrorParameterException("标签名不能为空"); + } + String name = markerName.trim(); + if (name.length() > MAX_MARKER_NAME_LENGTH) { + throw new ErrorParameterException("标签名太长了,请控制在 " + MAX_MARKER_NAME_LENGTH + " 个字符以内"); + } + return name; + } + + /** 归一化标签名:去首尾空白 + 小写;用于字典去重与候选过滤(中文不受影响,英文大小写不敏感) */ + private String normalizeTagKey(String tagName) { + return tagName.trim().toLowerCase(Locale.ROOT); + } + + private UserTagEntity requireDictionaryTag(Integer id) throws NotFindEntitiesException { + UserTagEntity existing = id == null ? null : userTagMapper.selectById(id); + if (existing == null) { + log.warn("未能找到标签字典项id[{}]", id); + throw new NotFindEntitiesException("这个标签不存在或已被删除"); + } + return existing; + } + + /** 当前用户已用过的用户标签(该查询不走拦截器,需显式传入登录名) */ + private List listUsedUserTags() { + String createdBy = currentUser(); + return StringUtils.hasText(createdBy) ? markerMapper.selectUserTagUsage(createdBy) : Collections.emptyList(); + } + + private String currentUser() { + try { + return cn.dev33.satoken.stp.StpUtil.getLoginIdAsString(); + } catch (Exception e) { + return null; + } + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/session/StudyReportDraftService.java b/src/main/java/com/guo/learningprogresstracker/service/session/StudyReportDraftService.java new file mode 100644 index 0000000..689f3bb --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/session/StudyReportDraftService.java @@ -0,0 +1,63 @@ +package com.guo.learningprogresstracker.service.session; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.ReportSections; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.service.StudyExpectationsService; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; +import com.guo.learningprogresstracker.service.impl.TasksServiceImpl; +import java.util.List; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +/** + * 学习报告草稿:优先调用 lpt-ai 聚合残片,服务不可用时降级为按序拼接。 + * + *

草稿仅作为编辑起点返回,不落库——最终报告由用户确认后经结束会话保存。 + * 会话与残片的取用由 {@link StudySessionsServiceImpl} 负责,本类只做「残片 → 三段文本」的合成。

+ */ +@Component +@RequiredArgsConstructor +public class StudyReportDraftService { + + private final TasksServiceImpl tasksServiceImpl; + private final StudyExpectationsService studyExpectationsService; + private final AiServiceClient aiServiceClient; + + /** + * 生成三段草稿:会话摘要、预期达成判断、自由总结。 + * + *

AI 可用时由它给出三段草稿;不可用(或失败)时降级为规则拼接: + * 会话摘要 = 碎片条数 + 首条摘要,自由总结留给用户填写,达成判断只在有预期时给一句规则结论。

+ */ + public ReportSections buildDraft(StudySessionsEntity session, List fragments) { + if (fragments.isEmpty()) { + return new ReportSections(null, null, null); + } + String taskName = tasksServiceImpl + .getOneOpt(Wrappers.lambdaQuery(TaskEntity.class).eq(TaskEntity::getTaskNum, session.getTaskNum())) + .map(TaskEntity::getTaskName) + .orElse("学习任务"); + String expectation = Optional.ofNullable(studyExpectationsService.getBySessionNum(session.getSessionNum())) + .map(e -> e.getDescription()) + .orElse(null); + return aiServiceClient + .aggregateReport(taskName, fragments, expectation) + .orElseGet(() -> ruleBasedDraft(fragments, expectation)); + } + + /** + * 规则降级:不依赖 AI 也能给出一份可编辑的草稿。 + *

只做能确定的事——摘要按碎片拼接、达成判断只在存在学习预期时给规则结论, + * 自由总结刻意留空由用户填写(AI 不可用时不应该替他编造卡点与下一步)。

+ */ + private static ReportSections ruleBasedDraft(List fragments, String expectation) { + String summary = String.join("\n", fragments); + String verdict = (expectation == null || expectation.isBlank()) + ? null + : "本次学习记录了 " + fragments.size() + " 条知识碎片,请对照预期自行判断达成情况。"; + return new ReportSections(summary, verdict, null); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionConvergenceScheduler.java b/src/main/java/com/guo/learningprogresstracker/service/session/StudySessionConvergenceScheduler.java similarity index 96% rename from src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionConvergenceScheduler.java rename to src/main/java/com/guo/learningprogresstracker/service/session/StudySessionConvergenceScheduler.java index 970177e..48b0b33 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/StudySessionConvergenceScheduler.java +++ b/src/main/java/com/guo/learningprogresstracker/service/session/StudySessionConvergenceScheduler.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.session; import com.guo.learningprogresstracker.service.StudySessionsService; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/guo/learningprogresstracker/service/session/StudySessionConvergenceService.java b/src/main/java/com/guo/learningprogresstracker/service/session/StudySessionConvergenceService.java new file mode 100644 index 0000000..fce93bb --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/service/session/StudySessionConvergenceService.java @@ -0,0 +1,81 @@ +package com.guo.learningprogresstracker.service.session; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.common.StudyTimePolicy; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.enums.StudySessionStateEnum; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import java.time.LocalDateTime; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +/** + * 悬挂会话收敛(会话-04):把「进行中但早已没人操作」的会话按硬兜底阈值结算成已暂停。 + * + *

两条路径:请求内的惰性收敛走租户隔离查询,只碰当前用户自己的会话; + * 定时扫描在请求之外执行,没有登录态,走忽略租户条件的系统级兜底。 + * 两条路径共用同一条条件更新,保证并发下只结算一次。

+ */ +@Component +@RequiredArgsConstructor +public class StudySessionConvergenceService { + + /** 单次定时扫描最多处理的会话数,避免一次拉回过多数据 */ + private static final int SCAN_BATCH_SIZE = 200; + + private final StudySessionsMapper studySessionsMapper; + private final StudyTimePolicy studyTimePolicy; + + public int convergeStaleSessionsOfCurrentUser() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes()); + + // 惰性收敛走租户隔离路径:只可能读到当前用户自己的会话 + List staleSessions = + studySessionsMapper.selectList(Wrappers.lambdaQuery() + .eq(StudySessionsEntity::getSessionState, StudySessionStateEnum.ONGOING.name()) + .le(StudySessionsEntity::getLastStartTime, cutoff) + .orderByAsc(StudySessionsEntity::getLastStartTime)); + + int converged = 0; + for (StudySessionsEntity session : staleSessions) { + if (convergeOne(session, now)) { + converged++; + } + } + return converged; + } + + public int scanAndConvergeStaleSessions() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes()); + + // 定时任务在请求之外执行,没有登录态,走忽略租户条件的扫描(系统级兜底) + List staleSessions = + studySessionsMapper.selectForcePausableSessions(cutoff, SCAN_BATCH_SIZE); + + int converged = 0; + for (StudySessionsEntity session : staleSessions) { + if (convergeOne(session, now)) { + converged++; + } + } + return converged; + } + + /** + * 收敛单个悬挂会话:先按硬兜底阈值复核,再用「状态仍为 ONGOING」的条件更新写入。 + * + *

条件更新保证惰性收敛与定时扫描并发时只结算一次(与结束会话的幂等处理同一思路), + * 写入按主键定位,所以定时扫描分支可以安全地忽略租户条件。

+ * + * @return 是否由本次调用完成收敛 + */ + private boolean convergeOne(StudySessionsEntity session, LocalDateTime now) { + if (!session.forceConverge(now, studyTimePolicy)) { + return false; + } + return studySessionsMapper.convergeStaleSession(session) > 0; + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/TaskDeletionService.java b/src/main/java/com/guo/learningprogresstracker/service/session/TaskDeletionService.java similarity index 54% rename from src/main/java/com/guo/learningprogresstracker/service/impl/TaskDeletionService.java rename to src/main/java/com/guo/learningprogresstracker/service/session/TaskDeletionService.java index bb73ddf..0f32dfd 100644 --- a/src/main/java/com/guo/learningprogresstracker/service/impl/TaskDeletionService.java +++ b/src/main/java/com/guo/learningprogresstracker/service/session/TaskDeletionService.java @@ -1,18 +1,26 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.session; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.guo.learningprogresstracker.dto.TaskDeletionSummary; -import com.guo.learningprogresstracker.entity.*; -import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.StudyReportsEntity; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.entity.TaskApplicationEntity; +import com.guo.learningprogresstracker.mapper.ReviewStandardMindMapMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.StudyReportsMapper; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapper.TaskApplicationMapper; +import com.guo.learningprogresstracker.service.recall.RecallPrivacyService; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - /** * 删除学习任务时对名下学习记录的处置(归属-01)。 * @@ -20,7 +28,7 @@ import java.util.stream.Collectors; *
    *
  • 知识碎片保留,内容归属置空 → 进入待归类。删任务撤销的是「这次学习的时间记录与收敛结果」, * 不是知识本身;碎片是原料,不因归属消失而消失。
  • - *
  • 学习会话、学习报告、标准思维导图、回忆记录、应用场景随任务一并软删除。
  • + *
  • 学习会话、学习报告、标准思维导图、应用场景随任务一并软删除。
  • *
* *

拆成独立组件的原因:{@code TasksServiceImpl} 若直接依赖这些 mapper 会与 @@ -35,26 +43,30 @@ public class TaskDeletionService { private final StudyReportsMapper studyReportsMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final ReviewStandardMindMapMapper standardMindMapMapper; - private final ReviewRecallRecordMapper recallRecordMapper; + private final TaskApplicationMapper taskApplicationMapper; + private final RecallPrivacyService recallPrivacyService; /** * 处置任务名下的学习记录。 * * @return 各对象的处理条数,供接口返回给前端展示(删除确认弹窗要分别列出「即将删除」与「即将保留」) */ - @Transactional + @Transactional(rollbackFor = Exception.class) public TaskDeletionSummary detachAndCleanUp(String taskNum) { + recallPrivacyService.taskDeleted(taskNum); TaskDeletionSummary summary = new TaskDeletionSummary(); // 1. 知识碎片:保留,只把内容归属置空 → 待归类 - List owned = studyReportFragmentsMapper.selectList( - Wrappers.lambdaQuery() + List owned = + studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) .select(StudyReportFragmentsEntity::getId)); if (!owned.isEmpty()) { - List ids = owned.stream().map(StudyReportFragmentsEntity::getId).collect(Collectors.toList()); - int released = studyReportFragmentsMapper.update(null, + List ids = + owned.stream().map(StudyReportFragmentsEntity::getId).collect(Collectors.toList()); + int released = studyReportFragmentsMapper.update( + null, Wrappers.lambdaUpdate() .in(StudyReportFragmentsEntity::getId, ids) .set(StudyReportFragmentsEntity::getOwnerTaskNum, null)); @@ -62,11 +74,12 @@ public class TaskDeletionService { } // 2. 学习会话及其产生的报告:软删除 - List sessionNums = studySessionsMapper.selectList( - Wrappers.lambdaQuery() - .eq(StudySessionsEntity::getTaskNum, taskNum) - .select(StudySessionsEntity::getSessionNum)) - .stream().map(StudySessionsEntity::getSessionNum) + List sessionNums = studySessionsMapper + .selectList(Wrappers.lambdaQuery() + .eq(StudySessionsEntity::getTaskNum, taskNum) + .select(StudySessionsEntity::getSessionNum)) + .stream() + .map(StudySessionsEntity::getSessionNum) .filter(Objects::nonNull) .collect(Collectors.toList()); @@ -77,22 +90,21 @@ public class TaskDeletionService { Wrappers.lambdaQuery().in(StudySessionsEntity::getSessionNum, sessionNums))); } - // 3. 标准思维导图与回忆记录:按任务软删除 - summary.setDeletedMindMaps(standardMindMapMapper.delete( - Wrappers.lambdaQuery() - .eq(ReviewStandardMindMapEntity::getTaskNum, taskNum))); - summary.setDeletedRecallRecords(recallRecordMapper.delete( - Wrappers.lambdaQuery() - .eq(ReviewRecallRecordEntity::getTaskNum, taskNum))); + summary.setDeletedMindMaps(standardMindMapMapper.delete(Wrappers.lambdaQuery() + .eq(ReviewStandardMindMapEntity::getTaskNum, taskNum))); // 4. 应用场景:按任务软删除 summary.setDeletedApplications(taskApplicationMapper.delete( - Wrappers.lambdaQuery() - .eq(TaskApplicationEntity::getTaskNum, taskNum))); + Wrappers.lambdaQuery().eq(TaskApplicationEntity::getTaskNum, taskNum))); - log.info("任务[{}]删除:释放碎片 {} 条,软删会话 {} 个/报告 {} 份/导图 {} 张/回忆记录 {} 条/应用场景 {} 个", - taskNum, summary.getReleasedFragments(), summary.getDeletedSessions(), summary.getDeletedReports(), - summary.getDeletedMindMaps(), summary.getDeletedRecallRecords(), summary.getDeletedApplications()); + log.info( + "任务[{}]删除:释放碎片 {} 条,软删会话 {} 个/报告 {} 份/导图 {} 张/应用场景 {} 个", + taskNum, + summary.getReleasedFragments(), + summary.getDeletedSessions(), + summary.getDeletedReports(), + summary.getDeletedMindMaps(), + summary.getDeletedApplications()); return summary; } @@ -100,15 +112,16 @@ public class TaskDeletionService { public TaskDeletionSummary previewDeletion(String taskNum) { TaskDeletionSummary summary = new TaskDeletionSummary(); - summary.setReleasedFragments(Math.toIntExact(studyReportFragmentsMapper.selectCount( - Wrappers.lambdaQuery() + summary.setReleasedFragments(Math.toIntExact( + studyReportFragmentsMapper.selectCount(Wrappers.lambdaQuery() .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum)))); - List sessionNums = studySessionsMapper.selectList( - Wrappers.lambdaQuery() - .eq(StudySessionsEntity::getTaskNum, taskNum) - .select(StudySessionsEntity::getSessionNum)) - .stream().map(StudySessionsEntity::getSessionNum) + List sessionNums = studySessionsMapper + .selectList(Wrappers.lambdaQuery() + .eq(StudySessionsEntity::getTaskNum, taskNum) + .select(StudySessionsEntity::getSessionNum)) + .stream() + .map(StudySessionsEntity::getSessionNum) .filter(Objects::nonNull) .collect(Collectors.toList()); summary.setDeletedSessions(sessionNums.size()); @@ -117,15 +130,12 @@ public class TaskDeletionService { Wrappers.lambdaQuery().in(StudyReportsEntity::getSessionNum, sessionNums)))); } - summary.setDeletedRecallRecords(Math.toIntExact(recallRecordMapper.selectCount( - Wrappers.lambdaQuery() - .eq(ReviewRecallRecordEntity::getTaskNum, taskNum)))); - summary.setDeletedMindMaps(Math.toIntExact(standardMindMapMapper.selectCount( - Wrappers.lambdaQuery() + summary.setDeletedMindMaps( + Math.toIntExact(standardMindMapMapper.selectCount(Wrappers.lambdaQuery() .eq(ReviewStandardMindMapEntity::getTaskNum, taskNum)))); + summary.setDeletedApplications(Math.toIntExact(taskApplicationMapper.selectCount( - Wrappers.lambdaQuery() - .eq(TaskApplicationEntity::getTaskNum, taskNum)))); + Wrappers.lambdaQuery().eq(TaskApplicationEntity::getTaskNum, taskNum)))); return summary; } } diff --git a/src/main/java/com/guo/learningprogresstracker/utils/CalculatedPriorityTool.java b/src/main/java/com/guo/learningprogresstracker/utils/CalculatedPriorityTool.java index abc793f..53765cd 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/CalculatedPriorityTool.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/CalculatedPriorityTool.java @@ -8,6 +8,8 @@ import com.guo.learningprogresstracker.entity.UserPriorityWeightsEntity; */ public class CalculatedPriorityTool { + private CalculatedPriorityTool() {} + /** * 使用系统默认权重计算加权优先级。 * 紧急性 0.35 / 重要性 0.25 / 内容难度 0.20 / 未来价值 0.10 / 主观优先级 0.10 @@ -20,10 +22,10 @@ public class CalculatedPriorityTool { * 使用用户自定义权重计算加权优先级。 */ public static Double calculatedPriority(PriorityDto priorityDto, UserPriorityWeightsEntity weights) { - return (priorityDto.getUrgency() * weights.getUrgencyWeight()) + - (priorityDto.getImportance() * weights.getImportanceWeight()) + - (priorityDto.getContentDifficulty() * weights.getContentDifficultyWeight()) + - (priorityDto.getFutureValue() * weights.getFutureValueWeight()) + - (priorityDto.getSubjectivePriority() * weights.getSubjectivePriorityWeight()); + return (priorityDto.getUrgency() * weights.getUrgencyWeight()) + + (priorityDto.getImportance() * weights.getImportanceWeight()) + + (priorityDto.getContentDifficulty() * weights.getContentDifficultyWeight()) + + (priorityDto.getFutureValue() * weights.getFutureValueWeight()) + + (priorityDto.getSubjectivePriority() * weights.getSubjectivePriorityWeight()); } } diff --git a/src/main/java/com/guo/learningprogresstracker/utils/CompareResult.java b/src/main/java/com/guo/learningprogresstracker/utils/CompareResult.java deleted file mode 100644 index 2e023b2..0000000 --- a/src/main/java/com/guo/learningprogresstracker/utils/CompareResult.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.guo.learningprogresstracker.utils; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.ArrayList; -import java.util.List; - -/** - * 思维导图结构对比结果。 - * 每个 {@link NodeDiff} 对应标准导图中的一个节点,标注其匹配状态及用户在回忆中撰写的标题。 - */ -@Data -public class CompareResult { - - /** 对比后的完整树(带 MATCHED/MISSED 标注) */ - private MindMapNode matchedTree; - - /** 用户追加但标准导图中不存在的节点 */ - private List extraNodes = new ArrayList<>(); - - /** 回忆覆盖率 0-1 */ - private double recallRatio; - - /** 命中节点数 */ - private int matchedCount; - - /** 遗漏节点数 */ - private int missedCount; - - /** 额外节点数 */ - private int extraCount; - - /** AI 评价文本(仅 AI 对比时有值,内置对比为 null) */ - private String evaluation; - - @Data - @NoArgsConstructor - @AllArgsConstructor - public static class FlatNode { - private String title; - private String path; // 以 / 分隔的路径 - private String sourceType; - private Integer sourceId; - } -} diff --git a/src/main/java/com/guo/learningprogresstracker/utils/ExportMarkdownRenderer.java b/src/main/java/com/guo/learningprogresstracker/utils/ExportMarkdownRenderer.java index aa6ff06..c6ba8a7 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/ExportMarkdownRenderer.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/ExportMarkdownRenderer.java @@ -4,7 +4,6 @@ import com.guo.learningprogresstracker.dto.ExportDocument; import com.guo.learningprogresstracker.dto.ExportEntry; import com.guo.learningprogresstracker.dto.ExportTaskSection; import com.guo.learningprogresstracker.dto.ReviewTaskStats; - import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; @@ -17,15 +16,16 @@ public final class ExportMarkdownRenderer { private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - private ExportMarkdownRenderer() { - } + private ExportMarkdownRenderer() {} public static String render(ExportDocument document) { StringBuilder md = new StringBuilder(); md.append("# LPT 学习数据导出\n\n"); md.append("- 导出时间:").append(formatTime(document.getGeneratedTime())).append('\n'); md.append("- 导出范围:").append(nullToDash(document.getScopeLabel())).append('\n'); - md.append("- 任务数:").append(document.getTasks() == null ? 0 : document.getTasks().size()).append("\n\n"); + md.append("- 任务数:") + .append(document.getTasks() == null ? 0 : document.getTasks().size()) + .append("\n\n"); List tasks = document.getTasks(); if (tasks == null || tasks.isEmpty()) { @@ -46,8 +46,12 @@ public final class ExportMarkdownRenderer { ReviewTaskStats stats = task.getStats(); if (stats != null) { - md.append("- 累计有效学习时长:").append(formatDuration((long) stats.getEffectiveTime())).append('\n'); - md.append("- 累计复习耗时:").append(formatDuration(stats.getReviewDurationSeconds())).append('\n'); + md.append("- 累计有效学习时长:") + .append(formatDuration((long) stats.getEffectiveTime())) + .append('\n'); + md.append("- 累计复习耗时:") + .append(formatDuration(stats.getReviewDurationSeconds())) + .append('\n'); md.append("- 学习会话:").append(stats.getSessionCount()).append(" 次\n"); md.append("- 学习报告:").append(stats.getReportCount()).append(" 份\n"); md.append("- 知识碎片:").append(stats.getFragmentCount()).append(" 条\n"); @@ -71,9 +75,15 @@ public final class ExportMarkdownRenderer { } int index = 1; for (ExportEntry entry : entries) { - md.append("#### ").append(index++).append(". ") + md.append("#### ") + .append(index++) + .append(". ") .append(formatTime(entry.getCreatedTime())) - .append("(会话 `").append(nullToDash(entry.getSessionNum())).append("`)\n\n"); + .append("(") + .append("REVIEW".equals(entry.getContextType()) ? "复习 / 学习引导" : "会话") + .append(" `") + .append(nullToDash(entry.getContextNum() == null ? entry.getSessionNum() : entry.getContextNum())) + .append("`)\n\n"); md.append(nullToDash(entry.getContent())).append("\n\n"); } } diff --git a/src/main/java/com/guo/learningprogresstracker/utils/GenerateNumTool.java b/src/main/java/com/guo/learningprogresstracker/utils/GenerateNumTool.java index 59dc9c7..620d408 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/GenerateNumTool.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/GenerateNumTool.java @@ -1,7 +1,5 @@ package com.guo.learningprogresstracker.utils; -import lombok.RequiredArgsConstructor; - import java.security.SecureRandom; import java.text.SimpleDateFormat; import java.util.Date; @@ -13,9 +11,10 @@ import java.util.Date; * 且该片段每 16.7 分钟就会重复一轮;现在追加 6 位随机数把撞号概率降到 1e-6 量级, * 最终防线是数据库唯一索引(见迁移 {@code V20261009_3})。

*/ -@RequiredArgsConstructor public class GenerateNumTool { + private GenerateNumTool() {} + /** 毫秒片段取值范围:保持既有编码的可读形态 */ private static final int MILLIS_SEQUENCE_BOUND = 1_000_000; diff --git a/src/main/java/com/guo/learningprogresstracker/utils/MindMapMatchTool.java b/src/main/java/com/guo/learningprogresstracker/utils/MindMapMatchTool.java new file mode 100644 index 0000000..94d918f --- /dev/null +++ b/src/main/java/com/guo/learningprogresstracker/utils/MindMapMatchTool.java @@ -0,0 +1,200 @@ +package com.guo.learningprogresstracker.utils; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * 思维导图的节点匹配与合并:按标题相似度找最接近的节点、取节点路径、把新树合并进旧树。 + * + *

相似度只做标题/备注的字符比较,不调用模型;合并时旧树优先,保留用户已有的编辑。

+ */ +public class MindMapMatchTool { + + private MindMapMatchTool() {} + + /** + * 查找与 content 最相似的节点。基于 title 的 bigram Jaccard 相似度。 + * @return 得分最高的节点,若所有节点得分均低于 0.1 则返回 null + */ + public static MindMapNode findClosestNode(MindMapNode root, String content) { + if (root == null || content == null || content.isBlank()) { + return null; + } + List flat = MindMapTreeTool.flatten(root); + MindMapNode best = null; + double bestScore = 0.0; + for (MindMapNode node : flat) { + if (node.getTitle() == null || node.getTitle().isBlank()) { + continue; + } + double score = similarityScore(node.getTitle(), content); + // notes 也参与匹配,但权重减半 + if (node.getNotes() != null && !node.getNotes().isBlank()) { + double noteScore = similarityScore(node.getNotes(), content); + score = Math.max(score, noteScore * 0.5); + } + if (score > bestScore) { + bestScore = score; + best = node; + } + } + return bestScore > 0.1 ? best : null; + } + + /** + * 获取节点在树中的路径(以 / 分隔的 title 序列) + */ + public static String getPath(MindMapNode root, String targetTitle) { + if (root == null || targetTitle == null) { + return ""; + } + List path = new ArrayList<>(); + if (findPathRecursive(root, targetTitle, path)) { + return String.join(" / ", path); + } + return ""; + } + + private static boolean findPathRecursive(MindMapNode node, String targetTitle, List path) { + if (node == null) { + return false; + } + path.add(node.getTitle() != null ? node.getTitle() : ""); + if (normalizeForMerge(node.getTitle()).equals(normalizeForMerge(targetTitle))) { + return true; + } + if (node.getChildren() != null) { + for (MindMapNode child : node.getChildren()) { + if (findPathRecursive(child, targetTitle, path)) { + return true; + } + } + } + path.remove(path.size() - 1); + return false; + } + + /** bigram Jaccard 相似度 */ + public static double similarityScore(String a, String b) { + if (a == null || b == null) { + return 0; + } + String na = normalizeForMerge(a); + String nb = normalizeForMerge(b); + if (na.isEmpty() || nb.isEmpty()) { + return 0; + } + if (na.equals(nb)) { + return 1.0; + } + // 子串匹配 + if (na.contains(nb) || nb.contains(na)) { + return 0.9; + } + Set bigramsA = bigrams(na); + Set bigramsB = bigrams(nb); + if (bigramsA.isEmpty() && bigramsB.isEmpty()) { + return 0; + } + Set union = new HashSet<>(bigramsA); + union.addAll(bigramsB); + Set intersect = new HashSet<>(bigramsA); + intersect.retainAll(bigramsB); + return (double) intersect.size() / union.size(); + } + + private static Set bigrams(String s) { + Set set = new LinkedHashSet<>(); + for (int i = 0; i < s.length() - 1; i++) { + set.add(s.substring(i, i + 2)); + } + return set; + } + + /** + * 合并新旧树:保留旧树中已有节点(用户编辑),追加新树中的新节点。 + * 按标准化标题匹配同级节点,旧树匹配到的节点优先保留。 + * + * @param oldRoot 旧树根(用户可能编辑过) + * @param newRoot 新树根(AI/BUILTIN 最新生成) + * @return 合并后的树 + */ + public static MindMapNode mergeTrees(MindMapNode oldRoot, MindMapNode newRoot) { + if (oldRoot == null) { + return newRoot; + } + if (newRoot == null) { + return oldRoot; + } + MindMapNode result = copyNodeShallow(oldRoot); + result.setChildren(mergeChildren(oldRoot.getChildren(), newRoot.getChildren())); + return result; + } + + /** 递归合并子节点列表 */ + private static List mergeChildren(List oldChildren, List newChildren) { + Map oldByNormalized = new LinkedHashMap<>(); + if (oldChildren != null) { + for (MindMapNode child : oldChildren) { + oldByNormalized.put(normalizeForMerge(child.getTitle()), child); + } + } + + List merged = new ArrayList<>(); + Set usedKeys = new HashSet<>(); + + if (newChildren != null) { + for (MindMapNode newNode : newChildren) { + String key = normalizeForMerge(newNode.getTitle()); + MindMapNode oldNode = oldByNormalized.get(key); + if (oldNode != null) { + // 旧节点存在:保留旧节点标题,递归合并子节点 + MindMapNode kept = copyNodeShallow(oldNode); + kept.setChildren(mergeChildren(oldNode.getChildren(), newNode.getChildren())); + merged.add(kept); + usedKeys.add(key); + } else { + // 新节点:直接添加 + merged.add(newNode); + } + } + } + + // 添加旧树中有但新树中没有的节点(用户添加的额外节点) + if (oldChildren != null) { + for (MindMapNode oldNode : oldChildren) { + if (!usedKeys.contains(normalizeForMerge(oldNode.getTitle()))) { + merged.add(oldNode); + } + } + } + + return merged; + } + + /** 浅拷贝节点(仅拷贝标量字段,不拷贝 children) */ + private static MindMapNode copyNodeShallow(MindMapNode node) { + MindMapNode copy = new MindMapNode(); + copy.setTitle(node.getTitle()); + copy.setNotes(node.getNotes()); + copy.setSourceType(node.getSourceType()); + copy.setSourceId(node.getSourceId()); + return copy; + } + + /** 比对用的标准化标题:去掉空白与标点、统一小写(包内共用,路径匹配与合并必须同一套规则) */ + static String normalizeForMerge(String s) { + if (s == null) { + return ""; + } + return s.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", "") + .toLowerCase(Locale.ROOT) + .trim(); + } +} diff --git a/src/main/java/com/guo/learningprogresstracker/utils/MindMapNode.java b/src/main/java/com/guo/learningprogresstracker/utils/MindMapNode.java index 78d126a..70112ac 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/MindMapNode.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/MindMapNode.java @@ -1,15 +1,14 @@ package com.guo.learningprogresstracker.utils; import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; /** * 思维导图树节点 DTO,与 MindMapFileParser 的输出结构兼容。 @@ -49,8 +48,12 @@ public class MindMapNode { Map map = new LinkedHashMap<>(); map.put("title", title != null ? title : ""); map.put("notes", notes != null ? notes : ""); - if (sourceType != null) map.put("sourceType", sourceType); - if (sourceId != null) map.put("sourceId", sourceId); + if (sourceType != null) { + map.put("sourceType", sourceType); + } + if (sourceId != null) { + map.put("sourceId", sourceId); + } List childMaps = new ArrayList<>(); if (children != null) { for (MindMapNode c : children) { diff --git a/src/main/java/com/guo/learningprogresstracker/utils/MindMapTreeTool.java b/src/main/java/com/guo/learningprogresstracker/utils/MindMapTreeTool.java index 1c13405..1f98233 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/MindMapTreeTool.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/MindMapTreeTool.java @@ -1,9 +1,10 @@ package com.guo.learningprogresstracker.utils; import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.Getter; - -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; /** * 思维导图树结构与缩进大纲文本之间的双向转换工具。 @@ -13,8 +14,7 @@ public class MindMapTreeTool { private static final int INDENT_SPACES = 2; - private MindMapTreeTool() { - } + private MindMapTreeTool() {} // ============ 序列化:树 → 缩进大纲 ============ @@ -29,7 +29,10 @@ public class MindMapTreeTool { private static void appendOutline(StringBuilder sb, MindMapNode node, int level) { if (level > 0) { - sb.append(" ".repeat(level)).append("- ").append(node.getTitle() != null ? node.getTitle() : "").append('\n'); + sb.append(" ".repeat(level)) + .append("- ") + .append(node.getTitle() != null ? node.getTitle() : "") + .append('\n'); } if (node.getChildren() != null) { for (MindMapNode child : node.getChildren()) { @@ -110,8 +113,12 @@ public class MindMapTreeTool { while (hashCount < trimmed.length() && trimmed.charAt(hashCount) == '#') { hashCount++; } - if (hashCount > 0) return hashCount; - if (indent == 0) return 1; + if (hashCount > 0) { + return hashCount; + } + if (indent == 0) { + return 1; + } return Math.max(1, indent / INDENT_SPACES + 1); } @@ -122,8 +129,7 @@ public class MindMapTreeTool { .strip(); } - private record StackEntry(int level, List children) { - } + private record StackEntry(int level, List children) {} // ============ 工具方法 ============ @@ -153,17 +159,11 @@ public class MindMapTreeTool { if (node.getChildren() == null || node.getChildren().isEmpty()) { return 1; } - return 1 + node.getChildren().stream().mapToInt(MindMapTreeTool::maxDepth).max().orElse(0); - } - - /** 浅拷贝节点(仅拷贝标量字段,不拷贝 children) */ - private static MindMapNode copyNodeShallow(MindMapNode node) { - MindMapNode copy = new MindMapNode(); - copy.setTitle(node.getTitle()); - copy.setNotes(node.getNotes()); - copy.setSourceType(node.getSourceType()); - copy.setSourceId(node.getSourceId()); - return copy; + return 1 + + node.getChildren().stream() + .mapToInt(MindMapTreeTool::maxDepth) + .max() + .orElse(0); } /** @@ -173,19 +173,27 @@ public class MindMapTreeTool { * @return 以路径末端节点为根的深拷贝子树,匹配失败时返回 null */ public static MindMapNode extractSubtree(MindMapNode root, String path) { - if (root == null || path == null || path.isBlank()) return null; + if (root == null || path == null || path.isBlank()) { + return null; + } String[] segments = path.split("\\s*/\\s*"); MindMapNode current = root; for (int i = 0; i < segments.length; i++) { String seg = segments[i].trim(); - if (seg.isEmpty()) continue; - if (current.getTitle() != null && normalizeForMerge(current.getTitle()).equals(normalizeForMerge(seg))) { + if (seg.isEmpty()) { + continue; + } + if (current.getTitle() != null + && MindMapMatchTool.normalizeForMerge(current.getTitle()) + .equals(MindMapMatchTool.normalizeForMerge(seg))) { continue; // 当前节点已匹配,看下一段 } MindMapNode found = null; if (current.getChildren() != null) { for (MindMapNode child : current.getChildren()) { - if (child.getTitle() != null && normalizeForMerge(child.getTitle()).equals(normalizeForMerge(seg))) { + if (child.getTitle() != null + && MindMapMatchTool.normalizeForMerge(child.getTitle()) + .equals(MindMapMatchTool.normalizeForMerge(seg))) { found = child; break; } @@ -202,7 +210,9 @@ public class MindMapTreeTool { /** 深拷贝节点及其子树 */ private static MindMapNode deepCopy(MindMapNode node) { - if (node == null) return null; + if (node == null) { + return null; + } MindMapNode copy = new MindMapNode(); copy.setTitle(node.getTitle()); copy.setNotes(node.getNotes()); @@ -218,147 +228,6 @@ public class MindMapTreeTool { return copy; } - /** - * 查找与 content 最相似的节点。基于 title 的 bigram Jaccard 相似度。 - * @return 得分最高的节点,若所有节点得分均低于 0.1 则返回 null - */ - public static MindMapNode findClosestNode(MindMapNode root, String content) { - if (root == null || content == null || content.isBlank()) return null; - List flat = flatten(root); - MindMapNode best = null; - double bestScore = 0.0; - for (MindMapNode node : flat) { - if (node.getTitle() == null || node.getTitle().isBlank()) continue; - double score = similarityScore(node.getTitle(), content); - // notes 也参与匹配,但权重减半 - if (node.getNotes() != null && !node.getNotes().isBlank()) { - double noteScore = similarityScore(node.getNotes(), content); - score = Math.max(score, noteScore * 0.5); - } - if (score > bestScore) { - bestScore = score; - best = node; - } - } - return bestScore > 0.1 ? best : null; - } - - /** - * 获取节点在树中的路径(以 / 分隔的 title 序列) - */ - public static String getPath(MindMapNode root, String targetTitle) { - if (root == null || targetTitle == null) return ""; - List path = new ArrayList<>(); - if (findPathRecursive(root, targetTitle, path)) { - return String.join(" / ", path); - } - return ""; - } - - private static boolean findPathRecursive(MindMapNode node, String targetTitle, List path) { - if (node == null) return false; - path.add(node.getTitle() != null ? node.getTitle() : ""); - if (normalizeForMerge(node.getTitle()).equals(normalizeForMerge(targetTitle))) return true; - if (node.getChildren() != null) { - for (MindMapNode child : node.getChildren()) { - if (findPathRecursive(child, targetTitle, path)) return true; - } - } - path.remove(path.size() - 1); - return false; - } - - /** bigram Jaccard 相似度 */ - public static double similarityScore(String a, String b) { - if (a == null || b == null) return 0; - String na = normalizeForMerge(a); - String nb = normalizeForMerge(b); - if (na.isEmpty() || nb.isEmpty()) return 0; - if (na.equals(nb)) return 1.0; - // 子串匹配 - if (na.contains(nb) || nb.contains(na)) return 0.9; - Set bigramsA = bigrams(na); - Set bigramsB = bigrams(nb); - if (bigramsA.isEmpty() && bigramsB.isEmpty()) return 0; - Set union = new HashSet<>(bigramsA); - union.addAll(bigramsB); - Set intersect = new HashSet<>(bigramsA); - intersect.retainAll(bigramsB); - return (double) intersect.size() / union.size(); - } - - private static Set bigrams(String s) { - Set set = new LinkedHashSet<>(); - for (int i = 0; i < s.length() - 1; i++) { - set.add(s.substring(i, i + 2)); - } - return set; - } - - /** - * 合并新旧树:保留旧树中已有节点(用户编辑),追加新树中的新节点。 - * 按标准化标题匹配同级节点,旧树匹配到的节点优先保留。 - * - * @param oldRoot 旧树根(用户可能编辑过) - * @param newRoot 新树根(AI/BUILTIN 最新生成) - * @return 合并后的树 - */ - public static MindMapNode mergeTrees(MindMapNode oldRoot, MindMapNode newRoot) { - if (oldRoot == null) return newRoot; - if (newRoot == null) return oldRoot; - MindMapNode result = copyNodeShallow(oldRoot); - result.setChildren(mergeChildren(oldRoot.getChildren(), newRoot.getChildren())); - return result; - } - - /** 递归合并子节点列表 */ - private static List mergeChildren(List oldChildren, List newChildren) { - Map oldByNormalized = new LinkedHashMap<>(); - if (oldChildren != null) { - for (MindMapNode child : oldChildren) { - oldByNormalized.put(normalizeForMerge(child.getTitle()), child); - } - } - - List merged = new ArrayList<>(); - Set usedKeys = new HashSet<>(); - - if (newChildren != null) { - for (MindMapNode newNode : newChildren) { - String key = normalizeForMerge(newNode.getTitle()); - MindMapNode oldNode = oldByNormalized.get(key); - if (oldNode != null) { - // 旧节点存在:保留旧节点标题,递归合并子节点 - MindMapNode kept = copyNodeShallow(oldNode); - kept.setChildren(mergeChildren(oldNode.getChildren(), newNode.getChildren())); - merged.add(kept); - usedKeys.add(key); - } else { - // 新节点:直接添加 - merged.add(newNode); - } - } - } - - // 添加旧树中有但新树中没有的节点(用户添加的额外节点) - if (oldChildren != null) { - for (MindMapNode oldNode : oldChildren) { - if (!usedKeys.contains(normalizeForMerge(oldNode.getTitle()))) { - merged.add(oldNode); - } - } - } - - return merged; - } - - private static String normalizeForMerge(String s) { - if (s == null) return ""; - return s.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", "") - .toLowerCase(Locale.ROOT) - .trim(); - } - /** 序列化整棵树为 JSON */ public static String toJson(MindMapNode root, ObjectMapper mapper) { try { diff --git a/src/main/java/com/guo/learningprogresstracker/utils/ReviewDurationTool.java b/src/main/java/com/guo/learningprogresstracker/utils/ReviewDurationTool.java index 45c732f..ec00785 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/ReviewDurationTool.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/ReviewDurationTool.java @@ -14,8 +14,7 @@ public final class ReviewDurationTool { /** 空闲截断窗口:超过该时长无交互,之后的时间不计入本次复习耗时 */ public static final long IDLE_WINDOW_SECONDS = 5 * 60L; - private ReviewDurationTool() { - } + private ReviewDurationTool() {} /** * 结算一次复习行为的净耗时(秒)。 @@ -26,8 +25,8 @@ public final class ReviewDurationTool { * @param now 服务端当前时刻 * @return 净耗时秒数,恒 >= 0,且不超过「开始时刻到 now」的墙钟跨度 */ - public static int resolveSeconds(LocalDateTime startedAt, LocalDateTime lastInteractionAt, - Integer reportedSeconds, LocalDateTime now) { + public static int resolveSeconds( + LocalDateTime startedAt, LocalDateTime lastInteractionAt, Integer reportedSeconds, LocalDateTime now) { if (startedAt == null || now == null) { return 0; } @@ -41,7 +40,9 @@ public final class ReviewDurationTool { long idleSeconds = Duration.between(lastInteractionAt, now).getSeconds(); if (idleSeconds > IDLE_WINDOW_SECONDS) { // 挂机超过窗口:耗时截断到上一次交互时间 - maxSeconds = Math.min(maxSeconds, Duration.between(startedAt, lastInteractionAt).getSeconds()); + maxSeconds = Math.min( + maxSeconds, + Duration.between(startedAt, lastInteractionAt).getSeconds()); } } diff --git a/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java b/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java index 14ab8e1..7b4cce9 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/TagScopeTool.java @@ -3,7 +3,6 @@ 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; @@ -29,13 +28,13 @@ public final class TagScopeTool { /** 存储用分隔符:标签名由用户输入,用不可能出现在标签里的控制字符拼接才不会有歧义 */ private static final String TAG_SEPARATOR = "\u001F"; + private static final String MODE_SEPARATOR = "\u001E"; /** 标签集合列是 JSON 数组,只承载字符串,不涉及时间等需要配置的类型 */ private static final ObjectMapper MAPPER = new ObjectMapper(); - private TagScopeTool() { - } + private TagScopeTool() {} /** 标签归一化:去首尾空白 + 小写 */ public static String normalize(String tagName) { @@ -80,7 +79,8 @@ public final class TagScopeTool { */ public static String scopeKey(Collection tagNames, TagCombineModeEnum mode) { String canonical = String.join(TAG_SEPARATOR, normalizedTags(tagNames)) - + MODE_SEPARATOR + (mode == null ? TagCombineModeEnum.defaultMode() : mode).name(); + + MODE_SEPARATOR + + (mode == null ? TagCombineModeEnum.defaultMode() : mode).name(); return sha256Hex(canonical); } @@ -100,8 +100,7 @@ public final class TagScopeTool { return List.of(); } try { - List tags = MAPPER.readValue(storedTags, new TypeReference<>() { - }); + List tags = MAPPER.readValue(storedTags, new TypeReference<>() {}); return tags == null ? List.of() : tags; } catch (Exception e) { return List.of(); diff --git a/src/main/java/com/guo/learningprogresstracker/utils/TitleFetcher.java b/src/main/java/com/guo/learningprogresstracker/utils/TitleFetcher.java index 4700ad5..648be56 100644 --- a/src/main/java/com/guo/learningprogresstracker/utils/TitleFetcher.java +++ b/src/main/java/com/guo/learningprogresstracker/utils/TitleFetcher.java @@ -1,11 +1,5 @@ package com.guo.learningprogresstracker.utils; -import lombok.extern.slf4j.Slf4j; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -13,20 +7,32 @@ import java.net.URI; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.cert.X509Certificate; -import java.util.*; -import java.util.concurrent.*; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import lombok.extern.slf4j.Slf4j; @Slf4j public class TitleFetcher { - private static final Pattern TITLE_PATTERN = Pattern.compile( - "]*>([^<]+)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); - private static final Pattern CHARSET_PATTERN = Pattern.compile( - "charset=([\\w\\-]+)", Pattern.CASE_INSENSITIVE); + private TitleFetcher() {} + + private static final Pattern TITLE_PATTERN = + Pattern.compile("]*>([^<]+)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); + private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=([\\w\\-]+)", Pattern.CASE_INSENSITIVE); private static final int MAX_REDIRECTS = 5; private static final int TIMEOUT_MS = 8_000; @@ -34,12 +40,16 @@ public class TitleFetcher { static { try { - TrustManager[] trustAll = new TrustManager[]{ - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } - public void checkClientTrusted(X509Certificate[] c, String a) {} - public void checkServerTrusted(X509Certificate[] c, String a) {} + TrustManager[] trustAll = new TrustManager[] { + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; } + + public void checkClientTrusted(X509Certificate[] c, String a) {} + + public void checkServerTrusted(X509Certificate[] c, String a) {} + } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAll, new java.security.SecureRandom()); @@ -52,14 +62,20 @@ public class TitleFetcher { } public static String fetchTitle(String url) { - if (url == null || url.isBlank()) return null; + if (url == null || url.isBlank()) { + return null; + } String lower = url.toLowerCase(); - if (!lower.startsWith("http://") && !lower.startsWith("https://")) return null; + if (!lower.startsWith("http://") && !lower.startsWith("https://")) { + return null; + } String currentUrl = url; for (int hop = 0; hop <= MAX_REDIRECTS; hop++) { String title = doFetch(currentUrl); - if (title != null) return title; + if (title != null) { + return title; + } // 检查是否需要跟随重定向 String redirect = getRedirect(currentUrl); @@ -84,25 +100,30 @@ public class TitleFetcher { conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(false); // 手动处理重定向 conn.setRequestProperty("Connection", "close"); - conn.setRequestProperty("User-Agent", - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + - "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"); - conn.setRequestProperty("Accept", - "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + conn.setRequestProperty( + "User-Agent", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"); + conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8"); int status = conn.getResponseCode(); if (status >= 200 && status < 400) { String contentType = conn.getContentType(); - if (contentType != null && !contentType.toLowerCase().contains("text/html") + if (contentType != null + && !contentType.toLowerCase().contains("text/html") && !contentType.toLowerCase().contains("application/xhtml")) { - if (!contentType.toLowerCase().contains("text/")) return null; + if (!contentType.toLowerCase().contains("text/")) { + return null; + } } Charset charset = detectCharset(contentType); String body = readBody(conn, charset); - if (body == null) return null; + if (body == null) { + return null; + } Matcher matcher = TITLE_PATTERN.matcher(body); if (matcher.find()) { @@ -113,7 +134,8 @@ public class TitleFetcher { .replace(""", "\"") .replace("'", "'") .replace(" ", " ") - .replaceAll("\\s+", " ").trim(); + .replaceAll("\\s+", " ") + .trim(); return title.isEmpty() ? null : title; } } @@ -122,7 +144,9 @@ public class TitleFetcher { log.debug("获取页面标题失败: url={}, error={}", url, e.getMessage()); return null; } finally { - if (conn != null) conn.disconnect(); + if (conn != null) { + conn.disconnect(); + } } } @@ -135,13 +159,12 @@ public class TitleFetcher { conn.setReadTimeout(TIMEOUT_MS); conn.setRequestMethod("HEAD"); conn.setInstanceFollowRedirects(false); - conn.setRequestProperty("User-Agent", - "Mozilla/5.0 (compatible; LPT/1.0)"); + conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; LPT/1.0)"); int status = conn.getResponseCode(); - if (status == HttpURLConnection.HTTP_MOVED_PERM // 301 - || status == HttpURLConnection.HTTP_MOVED_TEMP // 302 - || status == HttpURLConnection.HTTP_SEE_OTHER // 303 + if (status == HttpURLConnection.HTTP_MOVED_PERM // 301 + || status == HttpURLConnection.HTTP_MOVED_TEMP // 302 + || status == HttpURLConnection.HTTP_SEE_OTHER // 303 || status == 307 || status == 308) { String location = conn.getHeaderField("Location"); @@ -162,7 +185,9 @@ public class TitleFetcher { } catch (Exception e) { return null; } finally { - if (conn != null) conn.disconnect(); + if (conn != null) { + conn.disconnect(); + } } } @@ -171,7 +196,9 @@ public class TitleFetcher { * 并行抓取标题,整体超时 15 秒。 */ public static String embedTitles(String text) { - if (text == null || text.isBlank()) return text; + if (text == null || text.isBlank()) { + return text; + } // 1) 保护已有 [text](url) List protectedLinks = new ArrayList<>(); @@ -186,12 +213,15 @@ public class TitleFetcher { // 2) 提取裸 URL 并去重 Set bareUrls = new LinkedHashSet<>(); - Matcher um = Pattern.compile("https?://[^\\s)\u3001\uFF09\u300D\u300B<>]+").matcher(work); + Matcher um = + Pattern.compile("https?://[^\\s)\u3001\uFF09\u300D\u300B<>]+").matcher(work); while (um.find()) { String url = um.group().replaceAll("[.。,,;;!!??)】」』\\]]+$", ""); bareUrls.add(url); } - if (bareUrls.isEmpty()) return text; + if (bareUrls.isEmpty()) { + return text; + } // 3) 并行抓取标题 Map titleMap = new ConcurrentHashMap<>(); @@ -202,7 +232,9 @@ public class TitleFetcher { final String u = url; futures[fi++] = CompletableFuture.runAsync(() -> { String title = fetchTitle(u); - if (title != null) titleMap.put(u, title); + if (title != null) { + titleMap.put(u, title); + } }); } try { @@ -231,7 +263,10 @@ public class TitleFetcher { if (contentType != null) { Matcher m = CHARSET_PATTERN.matcher(contentType); if (m.find()) { - try { return Charset.forName(m.group(1)); } catch (Exception ignored) {} + try { + return Charset.forName(m.group(1)); + } catch (Exception ignored) { + } } } return StandardCharsets.UTF_8; @@ -244,7 +279,9 @@ public class TitleFetcher { } catch (IOException e) { is = conn.getErrorStream(); } - if (is == null) return null; + if (is == null) { + return null; + } String encoding = conn.getContentEncoding(); try { @@ -254,7 +291,10 @@ public class TitleFetcher { is = new InflaterInputStream(is); } } catch (IOException ignored) { - try { is.close(); } catch (Exception ignored2) {} + try { + is.close(); + } catch (Exception ignored2) { + } is = conn.getInputStream(); } @@ -266,7 +306,10 @@ public class TitleFetcher { total += n; } } finally { - try { is.close(); } catch (Exception ignored) {} + try { + is.close(); + } catch (Exception ignored) { + } } return new String(buf, 0, total, charset); } diff --git a/src/main/java/db/migration/V20261115_2__backfill_recall_scope_key.java b/src/main/java/db/migration/V20261115_2__backfill_recall_scope_key.java new file mode 100644 index 0000000..d66deaa --- /dev/null +++ b/src/main/java/db/migration/V20261115_2__backfill_recall_scope_key.java @@ -0,0 +1,68 @@ +package db.migration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import org.flywaydb.core.api.migration.BaseJavaMigration; +import org.flywaydb.core.api.migration.Context; + +/** Copy frozen scope keys without recomputing historical scopes or changing their documents. */ +public class V20261115_2__backfill_recall_scope_key extends BaseJavaMigration { + private static final ObjectMapper JSON = new ObjectMapper(); + + @Override + public void migrate(Context context) throws Exception { + // One document at a time keeps memory bounded even for large private recall snapshots. + try (PreparedStatement select = context.getConnection() + .prepareStatement( + "SELECT id, scope_type, document_json, deleted FROM review_recalls WHERE id > ? ORDER" + + " BY id LIMIT 1"); + PreparedStatement update = context.getConnection() + .prepareStatement("UPDATE review_recalls SET scope_key = ? WHERE id = ?")) { + long after = 0; + while (true) { + select.setLong(1, after); + String type; + String document; + int deleted; + try (ResultSet rows = select.executeQuery()) { + if (!rows.next()) { + break; + } + after = rows.getLong("id"); + type = rows.getString("scope_type"); + document = rows.getString("document_json"); + deleted = rows.getInt("deleted"); + } + if (deleted != 0 && document == null) { + continue; + } + String key = scopeKey(after, type, document); + update.setString(1, key); + update.setLong(2, after); + update.executeUpdate(); + } + } + } + + private static String scopeKey(long id, String type, String document) throws SQLException { + try { + JsonNode scope = JSON.readTree(document).path("detail").path("scope"); + JsonNode key = scope.path("scopeKey"); + if (!type.equals(scope.path("type").asText()) + || !key.isTextual() + || key.asText().isBlank() + || key.asText().length() > 64 + || (!"TAG".equals(type) && !"TASK".equals(type)) + || ("TAG".equals(type) && !key.asText().matches("[0-9a-f]{64}"))) { + throw new IllegalArgumentException(); + } + return key.asText(); + } catch (Exception ignored) { + // Do not attach the JSON exception: it may contain the private source document. + throw new SQLException("Recall scope key backfill rejected record id=" + id); + } + } +} diff --git a/src/main/java/db/migration/V20261115_3__validate_marker_value_length.java b/src/main/java/db/migration/V20261115_3__validate_marker_value_length.java new file mode 100644 index 0000000..515327f --- /dev/null +++ b/src/main/java/db/migration/V20261115_3__validate_marker_value_length.java @@ -0,0 +1,17 @@ +package db.migration; + +import org.flywaydb.core.api.migration.BaseJavaMigration; +import org.flywaydb.core.api.migration.Context; + +/** Validate before the following non-transactional MySQL DDL; never truncate historical values. */ +public class V20261115_3__validate_marker_value_length extends BaseJavaMigration { + @Override + public void migrate(Context context) throws Exception { + try (var statement = context.getConnection().createStatement(); + var rows = statement.executeQuery("SELECT id FROM markers WHERE CHAR_LENGTH(marker_value) > 128")) { + if (rows.next()) { + throw new IllegalStateException("Marker value exceeds 128 characters; record id=" + rows.getInt(1)); + } + } + } +} diff --git a/src/main/java/db/migration/V20261115_5__backfill_fragment_owner_tags.java b/src/main/java/db/migration/V20261115_5__backfill_fragment_owner_tags.java new file mode 100644 index 0000000..c1ab800 --- /dev/null +++ b/src/main/java/db/migration/V20261115_5__backfill_fragment_owner_tags.java @@ -0,0 +1,90 @@ +package db.migration; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import org.flywaydb.core.api.migration.BaseJavaMigration; +import org.flywaydb.core.api.migration.Context; + +/** Backfill current ownership only. Tombstones are user intent, not missing data. */ +public class V20261115_5__backfill_fragment_owner_tags extends BaseJavaMigration { + private record Owner(int fragmentId, String user, String name) {} + + @Override + public void migrate(Context context) throws Exception { + Connection connection = context.getConnection(); + // Close the source cursor before writes (also works with streaming JDBC drivers). + List owners = new ArrayList<>(); + try (var query = connection.createStatement(); + var rows = query.executeQuery(""" + SELECT f.id, f.created_by, t.task_name + FROM study_report_fragments f JOIN tasks t + ON t.task_num = f.owner_task_num AND t.created_by = f.created_by + WHERE f.deleted = 0 AND t.deleted = 0 AND f.created_by IS NOT NULL + ORDER BY f.id + """)) { + while (rows.next()) { + owners.add(new Owner(rows.getInt(1), rows.getString(2), rows.getString(3))); + } + } + try (var marker = connection.prepareStatement(""" + SELECT deleted FROM markers WHERE created_by = ? AND object_type = 'FRAGMENT' + AND object_num = ? AND kind = 'USER' AND LOWER(TRIM(marker_name)) = ? + """); + var dictionary = connection.prepareStatement( + "SELECT 1 FROM user_tags WHERE created_by = ? AND normalized_name = ?"); + var insertTag = connection.prepareStatement(""" + INSERT INTO user_tags (tag_name, normalized_name, created_by, created_time, deleted) + VALUES (?, ?, ?, CURRENT_TIMESTAMP, 0) + """); + var insertMarker = connection.prepareStatement(""" + INSERT INTO markers (object_type, object_num, kind, marker_name, marker_value, + created_by, created_time, deleted) + VALUES ('FRAGMENT', ?, 'USER', ?, NULL, ?, CURRENT_TIMESTAMP, 0) + """)) { + for (Owner owner : owners) { + if (owner.name() == null || owner.name().trim().isEmpty()) { + continue; + } + String display = owner.name().trim(); + String normalized = display.toLowerCase(Locale.ROOT); + marker.setString(1, owner.user()); + marker.setString(2, Integer.toString(owner.fragmentId())); + marker.setString(3, normalized); + boolean present = false; + boolean removed = false; + try (var rows = marker.executeQuery()) { + while (rows.next()) { + present = true; + removed |= rows.getInt(1) != 0; + } + } + // A deleted object tag must not be recreated, even if the dictionary still contains its name. + if (removed) { + continue; + } + dictionary.setString(1, owner.user()); + dictionary.setString(2, normalized); + boolean dictionaryPresent; + try (var rows = dictionary.executeQuery()) { + // Removing a dictionary suggestion does not remove or forbid tags on content. + // Preserve its tombstone while still backfilling the fragment's actual tag. + dictionaryPresent = rows.next(); + } + if (!dictionaryPresent) { + insertTag.setString(1, display); + insertTag.setString(2, normalized); + insertTag.setString(3, owner.user()); + insertTag.executeUpdate(); + } + if (!present) { + insertMarker.setString(1, Integer.toString(owner.fragmentId())); + insertMarker.setString(2, display); + insertMarker.setString(3, owner.user()); + insertMarker.executeUpdate(); + } + } + } + } +} diff --git a/src/main/java/db/migration/V20261118_2__strip_recall_exposures.java b/src/main/java/db/migration/V20261118_2__strip_recall_exposures.java new file mode 100644 index 0000000..5bc1233 --- /dev/null +++ b/src/main/java/db/migration/V20261118_2__strip_recall_exposures.java @@ -0,0 +1,82 @@ +package db.migration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import org.flywaydb.core.api.migration.BaseJavaMigration; +import org.flywaydb.core.api.migration.Context; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 内容暴露记录({@code detail.exposures})已从回忆文档中下线,这里把历史文档里的这个节点删掉。 + * + *

读兼容已经由 {@code RecallJson.readStored} 关闭未知字段报错兜住,所以这一步只是清存量: + * 除 {@code detail.exposures} 外的全部字段原样保留。

+ * + *

坏数据策略:解析不了、或者顶层不是 JSON 对象的文档原样跳过并计数,不抛异常也不删行。 + * 理由有两条:一是升级不能被少数坏文档卡死(抛 {@code SQLException} 的先例适合「必须全量校验」的 + * 回填,这里没有这个必要);二是运行期已有唯一的删除路径({@code ReviewRecallStore.deleteUnreadable}, + * 用户打开时删,或隐私清理扫到时删),迁移里再造一条删除路径会变成两处口径。跳过不会让字段复活, + * 因为新代码根本不读 {@code exposures}。日志只打记录 id 与计数,不带文档正文。

+ */ +public class V20261118_2__strip_recall_exposures extends BaseJavaMigration { + private static final Logger LOG = LoggerFactory.getLogger(V20261118_2__strip_recall_exposures.class); + private static final ObjectMapper JSON = new ObjectMapper(); + + @Override + public void migrate(Context context) throws Exception { + // One document at a time keeps memory bounded: these documents embed private learning text. + int stripped = 0; + int skipped = 0; + try (PreparedStatement select = context.getConnection() + .prepareStatement( + "SELECT id, document_json FROM review_recalls WHERE id > ? ORDER BY id LIMIT 1"); + PreparedStatement update = context.getConnection() + .prepareStatement("UPDATE review_recalls SET document_json = ? WHERE id = ?")) { + long after = 0; + while (true) { + select.setLong(1, after); + String document; + try (ResultSet rows = select.executeQuery()) { + if (!rows.next()) { + break; + } + after = rows.getLong("id"); + document = rows.getString("document_json"); + } + if (document == null) { + continue; + } + JsonNode root; + try { + root = JSON.readTree(document); + } catch (Exception unreadable) { + // Do not attach the parsing exception: it may contain the private source document. + LOG.warn("[迁移] 回忆文档不可解析,原样跳过: id={}", after); + skipped++; + continue; + } + if (!(root instanceof ObjectNode documentNode) + || !(documentNode.get("detail") instanceof ObjectNode detail)) { + LOG.warn("[迁移] 回忆文档结构不可识别,原样跳过: id={}", after); + skipped++; + continue; + } + if (!detail.has("exposures")) { + continue; + } + detail.remove("exposures"); + update.setString(1, JSON.writeValueAsString(documentNode)); + update.setLong(2, after); + update.executeUpdate(); + stripped++; + } + } + if (stripped > 0 || skipped > 0) { + LOG.info("[迁移] 回忆文档内容暴露记录清理完成: stripped={}, skipped={}", stripped, skipped); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 9e097c0..426cc02 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -63,6 +63,8 @@ lpt: ai-service: url: http://localhost:5199 timeout-seconds: 600 + # 提示在 lpt-ai 侧 55s 截止;BE 留 15s 余量,避免前端等 10 分钟 + hint-timeout-seconds: 70 # 安全-03:与 lpt-ai 共用的入站令牌;留空表示 lpt-ai 未启用令牌校验。 # 部署清单用 LPT_AI-SERVICE_TOKEN(secret lpt-secrets/lpt-ai-token,optional)注入 token: "" diff --git a/src/main/resources/db/migration/V20261114_1__add_free_recall_drafts.sql b/src/main/resources/db/migration/V20261114_1__add_free_recall_drafts.sql new file mode 100644 index 0000000..306fab2 --- /dev/null +++ b/src/main/resources/db/migration/V20261114_1__add_free_recall_drafts.sql @@ -0,0 +1,61 @@ +-- One row per owner serializes new recall mutation, creation idempotency and privacy/completion races. +CREATE TABLE review_recall_owner_locks ( + owner_id VARCHAR(64) NOT NULL PRIMARY KEY +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE review_recalls ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + recall_num VARCHAR(64) NOT NULL, + scope_type VARCHAR(8) NOT NULL, + task_num VARCHAR(64) NULL, + status VARCHAR(8) NOT NULL, + revision INT NOT NULL, + active_duration_ms BIGINT NOT NULL DEFAULT 0, + document_json LONGTEXT NULL, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_num (recall_num), + KEY idx_recall_user_status (created_by, deleted, status, last_modified_time, id), + KEY idx_recall_task (created_by, task_num, deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- Receipts hold digests and object identifiers only, never cached sensitive responses. +CREATE TABLE review_recall_receipts ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + receipt_key CHAR(64) NOT NULL, + payload_hash CHAR(64) NOT NULL, + recall_num VARCHAR(64) NOT NULL, + task_num VARCHAR(64) NULL, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_receipt (receipt_key) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE review_recall_requests ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + recall_num VARCHAR(64) NOT NULL, + task_num VARCHAR(64) NOT NULL, + semantic_key CHAR(64) NOT NULL, + params_json LONGTEXT NULL, + remote_task_id VARCHAR(64) NULL, + redacted INT NOT NULL DEFAULT 0, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_request_task (task_num), + KEY idx_recall_request_semantic (created_by, semantic_key), + KEY idx_recall_request_recall (created_by, recall_num) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +ALTER TABLE ai_tasks ADD COLUMN error_code VARCHAR(40) NULL; diff --git a/src/main/resources/db/migration/V20261115_1__add_recall_scope_key.sql b/src/main/resources/db/migration/V20261115_1__add_recall_scope_key.sql new file mode 100644 index 0000000..1451a47 --- /dev/null +++ b/src/main/resources/db/migration/V20261115_1__add_recall_scope_key.sql @@ -0,0 +1,2 @@ +ALTER TABLE review_recalls ADD COLUMN scope_key VARCHAR(64) NULL; +CREATE INDEX idx_recall_user_scope ON review_recalls (created_by, scope_type, scope_key, deleted, last_modified_time, id); diff --git a/src/main/resources/db/migration/V20261115_4__expand_user_tag_names.sql b/src/main/resources/db/migration/V20261115_4__expand_user_tag_names.sql new file mode 100644 index 0000000..d101f43 --- /dev/null +++ b/src/main/resources/db/migration/V20261115_4__expand_user_tag_names.sql @@ -0,0 +1,15 @@ +-- V20261115_3 checks all rows (including deleted ones) before any narrowing DDL. +-- System values are a fixed vocabulary; user tags have NULL values. +ALTER TABLE markers MODIFY COLUMN marker_value VARCHAR(128) NULL COMMENT '标记值:系统标记成对使用(如 来源=学习引导);用户标签留空'; +-- Drop the oversized lookup before expanding marker_name. Object queries retain idx_markers_object. +DROP INDEX idx_markers_lookup ON markers; +ALTER TABLE markers MODIFY COLUMN marker_name VARCHAR(255) NOT NULL COMMENT '标记名:系统标记来自固定词表;用户标签自由输入'; +CREATE INDEX idx_markers_lookup ON markers (created_by, marker_name, object_type); +ALTER TABLE user_tags MODIFY COLUMN tag_name VARCHAR(255) NOT NULL COMMENT '标签名:展示保留用户输入的原样'; +ALTER TABLE user_tags MODIFY COLUMN normalized_name VARCHAR(255) NOT NULL COMMENT '归一化标签名:去首尾空白 + 小写,用于去重与关键字过滤'; +-- utf8mb4 final keys: unique markers=(20+255+20+255+128)*4=2712; +-- lookup=(255+255+20)*4=2120; dictionary=(255+255)*4=2040 bytes. +-- A range contains up to ten 255-character labels; stored JSON also includes escaping. +ALTER TABLE review_tag_mind_maps MODIFY COLUMN tag_names TEXT NOT NULL COMMENT '范围的标签集合(JSON 数组,展示保留输入原样,按归一化名排序)'; +ALTER TABLE review_tag_mind_maps MODIFY COLUMN title TEXT NOT NULL COMMENT '标签导图标题(根节点标题)'; +ALTER TABLE review_recall_records MODIFY COLUMN scope_tags TEXT NULL COMMENT '范围的标签集合(JSON 数组,按归一化名排序);任务范围为空'; diff --git a/src/main/resources/db/migration/V20261116_1__replace_recall_storage.sql b/src/main/resources/db/migration/V20261116_1__replace_recall_storage.sql new file mode 100644 index 0000000..dc56141 --- /dev/null +++ b/src/main/resources/db/migration/V20261116_1__replace_recall_storage.sql @@ -0,0 +1,64 @@ +-- Free recall keeps one current expression and one current reference set; old histories are intentionally discarded. +DELETE FROM ai_tasks WHERE ai_type IN ('RECALL_COMPARE', 'TAG_RECALL_COMPARE', 'RECALL_HINT', 'RECALL_CHECK'); + +DROP TABLE IF EXISTS review_recall_requests; +DROP TABLE IF EXISTS review_recall_receipts; +DROP TABLE IF EXISTS review_recalls; +DROP TABLE IF EXISTS review_recall_owner_locks; +DROP TABLE IF EXISTS review_recall_records; + +CREATE TABLE review_recall_owner_locks ( + owner_id VARCHAR(64) NOT NULL PRIMARY KEY +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE review_recalls ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + recall_num VARCHAR(64) NOT NULL, + scope_type VARCHAR(8) NOT NULL, + task_num VARCHAR(64) NULL, + scope_key VARCHAR(64) NOT NULL, + status VARCHAR(8) NOT NULL, + active_duration_ms BIGINT NOT NULL DEFAULT 0, + document_json LONGTEXT NULL, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_num (recall_num), + KEY idx_recall_user_scope_status (created_by, scope_type, scope_key, status, deleted, last_modified_time, id), + KEY idx_recall_user_task (created_by, task_num, deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE review_recall_receipts ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + receipt_key CHAR(64) NOT NULL, + payload_hash CHAR(64) NOT NULL, + recall_num VARCHAR(64) NOT NULL, + task_num VARCHAR(64) NULL, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_receipt (receipt_key) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE review_recall_requests ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + recall_num VARCHAR(64) NOT NULL, + task_num VARCHAR(64) NOT NULL, + params_json LONGTEXT NULL, + remote_task_id VARCHAR(64) NULL, + redacted TINYINT(1) NOT NULL DEFAULT 0, + created_by VARCHAR(64) NOT NULL, + created_time DATETIME NOT NULL, + last_modified_time DATETIME NOT NULL, + last_modified_by VARCHAR(64) NULL, + device_info VARCHAR(64) NULL, + deleted INT NOT NULL DEFAULT 0, + UNIQUE KEY uk_recall_request_task (task_num), + KEY idx_recall_request_owner_recall (created_by, recall_num, deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/src/main/resources/db/migration/V20261118_1__clear_incompatible_recall_data.sql b/src/main/resources/db/migration/V20261118_1__clear_incompatible_recall_data.sql new file mode 100644 index 0000000..1340859 --- /dev/null +++ b/src/main/resources/db/migration/V20261118_1__clear_incompatible_recall_data.sql @@ -0,0 +1,6 @@ +-- Expression nodes gained style and hints gained anchorNodeId; previously written documents are unreadable. +-- Recall data is intentionally breaking: clear the current recalls and their recall AI tasks instead of adapting old JSON. +DELETE FROM review_recall_requests; +DELETE FROM review_recall_receipts; +DELETE FROM review_recalls; +DELETE FROM ai_tasks WHERE ai_type IN ('RECALL_HINT', 'RECALL_CHECK'); diff --git a/src/main/resources/mapper/ReviewRecallRecordMapper.xml b/src/main/resources/mapper/ReviewRecallRecordMapper.xml deleted file mode 100644 index a70e851..0000000 --- a/src/main/resources/mapper/ReviewRecallRecordMapper.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test/java/com/guo/learningprogresstracker/common/GlobalExceptionHandlerTest.java b/src/test/java/com/guo/learningprogresstracker/common/GlobalExceptionHandlerTest.java index 08f6714..36851ef 100644 --- a/src/test/java/com/guo/learningprogresstracker/common/GlobalExceptionHandlerTest.java +++ b/src/test/java/com/guo/learningprogresstracker/common/GlobalExceptionHandlerTest.java @@ -52,7 +52,7 @@ class GlobalExceptionHandlerTest { @Test void appException_returnsServerErrorWithMessage() { - CommonResult result = handler.AppException(new AppException("业务异常")); + CommonResult result = handler.handleAppException(new AppException("业务异常")); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), result.getCode()); assertEquals("业务异常", result.getMessage()); @@ -64,7 +64,7 @@ class GlobalExceptionHandlerTest { new MethodArgumentNotValidException(null, new BeanPropertyBindingResult(new Object(), "o")); ex.getBindingResult().addError(new FieldError("o", "f", "字段校验失败")); - CommonResult result = handler.MyMethodArgumentNotValidException(ex); + CommonResult result = handler.handleArgumentNotValid(ex); assertEquals(HttpStatus.BAD_REQUEST.value(), result.getCode()); assertEquals("字段校验失败", result.getMessage()); @@ -86,10 +86,10 @@ class GlobalExceptionHandlerTest { } @Test - void fallbackException_returnsGenericBadRequest() { - CommonResult result = handler.Exception(new RuntimeException("意外错误")); + void fallbackException_returnsServerError() { + CommonResult result = handler.handleUnexpected(new RuntimeException("意外错误")); - assertEquals(HttpStatus.BAD_REQUEST.value(), result.getCode()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), result.getCode()); assertEquals("操作没有成功,请稍后再试", result.getMessage()); } } diff --git a/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerTest.java b/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerTest.java index 666595d..1d231e2 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerTest.java @@ -26,6 +26,7 @@ class LoginControllerTest { loginBody.setPassword("admin"); CommonResult login = loginController.login(loginBody); assertEquals("登录成功!", login.getMessage()); + assertEquals(cn.dev33.satoken.stp.StpUtil.getLoginIdAsString(), login.getData().getAccountId()); // 测试种子用户 admin 命中默认白名单 lpt.ai-usage.admin-usernames assertTrue(login.getData().isAiAdmin(), "admin 应被识别为用量面板管理员"); diff --git a/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerUnitTest.java index b015e34..282717b 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/LoginControllerUnitTest.java @@ -50,6 +50,7 @@ class LoginControllerUnitTest { assertEquals(200, result.getCode()); assertEquals("登录成功!", result.getMessage()); assertEquals("token-abc", result.getData().getToken()); + assertEquals("U-1", result.getData().getAccountId(), "缓存身份只能来自认证后的不透明用户id"); assertTrue(result.getData().isAiAdmin(), "白名单用户登录后应下发 aiAdmin=true"); verify(loginService).login("U-1"); } @@ -66,6 +67,7 @@ class LoginControllerUnitTest { CommonResult result = controller.login(body); assertEquals(200, result.getCode()); + assertEquals("U-1", result.getData().getAccountId()); assertFalse(result.getData().isAiAdmin(), "非白名单用户不该拿到用量面板入口"); } diff --git a/src/test/java/com/guo/learningprogresstracker/controller/ReportFragmentsControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/ReportFragmentsControllerUnitTest.java index a75fa21..10f5ce5 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/ReportFragmentsControllerUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/ReportFragmentsControllerUnitTest.java @@ -17,9 +17,11 @@ 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; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; /** - * reportFragmentsController 纯单元测试(类名小写开头,保持与生产代码一致): + * ReportFragmentsController 纯单元测试(类名小写开头,保持与生产代码一致): * 直接 new 控制器并 mock StudyReportFragmentsServiceImpl。 */ @ExtendWith(MockitoExtension.class) @@ -29,7 +31,7 @@ class ReportFragmentsControllerUnitTest { private StudyReportFragmentsServiceImpl studyReportFragmentsServiceImpl; @InjectMocks - private reportFragmentsController controller; + private ReportFragmentsController controller; @Test void createFragments_delegatesToService() throws Exception { @@ -59,9 +61,9 @@ class ReportFragmentsControllerUnitTest { List fragments = List.of(new StudyReportFragmentsEntity()); when(studyReportFragmentsServiceImpl.getFragmentsBySession("S-2")).thenReturn(fragments); - CommonResult> result = controller.getFragmentsBySession("S-2"); + CommonResult> result = controller.getFragmentsBySession("S-2"); assertEquals(200, result.getCode()); - assertSame(fragments, result.getData()); + assertNotNull(result.getData()); } } diff --git a/src/test/java/com/guo/learningprogresstracker/controller/ReviewControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/ReviewControllerUnitTest.java index 31ceeab..9b5bd47 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/ReviewControllerUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/ReviewControllerUnitTest.java @@ -6,7 +6,6 @@ import com.guo.learningprogresstracker.dto.ReviewSummary; import com.guo.learningprogresstracker.dto.ReviewTaskStats; import com.guo.learningprogresstracker.dto.request.UpdateStandardMindMapRequest; import com.guo.learningprogresstracker.entity.CommonResult; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; @@ -28,6 +27,11 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; +import com.guo.learningprogresstracker.dto.response.StudyReportResponse; +import com.guo.learningprogresstracker.dto.response.StandardMindMapResponse; +import com.guo.learningprogresstracker.dto.request.FindNodeRequest; /** * ReviewController 纯单元测试:直接 new 控制器并 mock 两个服务接口。 @@ -118,10 +122,10 @@ class ReviewControllerUnitTest { StudyReportsEntity report = new StudyReportsEntity(); when(reviewService.getReportDetail(11)).thenReturn(report); - CommonResult result = controller.getReportDetail(11); + CommonResult result = controller.getReportDetail(11); assertEquals(200, result.getCode()); - assertSame(report, result.getData()); + assertNotNull(result.getData()); } @Test @@ -129,10 +133,10 @@ class ReviewControllerUnitTest { StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity(); when(reviewService.getFragmentDetail(22)).thenReturn(fragment); - CommonResult result = controller.getFragmentDetail(22); + CommonResult result = controller.getFragmentDetail(22); assertEquals(200, result.getCode()); - assertSame(fragment, result.getData()); + assertNotNull(result.getData()); } @Test @@ -140,10 +144,10 @@ class ReviewControllerUnitTest { ReviewStandardMindMapEntity mindMap = new ReviewStandardMindMapEntity(); when(standardMindMapService.getExisting("T003")).thenReturn(mindMap); - CommonResult result = controller.getStandardMindMap("T003"); + CommonResult result = controller.getStandardMindMap("T003"); assertEquals(200, result.getCode()); - assertSame(mindMap, result.getData()); + assertNotNull(result.getData()); // AI-02:读取路径不再触发生成,也就不会因为一个 GET 就阻塞并按 AI 计费 verify(standardMindMapService).getExisting("T003"); verify(standardMindMapService, never()).regenerate(anyString()); @@ -153,7 +157,7 @@ class ReviewControllerUnitTest { void getStandardMindMap_absentMap_returnsNullData() throws Exception { when(standardMindMapService.getExisting("T013")).thenReturn(null); - CommonResult result = controller.getStandardMindMap("T013"); + CommonResult result = controller.getStandardMindMap("T013"); assertEquals(200, result.getCode()); assertNull(result.getData(), "没有导图时返回 null,由前端发起 MIND_MAP 任务"); @@ -166,10 +170,10 @@ class ReviewControllerUnitTest { ReviewStandardMindMapEntity mindMap = new ReviewStandardMindMapEntity(); when(standardMindMapService.updateByOutline("T006", "- 根节点\n- 子节点")).thenReturn(mindMap); - CommonResult result = controller.updateStandardMindMap("T006", request); + CommonResult result = controller.updateStandardMindMap("T006", request); assertEquals(200, result.getCode()); - assertSame(mindMap, result.getData()); + assertNotNull(result.getData()); } @Test @@ -188,7 +192,7 @@ class ReviewControllerUnitTest { Map matched = Map.of("id", "n2"); when(standardMindMapService.findNode("T009", "")).thenReturn(matched); - CommonResult> result = controller.findNode("T009", Map.of("other", "x")); + CommonResult> result = controller.findNode("T009", new FindNodeRequest()); assertEquals(200, result.getCode()); assertSame(matched, result.getData()); @@ -199,31 +203,12 @@ class ReviewControllerUnitTest { Map matched = Map.of("id", "n3"); when(standardMindMapService.findNode("T010", "租户隔离")).thenReturn(matched); - CommonResult> result = controller.findNode("T010", Map.of("content", "租户隔离")); + FindNodeRequest request = new FindNodeRequest(); + request.setContent("租户隔离"); + CommonResult> result = controller.findNode("T010", request); assertEquals(200, result.getCode()); assertSame(matched, result.getData()); } - @Test - void listRecallRecords_returnsRecords() throws Exception { - List records = List.of(new ReviewRecallRecordEntity()); - when(standardMindMapService.listRecallRecords("T011")).thenReturn(records); - - CommonResult> result = controller.listRecallRecords("T011"); - - assertEquals(200, result.getCode()); - assertSame(records, result.getData()); - } - - @Test - void getRecallRecord_returnsSingleRecord() throws Exception { - ReviewRecallRecordEntity record = new ReviewRecallRecordEntity(); - when(standardMindMapService.getRecallRecord(33)).thenReturn(record); - - CommonResult result = controller.getRecallRecord(33); - - assertEquals(200, result.getCode()); - assertSame(record, result.getData()); - } } diff --git a/src/test/java/com/guo/learningprogresstracker/controller/ReviewExportControllerIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/controller/ReviewExportControllerIntegrationTest.java new file mode 100644 index 0000000..4b42cc1 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/controller/ReviewExportControllerIntegrationTest.java @@ -0,0 +1,179 @@ +package com.guo.learningprogresstracker.controller; + +import cn.dev33.satoken.stp.StpUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.common.TenantContext; +import com.guo.learningprogresstracker.entity.*; +import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.service.GuidanceService; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; +import com.guo.learningprogresstracker.service.ai.RecallAiClient; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.time.LocalDateTime; +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** H2 + real tenant interceptor + HTTP consumers: ownership and recording context are separate axes. */ +@SpringBootTest +@AutoConfigureMockMvc +class ReviewExportControllerIntegrationTest { + @Autowired MockMvc mvc; + @Autowired ObjectMapper mapper; + @Autowired TasksMapper tasks; + @Autowired StudySessionsMapper sessions; + @Autowired StudyReportsMapper reports; + @Autowired StudyReportFragmentsMapper fragments; + @Autowired GuidanceService guidance; + @MockBean AiTaskRunner runner; + @MockBean RecallAiClient client; + + String token, taskNum, otherTaskNum, sessionNum, guidanceNum; + StudyReportsEntity report; + StudyReportFragmentsEntity harvest; + String longText = "完整的学习引导收获🙂\n".repeat(40) + "导出结尾必须保留"; + LocalDateTime oldTime = LocalDateTime.of(2026, 10, 1, 10, 0); + + @BeforeEach void setUp() throws Exception { + StpUtil.login("review-export-" + UUID.randomUUID()); + token = StpUtil.getTokenValue(); + taskNum = task("目标任务"); otherTaskNum = task("原会话任务"); + sessionNum = session(taskNum); + String otherSession = session(otherTaskNum); + report = new StudyReportsEntity(); report.setSessionNum(sessionNum); + report.setSessionSummary("原学习报告" + "长报告正文".repeat(60)); report.setCreatedTime(oldTime); reports.insert(report); + fragment(taskNum, "SESSION", sessionNum, "会话知识", oldTime); + fragment(taskNum, "SESSION", otherSession, "归入目标任务的旁支", oldTime); + fragment(otherTaskNum, "SESSION", sessionNum, "已归到其他任务", oldTime); + fragment(null, "REVIEW", "pending", "待归类", oldTime); + StudyReportFragmentsEntity deleted = fragment(taskNum, "REVIEW", "deleted", "已删秘密", oldTime); fragments.deleteById(deleted.getId()); + TenantContext.runAs("foreign-" + UUID.randomUUID(), null, + () -> fragment(taskNum, "REVIEW", "foreign", "其他用户秘密", oldTime)); + guidanceNum = guidance.start(taskNum, "概念").getGuidanceNum(); + harvest = guidance.confirmFragment(guidanceNum, longText, null); + } + + @Test void taskDetailAndPaginatedHistoryIncludeReviewAndKeepSummaryContract() throws Exception { + JsonNode history = data("/review/task/" + taskNum); + assertEquals(4, history.size()); + JsonNode item = find(history, harvest.getId()); + assertEquals(harvest.getId(), history.get(0).path("id").asInt()); + assertEquals("FRAGMENT", history.get(0).path("sourceType").asText()); + assertEquals("REVIEW", item.path("contextType").asText()); + assertEquals(guidanceNum, item.path("contextNum").asText()); + assertEquals(taskNum, item.path("taskNum").asText()); + assertEquals("目标任务", item.path("taskName").asText()); + assertTrue(item.path("contentTruncated").asBoolean()); + assertEquals(longText.length(), item.path("contentLength").asInt()); + assertEquals(longText, data("/review/fragment/" + harvest.getId()).path("content").asText()); + JsonNode paged = data("/study-sessions/tasks/" + taskNum + "/fragments?size=20"); + assertEquals(3, paged.path("total").asInt()); + assertEquals(longText, find(paged.path("records"), harvest.getId()).path("content").asText()); + assertEquals(3, data("/review/tasks/" + taskNum).path("fragmentCount").asInt()); + assertEquals(1, data("/review/tasks/" + taskNum).path("sessionCount").asInt()); + assertEquals(1, data("/study-sessions/tasks/" + taskNum + "/reports").path("total").asInt()); + } + + @Test void taskAndAllTimeExportsContainFullBodiesAndSameOwnershipCountsInBothFormats() throws Exception { + for (String path : List.of("/export/task/" + taskNum, "/export/range")) { + JsonNode document = mapper.readTree(data(path + "?format=json").path("content").asText()); + JsonNode section = section(document, taskNum); + assertEquals(3, section.path("fragments").size()); + assertEquals(3, section.path("stats").path("fragmentCount").asInt()); + assertEquals(1, section.path("reports").size()); + assertEquals(1, section.path("stats").path("reportCount").asInt()); + JsonNode entry = find(section.path("fragments"), harvest.getId()); + assertEquals(longText, entry.path("content").asText()); + assertEquals("REVIEW", entry.path("contextType").asText()); + assertEquals(guidanceNum, entry.path("contextNum").asText()); + assertTrue(entry.path("sessionNum").isNull()); + assertTrue(section.path("reports").get(0).path("content").asText().contains(report.getSessionSummary())); + String md = data(path + "?format=markdown").path("content").asText(); + assertTrue(md.contains(longText)); + assertTrue(md.contains("复习 / 学习引导 `" + guidanceNum + "`")); + assertFalse(md.contains("会话 `" + guidanceNum + "`")); + assertTrue(md.contains(report.getSessionSummary())); + assertFalse(md.contains("已删秘密")); assertFalse(md.contains("其他用户秘密")); + } + } + + @Test void dateRangeCountsDescribeOnlyExportedBodiesAndIncludeReviewWithoutASession() throws Exception { + String date = harvest.getCreatedTime().toLocalDate().toString(); + String path = "/export/range?startDate=" + date + "&endDate=" + date; + JsonNode document = mapper.readTree(data(path + "&format=json").path("content").asText()); + JsonNode section = section(document, taskNum); + assertEquals(1, section.path("fragments").size()); + assertEquals(1, section.path("stats").path("fragmentCount").asInt()); + assertEquals(0, section.path("reports").size()); + assertEquals(0, section.path("stats").path("reportCount").asInt()); + String md = data(path + "&format=markdown").path("content").asText(); + assertTrue(md.contains("知识碎片:1 条")); assertTrue(md.contains(longText)); assertFalse(md.contains("原学习报告")); + String reviewOnlyTask = task("只有复习收获"); + fragment(reviewOnlyTask, "REVIEW", "review-only", "独立收获", LocalDateTime.now()); + JsonNode reviewOnly = section(mapper.readTree(data("/export/task/" + reviewOnlyTask + "?format=json").path("content").asText()), reviewOnlyTask); + assertEquals(1, reviewOnly.path("fragments").size()); assertEquals(0, reviewOnly.path("reports").size()); + assertEquals(0, reviewOnly.path("stats").path("sessionCount").asInt()); + JsonNode history = data("/review/task/" + reviewOnlyTask); + assertEquals(1, history.size()); + assertEquals("REVIEW", history.get(0).path("contextType").asText()); + assertEquals(reviewOnlyTask, history.get(0).path("taskNum").asText()); + JsonNode page = data("/study-sessions/tasks/" + reviewOnlyTask + "/fragments?keyword=独立收获"); + assertEquals(1, page.path("total").asInt()); + assertEquals("REVIEW", page.path("records").get(0).path("contextType").asText()); + assertEquals(0, data("/study-sessions/tasks/" + reviewOnlyTask + "/reports").path("total").asInt()); + assertTrue(data("/export/task/" + reviewOnlyTask + "?format=markdown").path("content").asText().contains("独立收获")); + } + + @Test void reportAndSessionConsumersNeverAbsorbReviewEvenWithCollidingContextNumber() throws Exception { + fragment(taskNum, "REVIEW", sessionNum, "复习不是旧报告正文", LocalDateTime.now()); + String structured = data("/review/report/" + report.getId() + "/structured").toString(); + assertFalse(structured.contains("复习不是旧报告正文")); assertFalse(structured.contains("导出结尾必须保留")); + String sessionContent = data("/study-sessions/" + sessionNum + "/all-fragments").toString(); + assertFalse(sessionContent.contains("复习不是旧报告正文")); + assertEquals(report.getSessionSummary(), reports.selectById(report.getId()).getSessionSummary()); + assertEquals(2, sessions.selectCount(null)); + } + + @Test void anotherAccountCannotReadTaskHistoryOrExportItsContent() throws Exception { + StpUtil.login("other-export-" + UUID.randomUUID()); token = StpUtil.getTokenValue(); + assertEquals(0, data("/review/task/" + taskNum).size()); + assertEquals(0, data("/study-sessions/tasks/" + taskNum + "/fragments").path("total").asInt()); + JsonNode response = mapper.readTree(mvc.perform(get("/export/task/" + taskNum).header("satoken", token)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(java.nio.charset.StandardCharsets.UTF_8)); + assertNotEquals(200, response.path("code").asInt()); assertFalse(response.toString().contains(longText)); + assertFalse(data("/export/range?format=json").toString().contains("导出结尾必须保留")); + } + + JsonNode data(String path) throws Exception { + JsonNode response = mapper.readTree(mvc.perform(get(path).header("satoken", token)).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(java.nio.charset.StandardCharsets.UTF_8)); + assertEquals(200, response.path("code").asInt(), response.toString()); return response.path("data"); + } + JsonNode section(JsonNode document, String owner) { + for (JsonNode section : document.path("tasks")) if (owner.equals(section.path("taskNum").asText())) return section; + throw new AssertionError("Missing task section"); + } + JsonNode find(JsonNode entries, int id) { + for (JsonNode entry : entries) if (entry.path("id").asInt() == id && !"REPORT".equals(entry.path("sourceType").asText())) return entry; + throw new AssertionError("Missing fragment " + id); + } + String task(String name) { + TaskEntity task = new TaskEntity(); task.setTaskNum(UUID.randomUUID().toString()); task.setTaskName(name); tasks.insert(task); return task.getTaskNum(); + } + String session(String task) { + StudySessionsEntity session = StudySessionsEntity.initNewSession(); session.setTaskNum(task); sessions.insert(session); return session.getSessionNum(); + } + StudyReportFragmentsEntity fragment(String owner, String type, String context, String text, LocalDateTime time) { + StudyReportFragmentsEntity f = new StudyReportFragmentsEntity(); f.setOwnerTaskNum(owner); f.setContextType(type); f.setContextNum(context); + f.setContent(text); f.setCreatedTime(time); fragments.insert(f); return f; + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java new file mode 100644 index 0000000..afaf5de --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/controller/ReviewRecallControllerIntegrationTest.java @@ -0,0 +1,143 @@ +package com.guo.learningprogresstracker.controller; + +import cn.dev33.satoken.stp.StpUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; +import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.service.*; +import com.guo.learningprogresstracker.service.impl.*; +import com.guo.learningprogresstracker.config.AiTaskProperties; +import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent; +import org.junit.jupiter.api.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.http.MediaType; +import java.util.*; +import java.util.function.Function; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import com.guo.learningprogresstracker.service.ai.AiTaskHandlerRegistry; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; +import com.guo.learningprogresstracker.service.ai.RecallAiClient; +import com.guo.learningprogresstracker.service.ai.RecallAiFailure; + +@SpringBootTest +@AutoConfigureMockMvc +class ReviewRecallControllerIntegrationTest { + @Autowired MockMvc mvc; + @Autowired ObjectMapper mapper; + @Autowired StudyReportFragmentsMapper fragments; + @Autowired MarkerService markers; + @Autowired AiTaskService aiTasks; + @Autowired AiTaskMapper tasks; + @Autowired AiTaskHandlerRegistry registry; + @Autowired AiTaskProperties properties; + @MockBean AiTaskRunner runner; + @MockBean RecallAiClient client; + String token, tag; + @BeforeEach void setup() throws Exception { + StpUtil.login("recall-http-" + UUID.randomUUID()); token = StpUtil.getTokenValue(); tag = UUID.randomUUID().toString(); + var fragment = new StudyReportFragmentsEntity(); fragment.setContextType("REVIEW"); fragment.setContextNum(tag); fragment.setContent("中文🙂资料"); fragments.insert(fragment); + markers.addUserTag(MarkerObjectTypeEnum.FRAGMENT, fragment.getId().toString(), tag); + } + String id() { return UUID.randomUUID().toString(); } + String createBody() throws Exception { return mapper.writeValueAsString(new CreateRecallRequest(id(), "editor", new ScopeInput("TAG", null, List.of(tag), "UNION"), null)); } + JsonNode create() throws Exception { + return mapper.readTree(mvc.perform(post("/review/recalls").header("satoken", token).contentType(MediaType.APPLICATION_JSON).content(createBody())) + .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200)).andReturn().getResponse().getContentAsString()).path("data"); + } + String aiBody(JsonNode detail, String type) throws Exception { + return mapper.writeValueAsString(Map.of("type", type, "targetNum", detail.path("recallNum").asText(), + "params", new AiParams(1, id(), "editor", detail.path("writeToken").asText(), "RECALL_HINT".equals(type) ? "KEYWORD" : null))); + } + @Test void currentDetailHasNoVersionsAndMaterialsArePagedWithoutVersionPaths() throws Exception { + JsonNode detail = create(); String num = detail.path("recallNum").asText(); + assertTrue(detail.path("createdAt").asText().endsWith("Z")); assertTrue(detail.has("writeToken")); + for (String field : List.of("expressionVersions", "expressionVersion", "referenceVersion", "revision", "notes")) assertFalse(detail.has(field)); + JsonNode page = mapper.readTree(mvc.perform(get("/review/recalls/" + num + "/references").header("satoken", token).param("pageSize", "10")) + .andExpect(jsonPath("$.data.total").value(1)).andExpect(jsonPath("$.data.records[0].preview").value("中文🙂资料")) + .andReturn().getResponse().getContentAsString()).path("data"); + String source = page.path("records").get(0).path("sourceId").asText(); + mvc.perform(get("/review/recalls/" + num + "/references/sources/" + source).header("satoken", token)).andExpect(jsonPath("$.data.content").value("中文🙂资料")); + mvc.perform(get("/review/recalls/" + num).header("satoken", token)).andExpect(jsonPath("$.data.writeToken").value(detail.path("writeToken").asText())); + } + @Test void oldVersionFieldsAndStaleWriteTokensAreExplicitErrors() throws Exception { + var legacy = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(createBody()); legacy.putNull("carryFrom"); + mvc.perform(post("/review/recalls").header("satoken", token).contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(legacy))) + .andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.data.reason").value("INVALID_INPUT")); + String num = create().path("recallNum").asText(); + mvc.perform(post("/review/recalls/" + num + "/resume").header("satoken", token).contentType(MediaType.APPLICATION_JSON) + .content(mapper.writeValueAsString(new ResumeRequest(id(), "second", "stale-token")))) + .andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.data.reason").value("REVISION_CONFLICT")); + } + @Test void otherUserAndDeletedRecallAreNotFound() throws Exception { + String num = create().path("recallNum").asText(); StpUtil.login("other-http-" + id()); String other = StpUtil.getTokenValue(); + mvc.perform(get("/review/recalls/" + num).header("satoken", other)).andExpect(jsonPath("$.data.reason").value("NOT_FOUND")); + mvc.perform(delete("/review/recalls/" + num).header("satoken", token)).andExpect(jsonPath("$.code").value(200)); + mvc.perform(get("/review/recalls/" + num).header("satoken", token)).andExpect(jsonPath("$.data.reason").value("NOT_FOUND")); + } + @ParameterizedTest + @ValueSource(strings = {"AI_UNAVAILABLE", "AI_TIMEOUT", "AI_REQUEST_FAILED", "INVALID_AI_RESULT", "SOURCE_REDACTED", + "AI_AUTH_FAILED", "AI_QUOTA_EXCEEDED", "AI_RATE_LIMITED", "AI_OUTPUT_LIMIT", "AI_EMPTY_RESPONSE"}) + void runnerStoresSafeFailureCodesAndPollingReturnsThem(String code) throws Exception { + for (String type : List.of("RECALL_HINT", "RECALL_CHECK")) { + JsonNode detail = create(); + JsonNode submitted = mapper.readTree(mvc.perform(post("/ai/tasks").header("satoken", token).contentType(MediaType.APPLICATION_JSON).content(aiBody(detail, type))) + .andExpect(jsonPath("$.data.status").value("PENDING")).andReturn().getResponse().getContentAsString()).path("data"); + String num = submitted.path("taskNum").asText(); + var task = tasks.selectOne(com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery().eq(com.guo.learningprogresstracker.entity.AiTaskEntity::getTaskNum, num)); + doThrow(new RecallAiFailure(code, "PRIVATE-PROMPT-and-api-key")).when(client).submit(any(), any(), any()); + new AiTaskRunner(aiTasks, registry, properties).onTaskSubmitted(new AiTaskSubmittedEvent(task.getId())); + String response = mvc.perform(get("/ai/tasks/" + num).header("satoken", token)).andExpect(jsonPath("$.data.status").value("FAILED")) + .andExpect(jsonPath("$.data.errorCode").value(code)).andExpect(jsonPath("$.data.result").isEmpty()).andReturn().getResponse().getContentAsString(); + assertFalse(response.contains("PRIVATE")); + mvc.perform(get("/review/recalls/" + detail.path("recallNum").asText()).header("satoken", token)) + .andExpect(jsonPath("$.data.requests[0].status").value("FAILED")).andExpect(jsonPath("$.data.requests[0].errorCode").value(code)); + } + } + /** + * 手写 body:前端按 TS 类型省略可选 style 是合法的,不能被当成缺必填字段; + * 真正必填的字段(schemaVersion / 节点 id / provenance)缺失和未知字段仍然要拒绝。 + */ + @Test void draftAcceptsOmittedOptionalStyleAndRejectsMissingRequiredFields() throws Exception { + JsonNode detail = create(); String num = detail.path("recallNum").asText(); String editorId = detail.path("editorId").asText(); + String child = "{\"id\":\"child\",\"title\":\"子节点\",\"notes\":\"\",\"provenance\":[],\"children\":[]}"; + String root = "{\"id\":\"root\",\"title\":\"\",\"notes\":\"\",\"provenance\":[],\"style\":null,\"children\":[" + child + "]}"; + String valid = "{\"schemaVersion\":1,\"root\":" + root + "}"; + // 每次保存都会换写令牌,所以每个用例都读最新的 detail 再拼 body。 + Function save = expression -> { + try { + String writeToken = mapper.readTree(mvc.perform(get("/review/recalls/" + num).header("satoken", token)) + .andReturn().getResponse().getContentAsString()).path("data").path("writeToken").asText(); + return mvc.perform(put("/review/recalls/" + num + "/draft").header("satoken", token).contentType(MediaType.APPLICATION_JSON) + .content("{\"editorId\":\"" + editorId + "\",\"writeToken\":\"" + writeToken + "\",\"clientRequestId\":\"" + id() + + "\",\"expression\":" + expression + ",\"timing\":{\"segmentActiveMs\":0,\"segmentActualMs\":0,\"lastInteractionAt\":null}}")); + } catch (Exception e) { throw new IllegalStateException(e); } + }; + save.apply(valid).andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.expression.root.children[0].title").value("子节点")); + for (String broken : List.of( + valid.replace("\"schemaVersion\":1,", ""), + valid.replace("\"id\":\"child\",", ""), + valid.replace("\"provenance\":[],", ""))) { + save.apply(broken).andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.data.reason").value("INVALID_INPUT")); + } + save.apply("{\"schemaVersion\":1,\"carryFrom\":\"x\",\"root\":" + root + "}") + .andExpect(jsonPath("$.code").value(400)).andExpect(jsonPath("$.data.reason").value("INVALID_INPUT")); + } + @Test void unknownLegacyAiTypesAreRejectedRatherThanWritingOldTables() throws Exception { + for (String type : List.of("RECALL_COMPARE", "TAG_RECALL_COMPARE")) { + mvc.perform(post("/ai/tasks").header("satoken", token).contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(Map.of("type", type, "targetNum", tag)))) + .andExpect(jsonPath("$.code").value(400)); + } + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/controller/StudySessionControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/StudySessionControllerUnitTest.java index d105b6c..3d85b72 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/StudySessionControllerUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/StudySessionControllerUnitTest.java @@ -28,6 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.guo.learningprogresstracker.dto.response.StudyExpectationResponse; +import com.guo.learningprogresstracker.dto.response.ReportFragmentResponse; +import com.guo.learningprogresstracker.dto.response.StudyReportResponse; /** * StudySessionController 纯单元测试:直接 new 控制器并 mock 服务层, @@ -52,10 +56,10 @@ class StudySessionControllerUnitTest { StudyExpectationsEntity entity = new StudyExpectationsEntity(); when(studyExpectationsService.upsertExpectation("S001", "目标:掌握租户隔离")).thenReturn(entity); - CommonResult result = controller.upsertExpectation("S001", request); + CommonResult result = controller.upsertExpectation("S001", request); assertEquals(200, result.getCode()); - assertSame(entity, result.getData()); + assertNotNull(result.getData()); verify(studyExpectationsService).upsertExpectation("S001", "目标:掌握租户隔离"); } @@ -64,10 +68,10 @@ class StudySessionControllerUnitTest { StudyExpectationsEntity entity = new StudyExpectationsEntity(); when(studyExpectationsService.getBySessionNum("S002")).thenReturn(entity); - CommonResult result = controller.getExpectation("S002"); + CommonResult result = controller.getExpectation("S002"); assertEquals(200, result.getCode()); - assertSame(entity, result.getData()); + assertNotNull(result.getData()); } @Test @@ -145,7 +149,7 @@ class StudySessionControllerUnitTest { CommonResult> result = controller.getAllFragments("S009"); assertEquals(200, result.getCode()); - assertSame(fragments, result.getData()); + assertNotNull(result.getData()); } @Test @@ -153,10 +157,10 @@ class StudySessionControllerUnitTest { Page page = new Page<>(); when(studySessionsServiceImpl.getTaskFragments("T001", 2, 5, "关键词")).thenReturn(page); - CommonResult> result = controller.getTaskFragments("T001", 2, 5, "关键词"); + CommonResult> result = controller.getTaskFragments("T001", 2, 5, "关键词"); assertEquals(200, result.getCode()); - assertSame(page, result.getData()); + assertNotNull(result.getData()); } @Test @@ -164,10 +168,10 @@ class StudySessionControllerUnitTest { Page page = new Page<>(); when(studySessionsServiceImpl.getTaskReports("T002", 3, 20, null)).thenReturn(page); - CommonResult> result = controller.getTaskReports("T002", 3, 20, null); + CommonResult> result = controller.getTaskReports("T002", 3, 20, null); assertEquals(200, result.getCode()); - assertSame(page, result.getData()); + assertEquals(page.getTotal(), result.getData().getTotal()); } @Test diff --git a/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java index 2b5c6f8..057bbb2 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/TagMindMapControllerUnitTest.java @@ -7,7 +7,6 @@ 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.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; import com.guo.learningprogresstracker.enums.TagCombineModeEnum; import com.guo.learningprogresstracker.service.ReviewTagMindMapService; @@ -23,6 +22,8 @@ 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; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.guo.learningprogresstracker.dto.response.TagMindMapResponse; /** * TagMindMapController 纯单元测试:直接 new 控制器并 mock 服务接口。 @@ -82,11 +83,10 @@ class TagMindMapControllerUnitTest { TagCombineModeEnum.INTERSECT); when(reviewTagMindMapService.resolveScope(List.of("Java", "并发"), "INTERSECT")).thenReturn(intersectScope); when(reviewTagMindMapService.updateByOutline(intersectScope, "- 根节点")).thenReturn(updated); - - CommonResult result = controller.updateTagMindMap(request); + CommonResult result = controller.updateTagMindMap(request); assertEquals(200, result.getCode()); - assertSame(updated, result.getData()); + assertNotNull(result.getData()); } @Test @@ -103,15 +103,4 @@ class TagMindMapControllerUnitTest { assertEquals(1, result.getData().getTotal()); } - @Test - void listRecallRecords_returnsRangeHistory() throws Exception { - List records = List.of(new ReviewRecallRecordEntity()); - when(reviewTagMindMapService.resolveScope(List.of("Java", "并发"), "UNION")).thenReturn(scope()); - when(reviewTagMindMapService.listRecallRecords(scope())).thenReturn(records); - - CommonResult> result = controller.listRecallRecords(request("UNION")); - - assertEquals(200, result.getCode()); - assertSame(records, result.getData()); - } } diff --git a/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerTest.java b/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerTest.java index 656fccc..bb19ea4 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerTest.java @@ -80,20 +80,23 @@ class TaskControllerTest { */ @Test void getTask() throws Exception { - String taskId = "1"; + TaskEntity fixture = createOwnFixture("读取任务-"); + String taskId = fixture.getId().toString(); mockMvc.perform(get("/tasks/"+taskId) .header("satoken",StpUtil.getTokenValue())) .andDo(print()) .andExpect(jsonPath("$.code").value(200)) - .andExpect(jsonPath("$.data").exists()); + .andExpect(jsonPath("$.data").exists()) + .andExpect(jsonPath("$.data.taskName").value(fixture.getTaskName())); } @Test void updateTask() throws Exception { - TaskRequest taskRequest = getTaskRequest("测试数据名称"); - taskRequest.setId(1); + TaskEntity fixture = createOwnFixture("更新任务-"); + TaskRequest taskRequest = getTaskRequest("测试数据名称-" + System.nanoTime()); + taskRequest.setId(fixture.getId()); String s = jacksonObjectMapper.writeValueAsString(taskRequest); mockMvc.perform(put("/tasks/"+taskRequest.getId()) @@ -103,9 +106,18 @@ class TaskControllerTest { .andDo(print()) .andExpect(jsonPath("$.code").value(200)) .andExpect(jsonPath("$.data").isEmpty()); + assertEquals(taskRequest.getTaskName(), tasksServiceImpl.getById(fixture.getId()).getTaskName()); } + private TaskEntity createOwnFixture(String prefix) throws Exception { + CommonResult created = taskController.addTask(getTaskRequest(prefix + System.nanoTime())); + assertEquals(200, created.getCode()); + TaskEntity fixture = tasksServiceImpl.getOne(Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, created.getData())); + assertNotNull(fixture, "每个用例自己建立当前用户的任务,不依赖共享数据库的 id=1"); + return fixture; + } + @Test void deleteTask() throws Exception { CommonResult commonResult = taskController.addTask(getTaskRequest("待删除任务-" + System.nanoTime())); diff --git a/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerUnitTest.java b/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerUnitTest.java index 675e20e..328d9fa 100644 --- a/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/controller/TaskControllerUnitTest.java @@ -25,6 +25,11 @@ 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; +import static org.mockito.ArgumentMatchers.any; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.guo.learningprogresstracker.dto.response.PriorityWeightsResponse; +import com.guo.learningprogresstracker.dto.response.TaskApplicationResponse; +import com.guo.learningprogresstracker.dto.request.PriorityWeightsRequest; /** * TaskController 纯单元测试:直接 new 控制器并 mock 三个依赖服务。 @@ -49,22 +54,22 @@ class TaskControllerUnitTest { UserPriorityWeightsEntity weights = new UserPriorityWeightsEntity(); when(priorityWeightsService.getWeights()).thenReturn(weights); - CommonResult result = controller.getPriorityWeights(); + CommonResult result = controller.getPriorityWeights(); assertEquals(200, result.getCode()); - assertSame(weights, result.getData()); + assertNotNull(result.getData()); } @Test void savePriorityWeights_delegatesToService() throws Exception { - UserPriorityWeightsEntity weights = new UserPriorityWeightsEntity(); + PriorityWeightsRequest request = new PriorityWeightsRequest(); UserPriorityWeightsEntity saved = new UserPriorityWeightsEntity(); - when(priorityWeightsService.saveWeights(weights)).thenReturn(saved); + when(priorityWeightsService.saveWeights(any(UserPriorityWeightsEntity.class))).thenReturn(saved); - CommonResult result = controller.savePriorityWeights(weights); + CommonResult result = controller.savePriorityWeights(request); assertEquals(200, result.getCode()); - assertSame(saved, result.getData()); + assertNotNull(result.getData()); } @Test @@ -112,10 +117,10 @@ class TaskControllerUnitTest { List applications = List.of(new TaskApplicationEntity()); when(tasksService.getApplications("T-1")).thenReturn(applications); - CommonResult> result = controller.getApplications("T-1"); + CommonResult> result = controller.getApplications("T-1"); assertEquals(200, result.getCode()); - assertSame(applications, result.getData()); + assertNotNull(result.getData()); } @Test @@ -125,11 +130,11 @@ class TaskControllerUnitTest { TaskApplicationEntity created = new TaskApplicationEntity(); when(tasksService.createApplication(request)).thenReturn(created); - CommonResult result = controller.createApplication("T-2", request); + CommonResult result = controller.createApplication("T-2", request); assertEquals("T-2", request.getTaskNum()); assertEquals(200, result.getCode()); - assertSame(created, result.getData()); + assertNotNull(result.getData()); } @Test @@ -139,10 +144,10 @@ class TaskControllerUnitTest { TaskApplicationEntity updated = new TaskApplicationEntity(); when(tasksService.updateApplication(7, request)).thenReturn(updated); - CommonResult result = controller.updateApplication(7, request); + CommonResult result = controller.updateApplication(7, request); assertEquals(200, result.getCode()); - assertSame(updated, result.getData()); + assertNotNull(result.getData()); } @Test diff --git a/src/test/java/com/guo/learningprogresstracker/mapStruct/FragmentsConvertTest.java b/src/test/java/com/guo/learningprogresstracker/mapstruct/FragmentsConvertTest.java similarity index 95% rename from src/test/java/com/guo/learningprogresstracker/mapStruct/FragmentsConvertTest.java rename to src/test/java/com/guo/learningprogresstracker/mapstruct/FragmentsConvertTest.java index 051a2ea..2571990 100644 --- a/src/test/java/com/guo/learningprogresstracker/mapStruct/FragmentsConvertTest.java +++ b/src/test/java/com/guo/learningprogresstracker/mapstruct/FragmentsConvertTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.mapStruct; +package com.guo.learningprogresstracker.mapstruct; import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; diff --git a/src/test/java/com/guo/learningprogresstracker/mapStruct/StudySessionConvertTest.java b/src/test/java/com/guo/learningprogresstracker/mapstruct/StudySessionConvertTest.java similarity index 95% rename from src/test/java/com/guo/learningprogresstracker/mapStruct/StudySessionConvertTest.java rename to src/test/java/com/guo/learningprogresstracker/mapstruct/StudySessionConvertTest.java index 44e4545..905b87c 100644 --- a/src/test/java/com/guo/learningprogresstracker/mapStruct/StudySessionConvertTest.java +++ b/src/test/java/com/guo/learningprogresstracker/mapstruct/StudySessionConvertTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.mapStruct; +package com.guo.learningprogresstracker.mapstruct; import com.guo.learningprogresstracker.dto.response.StudySessionResponse; import com.guo.learningprogresstracker.entity.StudySessionsEntity; diff --git a/src/test/java/com/guo/learningprogresstracker/migration/FragmentOwnerTagMigrationTest.java b/src/test/java/com/guo/learningprogresstracker/migration/FragmentOwnerTagMigrationTest.java new file mode 100644 index 0000000..3bf3bb0 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/migration/FragmentOwnerTagMigrationTest.java @@ -0,0 +1,126 @@ +package com.guo.learningprogresstracker.migration; + +import db.migration.V20261115_5__backfill_fragment_owner_tags; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.migration.Context; +import org.junit.jupiter.api.Test; + +import java.sql.*; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class FragmentOwnerTagMigrationTest { + String database(String target) { + String url = "jdbc:h2:mem:owner-tags-" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;NON_KEYWORDS=USER;DB_CLOSE_DELAY=-1"; + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target(target).load().migrate(); + return url; + } + @Test void backfillsCurrentOwnerPerTenantWithoutRevivingDeletedTagsOrReplacingCustomNames() throws Exception { + String url = database("20261115.2"); + try (Connection c = DriverManager.getConnection(url, "sa", "")) { + task(c, "old-session-task", "Original", "a", 0); + task(c, "current-task", "Renamed Now", "a", 0); + task(c, "same-name-task", " renamed now ", "a", 0); + task(c, "foreign-task", "Foreign", "b", 0); + task(c, "removed-task", "Removed", "a", 1); + task(c, "long-task", "长".repeat(255), "a", 0); + task(c, "dict-deleted", "Deleted Dictionary", "a", 0); + fragment(c, 1, "current-task", "a", 0); + fragment(c, 2, "same-name-task", "a", 0); + fragment(c, 3, "current-task", "b", 0); // invalid cross-tenant ownership + fragment(c, 4, "foreign-task", "b", 0); + fragment(c, 5, "removed-task", "a", 0); + fragment(c, 6, null, "a", 0); + fragment(c, 7, "current-task", "a", 1); + fragment(c, 8, "long-task", "a", 0); + fragment(c, 9, "current-task", "a", 0); + fragment(c, 10, "dict-deleted", "a", 0); + fragment(c, 11, "missing-task", "a", 0); + marker(c, "1", "Custom", "a", 0); + marker(c, "2", "RENAMED NOW", "a", 0); + marker(c, "9", " renamed NOW ", "a", 1); + try (var statement = c.createStatement()) { + statement.executeUpdate("INSERT INTO review_tag_mind_maps(scope_key,combine_mode,tag_names,title,content,created_time) VALUES ('old-scope','UNION','[\"Original\"]','Original title','{}',CURRENT_TIMESTAMP)"); + statement.executeUpdate("INSERT INTO review_recall_records(scope_type,scope_tags,recall_content,created_time) VALUES ('TAG','[\"Original\"]','old expression',CURRENT_TIMESTAMP)"); + } + try (var s = c.createStatement()) { s.executeUpdate("INSERT INTO user_tags(tag_name,normalized_name,created_by,created_time,deleted) VALUES ('Deleted Dictionary','deleted dictionary','a',CURRENT_TIMESTAMP,1)"); } + } + Flyway flyway = Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261115.5").load(); + flyway.migrate(); flyway.migrate(); + try (Connection c = DriverManager.getConnection(url, "sa", "")) { + Context context = mock(Context.class); when(context.getConnection()).thenReturn(c); + new V20261115_5__backfill_fragment_owner_tags().migrate(context); // actual data migration is idempotent too + assertEquals(7, count(c, "SELECT COUNT(*) FROM markers")); // custom + existing + tombstone + 4 additions + assertEquals(2, count(c, "SELECT COUNT(*) FROM markers WHERE object_num='1' AND deleted=0")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM markers WHERE object_num='2' AND marker_name='RENAMED NOW'")); + assertEquals(0, count(c, "SELECT COUNT(*) FROM markers WHERE object_num IN ('3','5','6','7','11')")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM markers WHERE object_num='10' AND marker_name='Deleted Dictionary' AND deleted=0"), + "A removed dictionary suggestion must not prevent the fragment's automatic tag"); + assertEquals(1, count(c, "SELECT COUNT(*) FROM markers WHERE object_num='9' AND deleted=1")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM markers WHERE object_num='8' AND CHAR_LENGTH(marker_name)=255")); + assertEquals(0, count(c, "SELECT COUNT(*) FROM markers WHERE marker_name='Original'")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM user_tags WHERE created_by='a' AND normalized_name='renamed now' AND deleted=0")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM user_tags WHERE created_by='b' AND normalized_name='foreign'")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM user_tags WHERE normalized_name='deleted dictionary' AND deleted=1")); + assertEquals(4, count(c, "SELECT COUNT(*) FROM user_tags")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM review_tag_mind_maps WHERE tag_names='[\"Original\"]' AND title='Original title' AND content='{}'")); + assertEquals(1, count(c, "SELECT COUNT(*) FROM review_recall_records WHERE scope_tags='[\"Original\"]' AND recall_content='old expression'")); + } + } + @Test void preflightIncludesSoftDeletedRowsAndFailsBeforeAnyDdlWithoutLeakingValues() throws Exception { + String url = database("20261115.2"); + try (Connection c = DriverManager.getConnection(url, "sa", "")) { + marker(c, "1", "private", "a", 1); + try (var s = c.prepareStatement("UPDATE markers SET marker_value=?")) { s.setString(1, "PRIVATE".repeat(20)); s.executeUpdate(); } + } + Exception failure = assertThrows(Exception.class, () -> Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").load().migrate()); + StringBuilder messages = new StringBuilder(); + for (Throwable e = failure; e != null; e = e.getCause()) messages.append(e.getMessage()); + assertTrue(messages.toString().contains("record id=")); assertFalse(messages.toString().contains("PRIVATE")); + try (Connection c = DriverManager.getConnection(url, "sa", "")) { + assertEquals(100, count(c, "SELECT character_maximum_length FROM information_schema.columns WHERE table_name='markers' AND column_name='marker_name'")); + assertEquals(255, count(c, "SELECT character_maximum_length FROM information_schema.columns WHERE table_name='markers' AND column_name='marker_value'")); + } + } + @Test void expandsAllLabelColumnsAndFinalIndexKeysFitMySqlLimit() throws Exception { + String url = database("20261115.5"); + try (Connection c = DriverManager.getConnection(url, "sa", "")) { + for (String column : new String[]{"markers.marker_name", "user_tags.tag_name", "user_tags.normalized_name"}) { + String[] parts = column.split("\\."); + assertEquals(255, count(c, "SELECT character_maximum_length FROM information_schema.columns WHERE table_name='" + parts[0] + "' AND column_name='" + parts[1] + "'")); + } + try (var s = c.createStatement(); var rows = s.executeQuery(""" + SELECT i.index_name, SUM(COALESCE(c.character_maximum_length * 4, 8)) AS key_bytes + FROM information_schema.index_columns i JOIN information_schema.columns c + ON c.table_schema=i.table_schema AND c.table_name=i.table_name AND c.column_name=i.column_name + WHERE i.table_name IN ('markers', 'user_tags') AND i.table_schema='public' + GROUP BY i.index_name + """)) { + int indexes = 0; + while (rows.next()) { indexes++; assertTrue(rows.getInt(2) <= 3072, rows.getString(1)); } + assertTrue(indexes >= 6); + } + } + for (var marker : com.guo.learningprogresstracker.enums.SystemMarkerEnum.values()) assertTrue(marker.getMarkerValue().length() <= 128); + } + int count(Connection c, String sql) throws SQLException { + try (var s = c.createStatement(); var rows = s.executeQuery(sql)) { assertTrue(rows.next()); return rows.getInt(1); } + } + void task(Connection c, String num, String name, String user, int deleted) throws SQLException { + try (var s = c.prepareStatement("INSERT INTO tasks(task_num,task_name,created_by,created_time,deleted) VALUES (?,?,?,CURRENT_TIMESTAMP,?)")) { + s.setString(1,num); s.setString(2,name); s.setString(3,user); s.setInt(4,deleted); s.executeUpdate(); + } + } + void fragment(Connection c, int id, String owner, String user, int deleted) throws SQLException { + try (var s = c.prepareStatement("INSERT INTO study_report_fragments(id,owner_task_num,context_type,context_num,content,created_by,created_time,deleted) VALUES (?,?,'SESSION','old-session-task','content',?,CURRENT_TIMESTAMP,?)")) { + s.setInt(1,id); s.setString(2,owner); s.setString(3,user); s.setInt(4,deleted); s.executeUpdate(); + } + } + void marker(Connection c, String id, String name, String user, int deleted) throws SQLException { + try (var s = c.prepareStatement("INSERT INTO markers(object_type,object_num,kind,marker_name,created_by,created_time,deleted) VALUES ('FRAGMENT',?,'USER',?,?,CURRENT_TIMESTAMP,?)")) { + s.setString(1,id); s.setString(2,name); s.setString(3,user); s.setInt(4,deleted); s.executeUpdate(); + } + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/migration/MigrationIndexKeyLengthTest.java b/src/test/java/com/guo/learningprogresstracker/migration/MigrationIndexKeyLengthTest.java index 553bb38..c8436c7 100644 --- a/src/test/java/com/guo/learningprogresstracker/migration/MigrationIndexKeyLengthTest.java +++ b/src/test/java/com/guo/learningprogresstracker/migration/MigrationIndexKeyLengthTest.java @@ -68,13 +68,16 @@ class MigrationIndexKeyLengthTest { void everyIndexFitsWithinInnoDbKeyLimit() throws Exception { Map> tableColumns = new LinkedHashMap<>(); List indexes = new ArrayList<>(); + List droppedIndexes = new ArrayList<>(); for (Path file : migrationFiles()) { String sql = stripComments(Files.readString(file)); Parser parser = new Parser(file.getFileName().toString()); - parser.parse(sql, tableColumns, indexes); + parser.parse(sql, tableColumns, indexes, droppedIndexes); } + // Dropping an index later cannot excuse an invalid key at its original creation step. + indexes.addAll(droppedIndexes); assertTrue(indexes.size() > 10, "应至少解析出若干索引,实际 " + indexes.size() + "(解析器是否失效?)"); List violations = new ArrayList<>(); @@ -170,6 +173,7 @@ class MigrationIndexKeyLengthTest { Pattern.compile("(?i)^\\s*(?:unique\\s+)?(?:key|index)\\s+(\\w+)\\s*\\(([^)]*)\\)"); private static final Pattern CREATE_INDEX = Pattern.compile("(?i)^\\s*create\\s+(?:unique\\s+)?index\\s+(\\w+)\\s+on\\s+(\\w+)\\s*\\(([^)]*)\\)"); + private static final Pattern DROP_INDEX = Pattern.compile("(?i)^drop\\s+index\\s+(\\w+)\\s+on\\s+(\\w+)"); private static final Pattern ADD_UNIQUE_CONSTRAINT = Pattern.compile("(?i)^add\\s+constraint\\s+(\\w+)\\s+unique\\s*\\(([^)]*)\\)"); @@ -205,7 +209,7 @@ class MigrationIndexKeyLengthTest { return new IndexDef(fileName, table, name, columns, declared); } - void parse(String sql, Map> tableColumns, List indexes) { + void parse(String sql, Map> tableColumns, List indexes, List droppedIndexes) { String[] lines = sql.split("\r?\n"); for (int i = 0; i < lines.length; i += 1) { String line = lines[i].strip(); @@ -254,6 +258,14 @@ class MigrationIndexKeyLengthTest { continue; } + Matcher dropIndex = DROP_INDEX.matcher(line); + if (dropIndex.find()) { + List removed = indexes.stream().filter(index -> index.table().equalsIgnoreCase(dropIndex.group(2)) + && index.name().equalsIgnoreCase(dropIndex.group(1))).toList(); + droppedIndexes.addAll(removed); + indexes.removeAll(removed); + continue; + } Matcher createIndex = CREATE_INDEX.matcher(line); // 必须用 find() 而不是 matches():语句行尾带分号(`... (a, b);`)时 // matches() 要求整行完全匹配,会把这条 CREATE INDEX 静默跳过—— @@ -300,7 +312,18 @@ class MigrationIndexKeyLengthTest { Matcher column = ADD_OR_MODIFY_COLUMN.matcher(rest); if (column.find()) { String name = column.group(1).toLowerCase(Locale.ROOT); - columns.put(name, declaredType(column.group(2), column.group(3))); + String type = declaredType(column.group(2), column.group(3)); + columns.put(name, type); + // MODIFY rebuilds existing indexes too: check their new key widths at this step. + Map affected = new LinkedHashMap<>(); + for (IndexDef index : indexes) { + if (index.table().equals(table) && index.columns().contains(name)) affected.put(index.name(), index); + } + for (IndexDef index : affected.values()) { + Map types = new LinkedHashMap<>(index.declaredTypes()); + types.put(name, type); + indexes.add(new IndexDef(fileName, table, index.name(), index.columns(), types)); + } } } } diff --git a/src/test/java/com/guo/learningprogresstracker/migration/RecallExposuresMigrationTest.java b/src/test/java/com/guo/learningprogresstracker/migration/RecallExposuresMigrationTest.java new file mode 100644 index 0000000..d629019 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/migration/RecallExposuresMigrationTest.java @@ -0,0 +1,57 @@ +package com.guo.learningprogresstracker.migration; + +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Test; + +import java.sql.*; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +/** 内容暴露记录下线:历史文档里的 detail.exposures 被摘掉,其余字段与无法解析的文档原样保留。 */ +class RecallExposuresMigrationTest { + @Test void stripsExposureNodesAndLeavesEveryOtherDocumentAlone() throws Exception { + String url = "jdbc:h2:mem:recall-exposures-" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;NON_KEYWORDS=USER;DB_CLOSE_DELAY=-1"; + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261118.1").load().migrate(); + String keep = "{\"detail\":{\"recallNum\":\"RECALL-2\",\"expression\":{\"schemaVersion\":1,\"root\":{\"id\":\"root\",\"title\":\"另一份私有标题\",\"notes\":\"\",\"provenance\":[],\"children\":[]}}}," + + "\"reference\":{\"status\":\"AVAILABLE\",\"sources\":[],\"units\":[],\"limitations\":[]},\"acceptedSegmentMs\":0}"; + String withExposures = "{\"detail\":{\"recallNum\":\"RECALL-1\",\"expression\":{\"schemaVersion\":1,\"root\":{\"id\":\"root\",\"title\":\"私有标题\",\"notes\":\"\",\"provenance\":[],\"children\":[]}}," + + "\"exposures\":[{\"exposureId\":\"EXPOSE-1\",\"kind\":\"SOURCE_TEXT\",\"sourceId\":\"fragment:1\",\"displayedText\":\"私有正文\",\"status\":\"AVAILABLE\"}],\"requests\":[]}," + + "\"reference\":{\"status\":\"AVAILABLE\",\"sources\":[],\"units\":[],\"limitations\":[]},\"epochStartedAt\":\"2026-11-18T00:00:00Z\",\"acceptedSegmentMs\":120}"; + String malformed = "PRIVATE-LEARNING-TEXT not JSON"; + try (Connection connection = DriverManager.getConnection(url, "sa", "")) { + insert(connection, 1, "with-exposures", withExposures); + insert(connection, 2, "without-exposures", keep); + insert(connection, 3, "malformed", malformed); + insert(connection, 4, "deleted-document", null); + } + + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").load().migrate(); + + try (Connection connection = DriverManager.getConnection(url, "sa", ""); + ResultSet rows = connection.createStatement().executeQuery("SELECT recall_num, document_json FROM review_recalls ORDER BY id")) { + assertTrue(rows.next()); + String stripped = rows.getString("document_json"); + assertFalse(stripped.contains("exposures")); + assertFalse(stripped.contains("私有正文")); + assertTrue(stripped.contains("私有标题")); + assertTrue(stripped.contains("\"acceptedSegmentMs\":120")); + assertTrue(stripped.contains("\"requests\":[]")); + assertTrue(rows.next()); + assertEquals(keep, rows.getString("document_json"), "没有 exposures 的文档必须逐字不变"); + assertTrue(rows.next()); + assertEquals(malformed, rows.getString("document_json"), "坏 JSON 跳过,不阻塞升级"); + assertTrue(rows.next()); + assertNull(rows.getString("document_json")); + assertFalse(rows.next()); + } + } + + void insert(Connection connection, int id, String recallNum, String document) throws SQLException { + try (PreparedStatement insert = connection.prepareStatement( + "INSERT INTO review_recalls (id, recall_num, scope_type, status, scope_key, created_by, created_time, last_modified_time, document_json) " + + "VALUES (?, ?, 'TAG', 'ENDED', 'key', 'owner', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)")) { + insert.setInt(1, id); insert.setString(2, recallNum); insert.setString(3, document); insert.executeUpdate(); + } + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/migration/RecallScopeKeyMigrationTest.java b/src/test/java/com/guo/learningprogresstracker/migration/RecallScopeKeyMigrationTest.java new file mode 100644 index 0000000..f076240 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/migration/RecallScopeKeyMigrationTest.java @@ -0,0 +1,79 @@ +package com.guo.learningprogresstracker.migration; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.sql.*; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +class RecallScopeKeyMigrationTest { + ObjectMapper mapper = new ObjectMapper().findAndRegisterModules(); + + @Test void upgradesOldSchemaAndCopiesFrozenKeysWithoutChangingDocuments() throws Exception { + String url = oldSchema(); + String tagKey = "a".repeat(64); + String tagDocument = document("TAG", tagKey); + String taskDocument = document("TASK", "historical-task"); + try (Connection connection = DriverManager.getConnection(url, "sa", "")) { + insert(connection, 1, "TAG", tagDocument, 0); + insert(connection, 2, "TASK", taskDocument, 0); + insert(connection, 3, "TAG", null, 1); + insert(connection, 4, "TAG", tagDocument, 1); + } + Flyway upgraded = Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261115.5").load(); + upgraded.migrate(); + assertEquals("20261115.5", upgraded.info().current().getVersion().toString(), "Java migration must be discovered after SQL migration"); + try (Connection connection = DriverManager.getConnection(url, "sa", ""); + ResultSet rows = connection.createStatement().executeQuery("SELECT id, scope_key, document_json FROM review_recalls ORDER BY id")) { + assertTrue(rows.next()); assertEquals(tagKey, rows.getString("scope_key")); assertEquals(tagDocument, rows.getString("document_json")); + assertTrue(rows.next()); assertEquals("historical-task", rows.getString("scope_key")); assertEquals(taskDocument, rows.getString("document_json")); + assertTrue(rows.next()); assertNull(rows.getString("scope_key")); assertNull(rows.getString("document_json")); + assertTrue(rows.next()); assertEquals(tagKey, rows.getString("scope_key")); + } + } + + @ParameterizedTest + @ValueSource(strings = {"malformed", "missing", "nontext", "oversized", "null"}) + void activeInvalidHistoryFailsWithOnlyRecordId(String kind) throws Exception { + String url = oldSchema(); + String body = switch (kind) { + case "malformed" -> "PRIVATE-LEARNING-TEXT not JSON"; + case "missing" -> "{\"detail\":{\"scope\":{\"type\":\"TAG\"}},\"private\":\"PRIVATE-LEARNING-TEXT\"}"; + case "nontext" -> "{\"detail\":{\"scope\":{\"type\":\"TAG\",\"scopeKey\":123}}}"; + case "oversized" -> document("TAG", "a".repeat(65)); + default -> null; + }; + try (Connection connection = DriverManager.getConnection(url, "sa", "")) { insert(connection, 17, "TAG", body, 0); } + Exception error = assertThrows(Exception.class, + () -> Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").load().migrate()); + StringBuilder chain = new StringBuilder(); + for (Throwable current = error; current != null; current = current.getCause()) chain.append(current.getMessage()); + assertTrue(chain.toString().contains("record id=17")); assertFalse(chain.toString().contains("PRIVATE-LEARNING-TEXT")); + } + + String oldSchema() { + String url = "jdbc:h2:mem:migration-" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;NON_KEYWORDS=USER;DB_CLOSE_DELAY=-1"; + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261114.1").load().migrate(); + return url; + } + String document(String type, String key) throws Exception { + RecallDetail detail = new RecallDetail(); + detail.setScope(new ScopeSnapshot(type, "TASK".equals(type) ? key : null, List.of("historical"), List.of("historical"), + "TAG".equals(type) ? "UNION" : null, key, "Frozen historical display", Instant.now())); + RecallDocument document = new RecallDocument(); document.setDetail(detail); + return mapper.writeValueAsString(document); + } + void insert(Connection connection, int id, String type, String body, int deleted) throws SQLException { + try (PreparedStatement insert = connection.prepareStatement("INSERT INTO review_recalls (id, recall_num, scope_type, status, revision, created_by, created_time, last_modified_time, document_json, deleted) VALUES (?, ?, ?, 'ACTIVE', 1, 'owner', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?)")) { + insert.setInt(1, id); insert.setString(2, "recall-" + id); insert.setString(3, type); insert.setString(4, body); insert.setInt(5, deleted); insert.executeUpdate(); + } + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java b/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java new file mode 100644 index 0000000..5ff43a0 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/migration/RecallStorageMigrationTest.java @@ -0,0 +1,54 @@ +package com.guo.learningprogresstracker.migration; + +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Test; +import java.sql.*; +import java.util.UUID; +import static org.junit.jupiter.api.Assertions.*; + +class RecallStorageMigrationTest { + @Test void removesAllOldRecallHistoryAndKeepsLearningAndTagMaps() throws Exception { + String url = "jdbc:h2:mem:recall-reset-" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;NON_KEYWORDS=USER;DB_CLOSE_DELAY=-1"; + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261115.5").load().migrate(); + try (Connection connection = DriverManager.getConnection(url, "sa", ""); Statement statement = connection.createStatement()) { + statement.executeUpdate("INSERT INTO review_recalls(recall_num,scope_type,status,revision,created_by,created_time,last_modified_time,document_json,scope_key) VALUES ('old','TAG','ACTIVE',3,'u',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'{\"expressionVersions\":[\"old content\"]}','scope')"); + statement.executeUpdate("INSERT INTO review_recall_records(task_num,recall_content,created_time) VALUES ('task','old recall',CURRENT_TIMESTAMP)"); + statement.executeUpdate("INSERT INTO review_standard_mind_maps(task_num,title,content,created_time) VALUES ('task','learning map','{}',CURRENT_TIMESTAMP)"); + statement.executeUpdate("INSERT INTO review_tag_mind_maps(scope_key,combine_mode,tag_names,title,content,created_time) VALUES ('scope','UNION','[\"A\"]','tag map','{}',CURRENT_TIMESTAMP)"); + for (String type : new String[]{"RECALL_COMPARE", "TAG_RECALL_COMPARE", "RECALL_CHECK", "RECALL_HINT", "MIND_MAP"}) { + statement.executeUpdate("INSERT INTO ai_tasks(task_num,ai_type,target_num,status,created_time) VALUES ('" + type + "','" + type + "','target','SUCCEEDED',CURRENT_TIMESTAMP)"); + } + } + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").load().migrate(); + try (Connection connection = DriverManager.getConnection(url, "sa", ""); Statement statement = connection.createStatement()) { + assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recalls")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM information_schema.tables WHERE table_name='review_recall_records'")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM information_schema.columns WHERE table_name='review_recalls' AND column_name='revision'")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM information_schema.columns WHERE table_name='review_recall_requests' AND column_name='semantic_key'")); + assertEquals(1, count(statement, "SELECT COUNT(*) FROM review_standard_mind_maps")); + assertEquals(1, count(statement, "SELECT COUNT(*) FROM review_tag_mind_maps")); + assertEquals(1, count(statement, "SELECT COUNT(*) FROM ai_tasks WHERE ai_type='MIND_MAP'")); + assertEquals(1, count(statement, "SELECT COUNT(*) FROM ai_tasks")); + } + } + @Test void clearsRecallDataAndRecallAiTasksWrittenBeforeTheBreakingSchema() throws Exception { + String url = "jdbc:h2:mem:recall-clear-" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;NON_KEYWORDS=USER;DB_CLOSE_DELAY=-1"; + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").target("20261116.1").load().migrate(); + try (Connection connection = DriverManager.getConnection(url, "sa", ""); Statement statement = connection.createStatement()) { + statement.executeUpdate("INSERT INTO review_recalls(recall_num,scope_type,status,scope_key,created_by,created_time,last_modified_time,document_json) VALUES ('old','TAG','ACTIVE','scope','u',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,'{}')"); + statement.executeUpdate("INSERT INTO review_recall_requests(recall_num,task_num,created_by,created_time,last_modified_time) VALUES ('old','AI1','u',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)"); + statement.executeUpdate("INSERT INTO review_recall_receipts(receipt_key,payload_hash,recall_num,created_by,created_time,last_modified_time) VALUES ('k','h','old','u',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)"); + statement.executeUpdate("INSERT INTO ai_tasks(task_num,ai_type,target_num,status,created_time) VALUES ('AI1','RECALL_HINT','old','SUCCEEDED',CURRENT_TIMESTAMP)"); + statement.executeUpdate("INSERT INTO ai_tasks(task_num,ai_type,target_num,status,created_time) VALUES ('AI2','MIND_MAP','task','SUCCEEDED',CURRENT_TIMESTAMP)"); + } + Flyway.configure().dataSource(url, "sa", "").locations("classpath:db/migration").load().migrate(); + try (Connection connection = DriverManager.getConnection(url, "sa", ""); Statement statement = connection.createStatement()) { + assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recalls")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recall_requests")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM review_recall_receipts")); + assertEquals(0, count(statement, "SELECT COUNT(*) FROM ai_tasks WHERE ai_type IN ('RECALL_HINT','RECALL_CHECK')")); + assertEquals(1, count(statement, "SELECT COUNT(*) FROM ai_tasks")); + } + } + int count(Statement statement, String sql) throws SQLException { try (ResultSet rows = statement.executeQuery(sql)) { rows.next(); return rows.getInt(1); } } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/AiServiceClientAttributionTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/AiServiceClientAttributionTest.java similarity index 97% rename from src/test/java/com/guo/learningprogresstracker/service/impl/AiServiceClientAttributionTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/AiServiceClientAttributionTest.java index d1527fd..5b3b716 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/AiServiceClientAttributionTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/AiServiceClientAttributionTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import cn.dev33.satoken.SaManager; import cn.dev33.satoken.context.SaTokenContext; @@ -14,6 +14,7 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; /** * AiServiceClient 的用量归属标记测试(契约 v2 第 1 节)。 diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/AiServiceClientTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/AiServiceClientTest.java similarity index 87% rename from src/test/java/com/guo/learningprogresstracker/service/impl/AiServiceClientTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/AiServiceClientTest.java index 92dcb34..49e1dfb 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/AiServiceClientTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/AiServiceClientTest.java @@ -1,6 +1,5 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; -import com.fasterxml.jackson.databind.JsonNode; import com.guo.learningprogresstracker.dto.MindMapFragmentPayload; import com.guo.learningprogresstracker.dto.ReportSections; import com.guo.learningprogresstracker.support.TestHttpServer; @@ -52,7 +51,6 @@ class AiServiceClientTest extends TestHttpServer { client.init(); assertTrue(client.aggregateReport("任务", List.of("片段"), null).isEmpty()); assertTrue(client.generateMindMap("任务", "描述", fragments("报告"), List.of()).isEmpty()); - assertTrue(client.compareRecall("任务", "标准大纲", "回忆大纲").isEmpty()); } // ============ aggregateReport ============ @@ -115,20 +113,6 @@ class AiServiceClientTest extends TestHttpServer { assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); } - // ============ compareRecall ============ - - @Test - void compareRecall_success_returnsJsonResult() { - route("POST", "/ai/tasks", 201, "{\"taskId\":\"t5\"}"); - route("GET", "/ai/tasks/t5", 200, - "{\"status\":\"done\",\"result\":{\"matches\":[],\"evaluation\":\"ok\"}}"); - AiServiceClient client = newClient(baseUrl(), 2); - - Optional result = client.compareRecall("任务A", "标准大纲", "回忆大纲"); - assertTrue(result.isPresent()); - assertEquals("ok", result.get().path("evaluation").asText()); - } - // ============ 提交阶段失败 ============ @Test @@ -136,7 +120,7 @@ class AiServiceClientTest extends TestHttpServer { route("POST", "/ai/tasks", 500, "server error body"); AiServiceClient client = newClient(baseUrl(), 1); - assertTrue(client.compareRecall("任务A", "标准大纲", "回忆大纲").isEmpty()); + assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); } @Test @@ -144,7 +128,7 @@ class AiServiceClientTest extends TestHttpServer { route("POST", "/ai/tasks", 201, "{\"message\":\"accepted\"}"); AiServiceClient client = newClient(baseUrl(), 1); - assertTrue(client.compareRecall("任务A", "标准大纲", "回忆大纲").isEmpty()); + assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); } @Test @@ -170,7 +154,7 @@ class AiServiceClientTest extends TestHttpServer { route("GET", "/ai/tasks/t8", 200, "{\"status\":\"failed\",\"error\":\"模型超时\"}"); AiServiceClient client = newClient(baseUrl(), 2); - assertTrue(client.compareRecall("任务A", "标准大纲", "回忆大纲").isEmpty()); + assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); } @Test @@ -179,7 +163,7 @@ class AiServiceClientTest extends TestHttpServer { route("GET", "/ai/tasks/t9", 404, "{\"error\":\"not found\"}"); AiServiceClient client = newClient(baseUrl(), 2); - assertTrue(client.compareRecall("任务A", "标准大纲", "回忆大纲").isEmpty()); + assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); } @Test @@ -188,7 +172,7 @@ class AiServiceClientTest extends TestHttpServer { route("GET", "/ai/tasks/t10", 200, "{\"status\":\"weird\"}"); AiServiceClient client = newClient(baseUrl(), 2); - assertTrue(client.compareRecall("任务A", "标准大纲", "回忆大纲").isEmpty()); + assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); } @Test @@ -198,7 +182,7 @@ class AiServiceClientTest extends TestHttpServer { AiServiceClient client = newClient(baseUrl(), 1); long start = System.currentTimeMillis(); - Optional result = client.compareRecall("任务A", "标准大纲", "回忆大纲"); + Optional result = client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()); long elapsed = System.currentTimeMillis() - start; assertTrue(result.isEmpty()); @@ -228,7 +212,7 @@ class AiServiceClientTest extends TestHttpServer { AiServiceClient client = newClient(baseUrl(), 1); long start = System.currentTimeMillis(); - Optional result = client.compareRecall("任务A", "标准大纲", "回忆大纲"); + Optional result = client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()); long elapsed = System.currentTimeMillis() - start; assertTrue(result.isEmpty()); @@ -275,6 +259,5 @@ class AiServiceClientTest extends TestHttpServer { assertTrue(client.aggregateReport("任务A", List.of("片段"), null).isEmpty()); assertTrue(client.generateMindMap("任务A", "描述", fragments("报告内容"), List.of()).isEmpty()); - assertTrue(client.compareRecall("任务A", "标准大纲", "回忆大纲").isEmpty()); } } diff --git a/src/test/java/com/guo/learningprogresstracker/service/ai/AiTaskRunnerTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/AiTaskRunnerTest.java new file mode 100644 index 0000000..1490c06 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/AiTaskRunnerTest.java @@ -0,0 +1,55 @@ +package com.guo.learningprogresstracker.service.ai; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.guo.learningprogresstracker.config.AiTaskProperties; +import com.guo.learningprogresstracker.entity.AiTaskEntity; +import com.guo.learningprogresstracker.service.AiTaskService; +import com.guo.learningprogresstracker.service.event.AiTaskSubmittedEvent; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.Optional; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class AiTaskRunnerTest { + AiTaskService service = mock(AiTaskService.class); + AiTaskHandlerRegistry registry = mock(AiTaskHandlerRegistry.class); + AiTaskRunner runner = new AiTaskRunner(service, registry, new AiTaskProperties()); + + @Test void wrappedRecallFailureKeepsCodeAndNeverLogsUnsafeCause() { + Logger logger = (Logger) LoggerFactory.getLogger(AiTaskRunner.class); + ListAppender logs = new ListAppender<>(); logs.start(); logger.addAppender(logs); + try { + AiTaskEntity task = task("RECALL_CHECK"); + when(registry.execute(task)).thenThrow(new IllegalStateException("PRIVATE-PROMPT", new RecallAiFailure("AI_OUTPUT_LIMIT", "SECRET-KEY"))); + runner.onTaskSubmitted(new AiTaskSubmittedEvent(1)); + assertEquals("AI_OUTPUT_LIMIT", task.getErrorCode()); + verify(service).markFailed(task, RecallAiFailure.forCode("AI_OUTPUT_LIMIT").getMessage()); + verify(service, never()).markSucceeded(any(), any()); + assertTrue(logs.list.stream().anyMatch(e -> e.getFormattedMessage().contains("AI_OUTPUT_LIMIT"))); + assertTrue(logs.list.stream().allMatch(e -> e.getThrowableProxy() == null && !e.getFormattedMessage().contains("PRIVATE") && !e.getFormattedMessage().contains("SECRET"))); + } finally { logger.detachAppender(logs); logs.stop(); } + } + @Test void unexpectedRecallFailureRemainsARequestFailure() { + AiTaskEntity task = task("RECALL_HINT"); when(registry.execute(task)).thenThrow(new IllegalStateException("PRIVATE")); + runner.onTaskSubmitted(new AiTaskSubmittedEvent(1)); + assertEquals("AI_REQUEST_FAILED", task.getErrorCode()); + verify(service).markFailed(task, RecallAiFailure.forCode("AI_REQUEST_FAILED").getMessage()); + } + @Test void legacyFailureBehaviorIsUnchanged() { + AiTaskEntity task = task("GUIDANCE"); when(registry.execute(task)).thenThrow(new IllegalStateException("legacy")); + runner.onTaskSubmitted(new AiTaskSubmittedEvent(1)); + assertNull(task.getErrorCode()); verify(service).markFailed(task, "生成失败了,请稍后再试"); + reset(registry, service); task = task("REPORT_DRAFT"); + when(registry.execute(task)).thenThrow(new AiTaskFailedException("已有业务文案")); + runner.onTaskSubmitted(new AiTaskSubmittedEvent(1)); + verify(service).markFailed(task, "已有业务文案"); assertNull(task.getErrorCode()); + } + AiTaskEntity task(String type) { + AiTaskEntity task = new AiTaskEntity(); task.setId(1); task.setAiType(type); task.setTaskNum("local-task-id"); task.setCreatedBy("owner"); + when(service.claimTask(1)).thenReturn(Optional.of(task)); return task; + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageClientTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/AiUsageClientTest.java similarity index 98% rename from src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageClientTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/AiUsageClientTest.java index d3e9468..86ab98b 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageClientTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/AiUsageClientTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.config.AiUsageProperties; import com.guo.learningprogresstracker.dto.AiUsageBalance; diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/BuiltinMindMapGeneratorTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/BuiltinMindMapGeneratorTest.java similarity index 99% rename from src/test/java/com/guo/learningprogresstracker/service/impl/BuiltinMindMapGeneratorTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/BuiltinMindMapGeneratorTest.java index c408fd6..dd23a39 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/BuiltinMindMapGeneratorTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/BuiltinMindMapGeneratorTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.TaskApplicationEntity; diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGeneratorTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/MindMapOutlineGeneratorTest.java similarity index 98% rename from src/test/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGeneratorTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/MindMapOutlineGeneratorTest.java index cb4eafe..fe6e119 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapOutlineGeneratorTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/MindMapOutlineGeneratorTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.TaskEntity; diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapReportContextLoaderTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/MindMapReportContextLoaderTest.java similarity index 98% rename from src/test/java/com/guo/learningprogresstracker/service/impl/MindMapReportContextLoaderTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/MindMapReportContextLoaderTest.java index 4926ad4..1808535 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/MindMapReportContextLoaderTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/MindMapReportContextLoaderTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.dto.MindMapReportContext; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; diff --git a/src/test/java/com/guo/learningprogresstracker/service/ai/RecallAiClientTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/RecallAiClientTest.java new file mode 100644 index 0000000..d84a902 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/RecallAiClientTest.java @@ -0,0 +1,132 @@ +package com.guo.learningprogresstracker.service.ai; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.guo.learningprogresstracker.common.TenantContext; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.*; + +/** Real loopback HTTP tests only; never contact an LLM or a configured external data source. */ +class RecallAiClientTest { + ObjectMapper mapper=new ObjectMapper().findAndRegisterModules(); RecallJson json=new RecallJson(mapper); + HttpServer server; RecallAiClient client; + AtomicReference method=new AtomicReference<>(),contentType=new AtomicReference<>(),body=new AtomicReference<>(),auth=new AtomicReference<>(); + int code=201; String response="{\"taskId\":\"remote-1\",\"status\":\"pending\",\"reused\":false}"; + @BeforeEach void start() throws Exception { + server=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0); + server.createContext("/ai/tasks", exchange->{ + method.set(exchange.getRequestMethod()); contentType.set(exchange.getRequestHeaders().getFirst("Content-Type")); auth.set(exchange.getRequestHeaders().getFirst("x-api-token")); + body.set(new String(exchange.getRequestBody().readAllBytes(),StandardCharsets.UTF_8)); + int status="DELETE".equals(exchange.getRequestMethod()) && contentType.get()!=null ? 400 : code; + byte[] bytes=response.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(status,status==204?-1:bytes.length); + if(status!=204)exchange.getResponseBody().write(bytes); exchange.close(); + }); server.start(); client=new RecallAiClient(json,"http://127.0.0.1:"+server.getAddress().getPort(),"service-secret",5,70); + } + @AfterEach void stop(){server.stop(0);} + RecallAiParams input() {return new RecallAiParams(1,"recall-v1",new AiScope("TASK","任务",List.of(),null),new AiExpression(1,new AiExpressionNode("root","学习内容","",List.of(),List.of())),null,List.of(),new Limits(3,5,12),List.of());} + @Test void submitPosts201ContractAndSeparatesCallerIdentityFromPrompt() throws Exception { + String id=TenantContext.callAs("opaque-account",null,()->client.submit("recall-check",input(),"semantic-and-task-digest")); + assertEquals("remote-1",id); assertEquals("POST",method.get()); assertEquals("application/json",contentType.get()); assertEquals("service-secret",auth.get()); + JsonNode payload=mapper.readTree(body.get()); assertEquals("opaque-account",payload.path("callerRef").asText()); assertEquals("semantic-and-task-digest",payload.path("idempotencyKey").asText()); assertFalse(payload.path("force").asBoolean()); + assertFalse(payload.path("params").toString().contains("opaque-account")); assertFalse(payload.path("params").toString().contains("service-secret")); + } + @Test void deleteIsBodylessAndOmitsJsonContentType_fastifyCompatible() { + code=204; response=""; assertTrue(client.purge("remote-1")); assertEquals("DELETE",method.get()); assertEquals("",body.get()); assertNull(contentType.get()); assertEquals("service-secret",auth.get()); + code=404; response="already purged"; assertTrue(client.purge("remote-1")); + } + @Test void pollingDoesNotSendJsonContentTypeAndRejectsEmptySuccess() { + code=200; response="{\"status\":\"done\",\"result\":{\"schemaVersion\":1}}"; + assertEquals(1,client.await("remote-1",()->true).path("schemaVersion").asInt()); assertEquals("GET",method.get()); assertNull(contentType.get()); + response="{\"status\":\"done\",\"result\":{}}"; assertEquals("INVALID_AI_RESULT",assertThrows(RecallAiFailure.class,()->client.await("remote-1",()->true)).getCode()); + } + @Test void remoteQuotaAndMalformedPayloadAreFailuresWithoutEchoingLearningText() { + code=200; response="{\"status\":\"failed\",\"errorCode\":\"AI_REQUEST_FAILED\",\"error\":\"402 quota with PRIVATE-LEARNING-PROMPT\"}"; + RecallAiFailure quota=assertThrows(RecallAiFailure.class,()->client.await("remote-1",()->true)); assertTrue(quota.getMessage().contains("额度")); assertFalse(quota.getMessage().contains("PRIVATE")); + response="{\"status\":\"mystery\",\"error\":\"PRIVATE\"}"; assertEquals("INVALID_AI_RESULT",assertThrows(RecallAiFailure.class,()->client.await("remote-1",()->true)).getCode()); + } + @Test void keepsOnlyThePhaseWhenAiReportsAFieldLevelReason() { + code=200; response="{\"status\":\"failed\",\"errorCode\":\"INVALID_AI_RESULT\",\"error\":\"AI 返回格式或依据不可信,未进行语义检查,请重试(未通过:结构与字段:缺少 findings)\"}"; + RecallAiFailure failure=assertThrows(RecallAiFailure.class,()->client.await("remote-1",()->true)); + assertEquals("INVALID_AI_RESULT",failure.getCode()); assertTrue(failure.getMessage().contains("结构与字段")); + assertFalse(failure.getMessage().contains("findings")); assertFalse(failure.getMessage().contains("请重试")); + } + @Test void sourceRedactionDiscardsPendingRemoteResultAndDeadlineIsClassified() { + code=204; response=""; assertEquals("SOURCE_REDACTED",assertThrows(RecallAiFailure.class,()->client.await("remote-1",()->false)).getCode()); assertEquals("DELETE",method.get()); + RecallAiClient expired=new RecallAiClient(json,"http://127.0.0.1:"+server.getAddress().getPort(),"service-secret",0,70); + assertEquals("AI_TIMEOUT",assertThrows(RecallAiFailure.class,()->expired.await("remote-1",()->true)).getCode()); + } + @Test void purgeFailureIsActuallyLoggedAsMetadata_neverClaimsRemoteErasure() { + Logger logger=(Logger)LoggerFactory.getLogger(RecallAiClient.class); ListAppender appender=new ListAppender<>(); appender.start(); logger.addAppender(appender); + try { + code=500; response="PRIVATE-RESULT"; assertFalse(client.purge("remote-1")); + String logs=String.join("\n",appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList()); + assertTrue(logs.contains("purge failed")); assertTrue(logs.contains("status=500")); assertTrue(logs.contains("BE already redacted")); assertFalse(logs.contains("PRIVATE-RESULT")); assertFalse(logs.contains("service-secret")); + } finally {logger.detachAppender(appender); appender.stop();} + } + @ParameterizedTest + @ValueSource(strings = {"AI_UNAVAILABLE", "AI_TIMEOUT", "AI_REQUEST_FAILED", "INVALID_AI_RESULT", "SOURCE_REDACTED", + "AI_AUTH_FAILED", "AI_QUOTA_EXCEEDED", "AI_RATE_LIMITED", "AI_OUTPUT_LIMIT", "AI_EMPTY_RESPONSE"}) + void remoteCodesAreAllowlistedAndBodyNeverEscapes(String expected) { + code = 200; response = "{\"status\":\"failed\",\"errorCode\":\"" + expected + "\",\"error\":\"PRIVATE api-key-secret learning text\"}"; + RecallAiFailure failure = assertThrows(RecallAiFailure.class, () -> client.await("remote-1", () -> true)); + assertEquals(expected, failure.getCode()); assertFalse(failure.getMessage().contains("PRIVATE")); + } + @ParameterizedTest + @CsvSource({"401,AI_AUTH_FAILED", "403,AI_AUTH_FAILED", "402,AI_QUOTA_EXCEEDED", "429,AI_RATE_LIMITED", + "408,AI_TIMEOUT", "504,AI_TIMEOUT", "503,AI_UNAVAILABLE", "400,AI_REQUEST_FAILED"}) + void httpFailuresHaveSafeCategoriesForSubmitAndPoll(int status, String expected) { + code = status; response = "PRIVATE api-key-secret learning text"; + assertEquals(expected, assertThrows(RecallAiFailure.class, () -> TenantContext.callAs("user", null, + () -> client.submit("recall-hint", input(), "key"))).getCode()); + assertEquals(expected, assertThrows(RecallAiFailure.class, () -> client.await("remote-1", () -> true)).getCode()); + } + @ParameterizedTest + @CsvSource({"AI_REQUEST_FAILED(timeout),AI_TIMEOUT", "AI_REQUEST_FAILED(auth),AI_AUTH_FAILED", + "AI_REQUEST_FAILED(insufficient_quota),AI_QUOTA_EXCEEDED", "AI_REQUEST_FAILED(rate_limited),AI_RATE_LIMITED", + "HTTP 504 gateway timeout,AI_TIMEOUT", "401 invalid credentials,AI_AUTH_FAILED", + "AI_REQUEST_FAILED(upstream_error),AI_REQUEST_FAILED"}) + void legacyMachineCategoriesRetainDiagnosis(String error, String expected) { + code = 200; + response = json.write(Map.of("status", "failed", "errorCode", "AI_REQUEST_FAILED", "error", error)); + RecallAiFailure failure = assertThrows(RecallAiFailure.class, () -> client.await("remote-1", () -> true)); + assertEquals(expected, failure.getCode()); + assertEquals(RecallAiFailure.forCode(expected).getMessage(), failure.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {"author wrote about authentication", "PRIVATE quota and balance lesson", + "PRIVATE api key explanation", "upstream_error at record 401", "40100 private record", + "AI_REQUEST_FAILED(upstream_error) PRIVATE auth quota 429"}) + void arbitraryRemoteTextDoesNotInventAuthQuotaOrRateLimitDiagnosis(String error) { + code = 200; + response = json.write(Map.of("status", "failed", "errorCode", "AI_REQUEST_FAILED", "error", error)); + RecallAiFailure failure = assertThrows(RecallAiFailure.class, () -> client.await("remote-1", () -> true)); + assertEquals("AI_REQUEST_FAILED", failure.getCode()); + assertEquals(RecallAiFailure.forCode("AI_REQUEST_FAILED").getMessage(), failure.getMessage()); + } + + @Test void malformedJsonAndUnknownRemoteCodesDoNotLeakOrPretendSuccess() { + code = 200; response = "PRIVATE malformed response"; + assertEquals("INVALID_AI_RESULT", assertThrows(RecallAiFailure.class, () -> client.await("remote-1", () -> true)).getCode()); + code = 201; + assertEquals("INVALID_AI_RESULT", assertThrows(RecallAiFailure.class, () -> TenantContext.callAs("user", null, + () -> client.submit("recall-check", input(), "key"))).getCode()); + code = 200; response = "{\"status\":\"failed\",\"errorCode\":\"PRIVATE-secret\",\"error\":\"upstream_error\"}"; + RecallAiFailure failure = assertThrows(RecallAiFailure.class, () -> client.await("remote-1", () -> true)); + assertEquals("AI_REQUEST_FAILED", failure.getCode()); assertFalse(failure.getMessage().contains("PRIVATE")); + } + +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/ai/RecallAiResultValidatorTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/RecallAiResultValidatorTest.java new file mode 100644 index 0000000..19bd020 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/RecallAiResultValidatorTest.java @@ -0,0 +1,182 @@ +package com.guo.learningprogresstracker.service.ai; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import java.util.*; +import org.junit.jupiter.api.Test; +import com.guo.learningprogresstracker.service.recall.RecallReferenceLoader; + +/** + * lpt-ai 已保证结构与语义(见 lpt-ai 的 {@code recall.test.ts}),本类只验证本服务自己守的那条线: + * 引文与表达依据能否在本次输入里按偏移逐字取回;结构对不上时 fail-closed。 + */ +class RecallAiResultValidatorTest { + RecallJson json = new RecallJson(new ObjectMapper().findAndRegisterModules()); + RecallAiResultValidator validator = new RecallAiResultValidator(json); + AiExpression expression = new AiExpression(1, new AiExpressionNode("stable", "中文🙂知识", "条件", List.of(), List.of())); + ReferenceSource source = RecallReferenceLoader.source( + "FRAGMENT", + "1", + "碎片", + "中文🙂知识", + new StudyReportFragmentsEntity(), + new RecallReferenceLoader.SourceContext("PRIMARY", "SESSION", "s", List.of())); + ReferenceUnit unit = RecallReferenceLoader.units(source).get(0); + ReferenceSnapshot full = new ReferenceSnapshot("AVAILABLE", List.of(source), List.of(unit), List.of()); + AiReferenceUnit aiUnit = new AiReferenceUnit( + unit.unitId(), + source.sourceId(), + source.type(), + unit.role(), + source.title(), + unit.start(), + unit.end(), + unit.text(), + List.of()); + + RecallAiParams input(String form) { + return new RecallAiParams( + 1, + "recall-v1", + new AiScope("TASK", "任务", List.of(), null), + expression, + form, + List.of(aiUnit), + new Limits(3, 5, 12), + List.of()); + } + + Citation cite() { + return new Citation(unit.unitId(), 0, unit.text().length(), unit.text()); + } + + ExpressionEvidence evidence() { + return new ExpressionEvidence( + "stable", + "TITLE", + 0, + expression.root().title().length(), + expression.root().title()); + } + + Finding finding(String category, List citations, List evidence) { + return new Finding("finding", category, "线索", "解释", citations, evidence); + } + + RecallAiResult result(List assessments, List hints, List findings) { + return new RecallAiResult( + 1, + hints.isEmpty() ? "CHECK" : "HINT", + "controlled-stub", + "COMPLETE", + assessments, + hints, + findings, + List.of()); + } + + RecallAiResult verify(RecallAiResult result, String form) { + return validator.validate(json.tree(result), input(form), full); + } + + void invalid(RecallAiResult result) { + assertEquals( + "INVALID_AI_RESULT", + assertThrows(RecallAiFailure.class, () -> verify(result, null)).getCode()); + } + + @Test + void exactChineseEmojiCitationsAndEvidencePass() { + RecallAiResult checked = verify( + result(List.of(), List.of(), List.of(finding("EXPRESSED", List.of(cite()), List.of(evidence())))), + null); + assertEquals("EXPRESSED", checked.findings().get(0).category()); + } + + @Test + void forgedQuoteUnknownUnitAndSplitSurrogateStillFail() { + invalid(result( + List.of(), + List.of(), + List.of(finding("POSSIBLY_MISSING", List.of(new Citation(unit.unitId(), 0, 2, "假的")), List.of())))); + invalid(result( + List.of(), + List.of(), + List.of(finding("POSSIBLY_MISSING", List.of(new Citation("unknown", 0, 2, "中文")), List.of())))); + invalid(result( + List.of(), + List.of(), + List.of(finding("POSSIBLY_MISSING", List.of(new Citation(unit.unitId(), 2, 3, "\uD83D")), List.of())))); + } + + @Test + void evidenceOutsideSubmittedNodesOrWithoutExactSliceFails() { + invalid(result( + List.of(), + List.of(), + List.of(finding( + "EXPRESSED", + List.of(cite()), + List.of(new ExpressionEvidence("missing", "TITLE", 0, 2, "中文")))))); + invalid(result( + List.of(), + List.of(), + List.of(finding( + "EXPRESSED", + List.of(cite()), + List.of(new ExpressionEvidence("stable", "NOTES", 0, 2, "中文")))))); + } + + @Test + void hintCitationsAreCheckedTheSameWay() { + HintItem hint = new HintItem("h", "KEYWORD", "起点", null, List.of(), List.of(cite())); + assertEquals( + 1, + verify(result(List.of(), List.of(hint), List.of()), "KEYWORD") + .hints() + .size()); + HintItem forged = + new HintItem("h", "KEYWORD", "起点", null, List.of(), List.of(new Citation(unit.unitId(), 0, 2, "冒名"))); + assertEquals( + "INVALID_AI_RESULT", + assertThrows( + RecallAiFailure.class, + () -> verify(result(List.of(), List.of(forged), List.of()), "KEYWORD")) + .getCode()); + } + /** 结构层面 lpt-ai 已拒绝,本服务不再重复判定,只按原样保留(越权拒绝会和 AI 服务分叉)。 */ + @Test + void structureAcceptedUpstreamIsNotReJudgedHere() { + HintItem extra = new HintItem("h", "KEYWORD", "起点", null, List.of(), List.of(cite())); + RecallAiResult unnormalized = + new RecallAiResult(1, "HINT", "stub", "PARTIAL", List.of(), List.of(extra), List.of(), List.of("上限说明")); + assertEquals("PARTIAL", verify(unnormalized, "KEYWORD").analysisStatus()); + } + + @Test + void mappedResultKeepsProducingServiceShape() { + RecallAiResult checked = validator.validate( + json.tree(result( + List.of(), List.of(), List.of(finding("EXPRESSED", List.of(cite()), List.of(evidence()))))), + input(null), + full); + assertEquals( + List.of("EXPRESSED"), + checked.findings().stream().map(Finding::category).toList()); + assertTrue(checked.hints().isEmpty()); + } + + @Test + void resultsThatDoNotMatchAgreedStructureFailClosed() { + ObjectNode raw = (ObjectNode) json.tree(result(List.of(), List.of(), List.of())); + raw.put("hints", "not-an-array"); + assertEquals( + "INVALID_AI_RESULT", + assertThrows(RecallAiFailure.class, () -> validator.validate(raw, input(null), full)) + .getCode()); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/RemoteAiMindMapClientTest.java b/src/test/java/com/guo/learningprogresstracker/service/ai/RemoteAiMindMapClientTest.java similarity index 99% rename from src/test/java/com/guo/learningprogresstracker/service/impl/RemoteAiMindMapClientTest.java rename to src/test/java/com/guo/learningprogresstracker/service/ai/RemoteAiMindMapClientTest.java index a611245..b5e5dbf 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/RemoteAiMindMapClientTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/ai/RemoteAiMindMapClientTest.java @@ -1,4 +1,4 @@ -package com.guo.learningprogresstracker.service.impl; +package com.guo.learningprogresstracker.service.ai; import com.guo.learningprogresstracker.dto.MindMapFragmentPayload; import com.guo.learningprogresstracker.dto.MindMapReportContext; diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskIntegrationTest.java index d9f5b8c..f7c7b98 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskIntegrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskIntegrationTest.java @@ -31,6 +31,8 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; /** * AI 链路的落库集成测试(AI-01 / AI-02 / AI-04)。 @@ -182,33 +184,9 @@ class AiTaskIntegrationTest { } @Test - void recallCompareTask_completesAndPersistsRecallRecord() throws Exception { - String taskNum = createTaskWithReport(); - // 先让标准导图存在,回忆对比才有基准 - AiTaskResponse mindMapTask = aiTaskService.submit(request("MIND_MAP", taskNum, Map.of("mode", "full"))); - awaitTerminal(mindMapTask.getTaskNum()); - - when(aiServiceClient.compareRecall(anyString(), anyString(), anyString())).thenAnswer(invocation -> { - aiCalled.set(true); - transactionActiveDuringAiCall.set(TransactionSynchronizationManager.isActualTransactionActive()); - Thread.sleep(50); - JsonNode json = objectMapper.readTree(""" - {"matches":[{"standardTitle":"子知识点"}],"missedTitles":[],"extraNodes":[],"evaluation":"不错"} - """); - return Optional.of(json); - }); - - AiTaskResponse submitted = aiTaskService.submit(request("RECALL_COMPARE", taskNum, - Map.of("recallOutline", "- 根主题\n\t- 子知识点", - "reviewStartedAt", java.time.LocalDateTime.now().minusMinutes(2).toString(), - "reviewDurationSeconds", 120))); - - AiTaskResponse done = awaitTerminal(submitted.getTaskNum()); - - assertFalse(transactionActiveDuringAiCall.get(), "AI-01:回忆对比的 AI 调用也必须在事务之外"); - assertEquals(AiTaskStatusEnum.SUCCEEDED.name(), done.getStatus(), done.getErrorMessage()); - assertNotNull(done.getResult().get("recallRecordId"), "回忆记录应已落库"); - assertNotNull(done.getResult().get("recallRatio"), "覆盖率应随结果返回"); + void recallCompareTask_rejectsLegacyScoreWrites() { + assertThrows(com.guo.learningprogresstracker.exception.ErrorParameterException.class, + () -> aiTaskService.submit(request("RECALL_COMPARE", "old-task", Map.of("recallOutline", "旧表达")))); } @Test diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImplTest.java index 6e08635..0602111 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/AiTaskServiceImplTest.java @@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; +import com.guo.learningprogresstracker.service.ai.RecallAiService; /** * AI 异步任务服务单元测试(AI-02 / AI-04)。 @@ -52,7 +53,7 @@ class AiTaskServiceImplTest { private final AiTaskProperties properties = new AiTaskProperties(); private void injectDependencies() { - service = new AiTaskServiceImpl(aiTaskMapper, objectMapper, properties, eventPublisher); + service = new AiTaskServiceImpl(aiTaskMapper, objectMapper, properties, eventPublisher, mock(RecallAiService.class)); } private static AiTaskSubmitRequest request(String type, String targetNum, Map params) { @@ -208,6 +209,17 @@ class AiTaskServiceImplTest { assertEquals(AiTaskStatusEnum.RUNNING.name(), claimed.get(0).getStatus()); } + @Test + void claimPendingTasks_reclaimsStuckRowsAtMostOncePerMinute() { + injectDependencies(); + when(aiTaskMapper.selectPendingTasks(anyInt())).thenReturn(List.of()); + + service.claimPendingTasks(10); + service.claimPendingTasks(10); + + verify(aiTaskMapper, times(1)).reclaimStuckTasks(any(), any()); + } + @Test void markSucceeded_writesResultPayload() { injectDependencies(); diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceUnitTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceUnitTest.java index f16a816..351a0b9 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceUnitTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/AiUsageServiceUnitTest.java @@ -44,6 +44,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.guo.learningprogresstracker.service.ai.AiUsageClient; /** * AiUsageServiceImpl 纯单元测试:白名单口径与汇总口径(mock Mapper / UserService)。 diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/ExportServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/ExportServiceImplTest.java index 0c7362a..9c55467 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/ExportServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/ExportServiceImplTest.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.guo.learningprogresstracker.dto.ExportResult; -import com.guo.learningprogresstracker.dto.ReviewFeedItem; import com.guo.learningprogresstracker.dto.ReviewTaskStats; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; @@ -36,7 +35,6 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; /** @@ -84,9 +82,12 @@ class ExportServiceImplTest { void exportTask_markdown_containsReportsAndFragments() throws Exception { when(tasksMapper.selectList(any())).thenReturn(List.of(task("TASK-1", "学习 Vue3"))); when(reviewService.getReviewTaskStats("TASK-1")).thenReturn(stats("TASK-1")); - when(reviewService.getTaskReview("TASK-1")).thenReturn(List.of( - feedItem(1, "SESSION-1", "REPORT", "报告正文", LocalDateTime.of(2026, 10, 1, 20, 15)), - feedItem(2, "SESSION-1", "FRAGMENT", "碎片正文", LocalDateTime.of(2026, 10, 1, 20, 18)))); + when(studySessionsMapper.selectList(any())).thenReturn(List.of(session("SESSION-1", "TASK-1"))); + StudyReportsEntity report = new StudyReportsEntity(); + report.setId(1); report.setSessionNum("SESSION-1"); report.setFreeSummary("报告正文"); + report.setCreatedTime(LocalDateTime.of(2026, 10, 1, 20, 15)); + when(studyReportsMapper.selectList(any())).thenReturn(List.of(report)); + when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of(fragment("碎片正文"))); ExportResult result = exportService.exportTask("TASK-1", "markdown"); @@ -103,8 +104,7 @@ class ExportServiceImplTest { void exportTask_json_isStructuredAndContainsOriginalText() throws Exception { when(tasksMapper.selectList(any())).thenReturn(List.of(task("TASK-1", "学习 Vue3"))); when(reviewService.getReviewTaskStats("TASK-1")).thenReturn(stats("TASK-1")); - when(reviewService.getTaskReview("TASK-1")).thenReturn(List.of( - feedItem(1, "SESSION-1", "FRAGMENT", "碎片正文", LocalDateTime.of(2026, 10, 1, 20, 18)))); + when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of(fragment("碎片正文"))); ExportResult result = exportService.exportTask("TASK-1", "json"); @@ -138,6 +138,8 @@ class ExportServiceImplTest { StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity(); fragment.setId(2); fragment.setContextNum("SESSION-2"); + fragment.setContextType("SESSION"); + fragment.setOwnerTaskNum("TASK-2"); fragment.setContent("碎片正文"); fragment.setCreatedTime(LocalDateTime.of(2026, 10, 2, 9, 0)); @@ -205,14 +207,14 @@ class ExportServiceImplTest { return stats; } - private static ReviewFeedItem feedItem(int id, String sessionNum, String sourceType, String content, - LocalDateTime createdTime) { - ReviewFeedItem item = new ReviewFeedItem(); - item.setId(id); - item.setContextNum(sessionNum); - item.setSourceType(sourceType); - item.setContent(content); - item.setCreatedTime(createdTime); - return item; + private static StudyReportFragmentsEntity fragment(String content) { + StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity(); + fragment.setId(2); + fragment.setContextType("SESSION"); + fragment.setContextNum("SESSION-1"); + fragment.setOwnerTaskNum("TASK-1"); + fragment.setContent(content); + fragment.setCreatedTime(LocalDateTime.of(2026, 10, 1, 20, 18)); + return fragment; } } diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/FragmentOwnerTagIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/FragmentOwnerTagIntegrationTest.java new file mode 100644 index 0000000..dfcf12e --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/FragmentOwnerTagIntegrationTest.java @@ -0,0 +1,126 @@ +package com.guo.learningprogresstracker.service.impl; + +import cn.dev33.satoken.stp.StpUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; +import com.guo.learningprogresstracker.dto.request.UpdateFragmentsRequest; +import com.guo.learningprogresstracker.entity.*; +import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; +import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.service.*; +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import com.guo.learningprogresstracker.service.recall.RecallReferenceLoader; + +@SpringBootTest +@AutoConfigureMockMvc +class FragmentOwnerTagIntegrationTest { + @Autowired TasksMapper tasks; + @Autowired StudyReportFragmentsMapper fragments; + @Autowired StudySessionsMapper sessions; + @Autowired MarkerMapper markers; + @Autowired MarkerService tags; + @Autowired StudyReportFragmentsService service; + @Autowired GuidanceService guidance; + @Autowired MockMvc mvc; + @SpyBean ReviewTagMindMapService maps; + + @BeforeEach void login() { StpUtil.login("owner-tags-" + UUID.randomUUID()); } + TaskEntity task(String name) { + TaskEntity t = new TaskEntity(); t.setTaskNum(UUID.randomUUID().toString()); t.setTaskName(name); tasks.insert(t); return t; + } + StudyReportFragmentsEntity fragment(String owner) { + StudyReportFragmentsEntity f = new StudyReportFragmentsEntity(); f.setOwnerTaskNum(owner); + f.setContextType("REVIEW"); f.setContextNum(UUID.randomUUID().toString()); f.setContent("知识"); fragments.insert(f); return f; + } + CreateFragmentsRequest request(TaskEntity task) { + StudySessionsEntity session = StudySessionsEntity.initNewSession(); session.setTaskNum(task.getTaskNum()); sessions.insert(session); + CreateFragmentsRequest r = new CreateFragmentsRequest(); r.setContextNum(session.getSessionNum()); r.setContent("学习知识"); return r; + } + List names(StudyReportFragmentsEntity f) { + return tags.listByObject(MarkerObjectTypeEnum.FRAGMENT, f.getId().toString()).stream().filter(m -> "USER".equals(m.getKind())).map(MarkerEntity::getMarkerName).toList(); + } + @Test void learningOwnershipAndGuidanceKeepOrdinaryLongTagsAndNeverRewriteAfterRename() throws Exception { + String longName = "长".repeat(255); + TaskEntity original = task(longName), next = task("Next Name"); + service.createFragments(request(original)); + StudyReportFragmentsEntity learned = fragments.selectList(null).get(0); + assertEquals(List.of(longName), names(learned)); + original.setTaskName("Later Rename"); tasks.updateById(original); + assertEquals(List.of(longName), names(learned)); + UpdateFragmentsRequest unchangedOwner = new UpdateFragmentsRequest(); unchangedOwner.setOwnerTaskNum(original.getTaskNum()); unchangedOwner.setContent("只改正文"); + service.updateFragments(learned.getId(), unchangedOwner); + assertEquals(List.of(longName), names(learned)); + service.assignOwnership(learned.getId(), next.getTaskNum()); + service.assignOwnership(learned.getId(), next.getTaskNum()); + tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, learned.getId().toString(), " NEXT NAME "); + assertEquals(List.of(longName, "Next Name"), names(learned)); + StudyReportFragmentsEntity pending = fragment(null); assertTrue(names(pending).isEmpty()); + service.assignOwnership(pending.getId(), original.getTaskNum()); + assertEquals(List.of("Later Rename"), names(pending)); + UpdateFragmentsRequest update = new UpdateFragmentsRequest(); update.setOwnerTaskNum(next.getTaskNum()); + service.updateFragments(pending.getId(), update); + assertEquals(List.of("Later Rename", "Next Name"), names(pending)); + StudyReportFragmentsEntity harvest = guidance.confirmFragment(guidance.start(next.getTaskNum(), "概念").getGuidanceNum(), "收获", null); + assertEquals(List.of("Next Name"), names(harvest)); + assertTrue(tags.listDictionaryTags().stream().anyMatch(t -> longName.equals(t.getTagName()))); + assertEquals(1, tags.listDictionaryTags().stream().filter(t -> "next name".equals(t.getNormalizedName())).count()); + assertThrows(com.guo.learningprogresstracker.exception.ErrorParameterException.class, + () -> tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, pending.getId().toString(), "长".repeat(256))); + assertDoesNotThrow(() -> RecallReferenceLoader.tagScopeKey(List.of(longName), "UNION")); + assertDoesNotThrow(() -> maps.resolveScope(List.of(longName), "UNION")); + assertThrows(com.guo.learningprogresstracker.exception.RecallBusinessException.class, + () -> RecallReferenceLoader.tagScopeKey(List.of("长".repeat(256)), "UNION")); + } + @Test void failuresRollBackLearningOwnershipUpdateAndGuidanceInsteadOfLeavingUntaggedFragments() throws Exception { + TaskEntity t = task("Must be atomic"); + StudyReportFragmentsEntity pending = fragment(null); + doThrow(new IllegalStateException("simulated tag downstream failure")).when(maps).markStaleForTags(anyCollection()); + assertThrows(IllegalStateException.class, () -> service.createFragments(request(t))); + assertEquals(1, fragments.selectCount(null)); assertEquals(0, markers.selectCount(null)); + assertThrows(IllegalStateException.class, () -> service.assignOwnership(pending.getId(), t.getTaskNum())); + assertNull(fragments.selectById(pending.getId()).getOwnerTaskNum()); assertEquals(0, markers.selectCount(null)); + UpdateFragmentsRequest update = new UpdateFragmentsRequest(); update.setOwnerTaskNum(t.getTaskNum()); update.setContent("changed"); + assertThrows(IllegalStateException.class, () -> service.updateFragments(pending.getId(), update)); + assertNull(fragments.selectById(pending.getId()).getOwnerTaskNum()); assertEquals("知识", fragments.selectById(pending.getId()).getContent()); + String conversation = guidance.start(t.getTaskNum(), "concept").getGuidanceNum(); + assertThrows(IllegalStateException.class, () -> guidance.confirmFragment(conversation, "harvest", null)); + assertEquals(1, fragments.selectCount(null)); assertEquals(0, markers.selectCount(null)); + } + @Test void fragmentUsageHttpFiltersDeletedAndForeignObjectsAndKeepsNoArgumentManagement() throws Exception { + TaskEntity t = task("task"); + StudyReportFragmentsEntity a = fragment(t.getTaskNum()), b = fragment(null), removed = fragment(null); + tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, a.getId().toString(), "Alpha"); + tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, b.getId().toString(), " alpha "); + tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, removed.getId().toString(), "Deleted Fragment"); + fragments.deleteById(removed.getId()); // exercise orphan tags too + tags.addUserTag(MarkerObjectTypeEnum.TASK, t.getTaskNum(), "Task Only"); + tags.createDictionaryTag("Dictionary Only"); + tags.addSystemMarker(MarkerObjectTypeEnum.FRAGMENT, a.getId().toString(), com.guo.learningprogresstracker.enums.SystemMarkerEnum.FROM_GUIDANCE); + MarkerEntity deletedTag = tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, a.getId().toString(), "Deleted Tag"); tags.deleteMarker(deletedTag.getId()); + String owner = StpUtil.getLoginIdAsString(), token = StpUtil.getTokenValue(); + StpUtil.login("foreign-" + UUID.randomUUID()); StudyReportFragmentsEntity foreign = fragment(null); + tags.addUserTag(MarkerObjectTypeEnum.FRAGMENT, foreign.getId().toString(), "Foreign Tag"); + StpUtil.login(owner); + MarkerEntity corrupt = new MarkerEntity(); corrupt.setObjectType("FRAGMENT"); corrupt.setObjectNum(foreign.getId().toString()); corrupt.setKind("USER"); corrupt.setMarkerName("Cross Tenant Object"); markers.insert(corrupt); + mvc.perform(get("/markers/tags").param("objectType", "FRAGMENT").header("satoken", token)) + .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200)).andExpect(jsonPath("$.data.length()").value(1)) + .andExpect(jsonPath("$.data[0].markerCount").value(2)).andExpect(jsonPath("$.data[0].objectCount").value(2)); + assertTrue(tags.listUserTagUsage().stream().anyMatch(u -> "Task Only".equals(u.getMarkerName()))); + mvc.perform(get("/markers/tags").header("satoken", token)).andExpect(jsonPath("$.code").value(200)) + .andExpect(jsonPath("$.data[?(@.markerName == 'Task Only')]").isNotEmpty()); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/GuidanceIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/GuidanceIntegrationTest.java index 5d5d9e7..52e6a62 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/GuidanceIntegrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/GuidanceIntegrationTest.java @@ -30,6 +30,8 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; /** * 学习引导的落库集成测试(复习-06)。 diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java b/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java new file mode 100644 index 0000000..6090291 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/HistoricalRecallFixture.java @@ -0,0 +1,29 @@ +package com.guo.learningprogresstracker.service.impl; + +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import com.guo.learningprogresstracker.service.recall.RecallReferenceLoader; +import com.guo.learningprogresstracker.service.recall.ReviewRecallStore; + +/** Persisted task-scope fixture for duration/export isolation tests. */ +public final class HistoricalRecallFixture { + private HistoricalRecallFixture() {} + public static RecallDetail insert(ReviewRecallStore store, RecallReferenceLoader loader, String taskNum) { + Instant now = Instant.now(); + ScopeSnapshot scope = loader.scope(new ScopeInput("TASK", taskNum, List.of(), null)); + ReferenceSnapshot reference = loader.snapshot(scope); + RecallDetail detail = new RecallDetail(); + detail.setRecallNum("RECALL-" + UUID.randomUUID()); detail.setStatus("ACTIVE"); detail.setScope(scope); detail.setScopeStatus("VALID"); + detail.setActiveDurationMs(0); detail.setCreatedAt(now); detail.setUpdatedAt(now); detail.setEditorId("editor"); + detail.setWriteToken(UUID.randomUUID().toString()); + detail.setExpression(new Expression(1, new ExpressionNode("root", "", "", List.of(), null, List.of()))); + detail.setReference(new ReferenceSummary(reference.status(), reference.sources().size(), reference.limitations())); + detail.setRequests(new ArrayList<>()); + RecallDocument document = new RecallDocument(); document.setDetail(detail); document.setReference(reference); + document.setEpochStartedAt(now); document.setAcceptedSegmentMs(0); store.insert(document); + return detail; + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/RecallRatioQueryIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/RecallRatioQueryIntegrationTest.java deleted file mode 100644 index 3e7ab65..0000000 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/RecallRatioQueryIntegrationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.guo.learningprogresstracker.service.impl; - -import cn.dev33.satoken.stp.StpUtil; -import com.guo.learningprogresstracker.dto.TaskRecallRatio; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import com.guo.learningprogresstracker.mapper.ReviewRecallRecordMapper; -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 java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * 覆盖率查询的落库集成测试(复习-04)。 - * - *

验收:该查询返回行数等于任务数而非回忆记录数——即不再把某个任务的全部 - * 回忆记录(含 {@code compare_result} 大字段)拉回内存再逐条取最新。

- */ -@SpringBootTest -class RecallRatioQueryIntegrationTest { - - private static final String USER = "覆盖率查询集成测试用户"; - - private static final AtomicInteger SEQ = new AtomicInteger(); - - @Autowired - private ReviewRecallRecordMapper recallRecordMapper; - - @BeforeEach - void setUp() { - StpUtil.login(USER, "test_device"); - } - - private static String uniqueTaskNum() { - return "TASKRATIO-IT-" + System.nanoTime() + "-" + SEQ.incrementAndGet(); - } - - private void insertRecall(String taskNum, double ratio, String compareResult) { - ReviewRecallRecordEntity record = new ReviewRecallRecordEntity(); - record.setTaskNum(taskNum); - record.setRecallContent("- 回忆"); - record.setRecallRatio(ratio); - record.setMatchedCount(1); - record.setMissedCount(1); - record.setExtraCount(0); - record.setCompareResult(compareResult); - recallRecordMapper.insert(record); - } - - @Test - void returnsOneRowPerTaskRegardlessOfRecallCount() { - String taskA = uniqueTaskNum(); - String taskB = uniqueTaskNum(); - for (int i = 0; i < 12; i++) { - insertRecall(taskA, 0.1 * i, "{\"big\":\"" + "x".repeat(200) + "\"}"); - } - insertRecall(taskB, 0.9, "{}"); - - List rows = recallRecordMapper.selectLatestRatioByTask(Set.of(taskA, taskB)); - - assertEquals(2, rows.size(), "两个任务即使有 13 条回忆记录,也只应返回 2 行"); - } - - @Test - void returnsLatestRatioPerTask() { - String taskNum = uniqueTaskNum(); - insertRecall(taskNum, 0.20, null); - insertRecall(taskNum, 0.55, null); - insertRecall(taskNum, 0.80, null); - - List rows = recallRecordMapper.selectLatestRatioByTask(Set.of(taskNum)); - - assertEquals(1, rows.size()); - assertEquals(0.80, rows.get(0).getRecallRatio(), 0.0001, "应取最近一次(最后插入)的覆盖率"); - } - - @Test - void excludesLogicallyDeletedRecordsAndOtherTenants() { - String taskNum = uniqueTaskNum(); - ReviewRecallRecordEntity deleted = new ReviewRecallRecordEntity(); - deleted.setTaskNum(taskNum); - deleted.setRecallContent("- 将被删除"); - deleted.setRecallRatio(0.99); - deleted.setMatchedCount(0); - deleted.setMissedCount(1); - deleted.setExtraCount(0); - recallRecordMapper.insert(deleted); - recallRecordMapper.deleteById(deleted.getId()); - - insertRecall(taskNum, 0.30, null); - - List rows = recallRecordMapper.selectLatestRatioByTask(Set.of(taskNum)); - assertEquals(1, rows.size()); - assertEquals(0.30, rows.get(0).getRecallRatio(), 0.0001, "已删除的记录不应参与取最新"); - - StpUtil.login("覆盖率查询集成测试另一个用户", "test_device"); - assertTrue(recallRecordMapper.selectLatestRatioByTask(Set.of(taskNum)).isEmpty(), - "覆盖率查询必须受租户隔离约束"); - } - - @Test - void emptyTaskSet_returnsEmpty() { - assertTrue(recallRecordMapper.selectLatestRatioByTask(Set.of()).isEmpty()); - assertTrue(recallRecordMapper.selectLatestRatioByTask(null).isEmpty()); - } - - @Test - void taskWithoutAnyRecall_isAbsentFromResult() { - String taskNum = uniqueTaskNum(); - assertTrue(recallRecordMapper.selectLatestRatioByTask(Set.of(taskNum)).isEmpty(), - "从未回忆过的任务不返回行,由调用方按「最需要复习」处理"); - } - - @Test - void generatedTaskNumIsUsable() { - assertTrue(GenerateNumTool.generateNum("TASKRATIO").startsWith("TASKRATIO-")); - } -} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewDurationIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewDurationIntegrationTest.java deleted file mode 100644 index 36be7f6..0000000 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewDurationIntegrationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.guo.learningprogresstracker.service.impl; - -import cn.dev33.satoken.stp.StpUtil; -import com.guo.learningprogresstracker.dto.ReviewTaskStats; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import com.guo.learningprogresstracker.mapper.ReviewRecallRecordMapper; -import com.guo.learningprogresstracker.service.ReviewService; -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 java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * 复习耗时的落库与聚合集成测试(复习-07):在真实 SQL(含租户条件、逻辑删除与 GROUP BY 聚合)下验证。 - *

聚合走自定义 Mapper SQL,因此这里同时守住两个容易漏的条件:租户隔离与逻辑删除。

- */ -@SpringBootTest -class ReviewDurationIntegrationTest { - - private static final String USER_A = "复习耗时集成测试用户A"; - private static final String USER_B = "复习耗时集成测试用户B"; - - /** GenerateNumTool 在同毫秒内会生成相同编号(数据-03),集成测试自己保证任务编号唯一。 */ - private static final AtomicInteger SEQ = new AtomicInteger(); - - @Autowired - private ReviewService reviewService; - - @Autowired - private ReviewRecallRecordMapper recallRecordMapper; - - @BeforeEach - void setUp() { - StpUtil.login(USER_A, "test_device"); - } - - private static String uniqueTaskNum() { - return "TASKRD-IT-" + System.nanoTime() + "-" + SEQ.incrementAndGet(); - } - - @Test - void reviewDuration_isPersistedAndAggregatedPerTask() { - String taskNum = uniqueTaskNum(); - String otherTaskNum = uniqueTaskNum(); - - insertRecall(taskNum, 300); - insertRecall(taskNum, 120); - insertRecall(otherTaskNum, 60); - - assertEquals(420L, reviewService.getReviewTaskStats(taskNum).getReviewDurationSeconds(), - "同一任务应累计 300+120 秒"); - assertEquals(60L, reviewService.getReviewTaskStats(otherTaskNum).getReviewDurationSeconds(), - "不同任务之间不应串数据"); - } - - @Test - void reviewDuration_databaseDefaultIsZero() { - ReviewRecallRecordEntity saved = insertRecall(uniqueTaskNum(), null); - - assertEquals(0, recallRecordMapper.selectById(saved.getId()).getReviewDurationSeconds(), - "未上报耗时时应落库为 0,而不是 null"); - } - - @Test - void reviewDuration_customSqlStillIsolatedByTenant() { - String taskNum = uniqueTaskNum(); - insertRecall(taskNum, 300); - - StpUtil.login(USER_B, "test_device"); - insertRecall(taskNum, 999); - assertEquals(999L, reviewService.getReviewTaskStats(taskNum).getReviewDurationSeconds(), - "用户 B 只应看到自己的记录"); - - StpUtil.login(USER_A, "test_device"); - assertEquals(300L, reviewService.getReviewTaskStats(taskNum).getReviewDurationSeconds(), - "自定义 SQL 也必须被租户拦截器追加 created_by 条件"); - } - - @Test - void reviewDuration_excludesLogicallyDeletedRecords() { - String taskNum = uniqueTaskNum(); - ReviewRecallRecordEntity deleted = insertRecall(taskNum, 300); - insertRecall(taskNum, 120); - - recallRecordMapper.deleteById(deleted.getId()); - - assertEquals(120L, reviewService.getReviewTaskStats(taskNum).getReviewDurationSeconds(), - "自定义 SQL 未被 @TableLogic 自动追加条件,必须显式过滤 deleted = 0"); - } - - private ReviewRecallRecordEntity insertRecall(String taskNum, Integer durationSeconds) { - ReviewRecallRecordEntity record = new ReviewRecallRecordEntity(); - record.setTaskNum(taskNum); - record.setRecallContent("- 集成测试回忆"); - record.setRecallRatio(0.5); - record.setMatchedCount(1); - record.setMissedCount(1); - record.setExtraCount(0); - record.setReviewDurationSeconds(durationSeconds); - recallRecordMapper.insert(record); - return record; - } -} diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewFeedbackIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewFeedbackIntegrationTest.java index 2ed5412..42f8876 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewFeedbackIntegrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewFeedbackIntegrationTest.java @@ -121,7 +121,7 @@ class ReviewFeedbackIntegrationTest { assertNotNull(initial.getDescription()); reviewService.saveSortPreference("MASTERY_FIRST"); - assertEquals("MASTERY_FIRST", reviewService.getSortPreference().getPreset()); + assertEquals("BALANCED", reviewService.getSortPreference().getPreset(), "旧掌握度档位不再消费覆盖率"); // 未知值回落默认,避免一个坏值让 Feed 报错 reviewService.saveSortPreference("NOT_A_PRESET"); diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java index eb4c1cf..fd75673 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java @@ -1,38 +1,5 @@ package com.guo.learningprogresstracker.service.impl; -import com.baomidou.mybatisplus.core.MybatisConfiguration; -import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; -import com.guo.learningprogresstracker.dto.IdRange; -import com.guo.learningprogresstracker.dto.ReviewFeedItem; -import com.guo.learningprogresstracker.dto.ReviewSummary; -import com.guo.learningprogresstracker.dto.ReviewTaskStats; -import com.guo.learningprogresstracker.dto.TaskContentCount; -import com.guo.learningprogresstracker.dto.TaskRecallRatio; -import com.guo.learningprogresstracker.dto.TaskReviewDuration; -import com.guo.learningprogresstracker.dto.TaskSessionStats; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; -import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; -import com.guo.learningprogresstracker.entity.StudyReportsEntity; -import com.guo.learningprogresstracker.entity.StudySessionsEntity; -import com.guo.learningprogresstracker.entity.TaskEntity; -import com.guo.learningprogresstracker.mapper.ReviewRecallRecordMapper; -import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; -import com.guo.learningprogresstracker.mapper.StudyReportsMapper; -import com.guo.learningprogresstracker.mapper.StudySessionsMapper; -import com.guo.learningprogresstracker.mapper.TasksMapper; -import com.guo.learningprogresstracker.mapper.UserReviewPreferencesMapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.apache.ibatis.builder.MapperBuilderAssistant; -import org.junit.jupiter.api.BeforeAll; -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.time.LocalDateTime; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -41,6 +8,38 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.baomidou.mybatisplus.core.MybatisConfiguration; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.guo.learningprogresstracker.dto.IdRange; +import com.guo.learningprogresstracker.dto.ReviewFeedItem; +import com.guo.learningprogresstracker.dto.ReviewSummary; +import com.guo.learningprogresstracker.dto.ReviewTaskStats; +import com.guo.learningprogresstracker.dto.TaskContentCount; +import com.guo.learningprogresstracker.dto.TaskSessionStats; +import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; +import com.guo.learningprogresstracker.entity.StudyReportsEntity; +import com.guo.learningprogresstracker.entity.StudySessionsEntity; +import com.guo.learningprogresstracker.entity.TaskEntity; +import com.guo.learningprogresstracker.mapper.ReviewRecallMapper; +import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; +import com.guo.learningprogresstracker.mapper.StudyReportsMapper; +import com.guo.learningprogresstracker.mapper.StudySessionsMapper; +import com.guo.learningprogresstracker.mapper.TasksMapper; +import com.guo.learningprogresstracker.mapper.UserReviewPreferencesMapper; +import java.time.LocalDateTime; +import java.util.List; +import org.apache.ibatis.builder.MapperBuilderAssistant; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import com.guo.learningprogresstracker.service.review.ReviewFeedService; +import com.guo.learningprogresstracker.service.review.ReviewStatsService; +import com.baomidou.mybatisplus.core.metadata.IPage; + @ExtendWith(MockitoExtension.class) class ReviewServiceImplTest { @@ -53,9 +52,6 @@ class ReviewServiceImplTest { TableInfoHelper.initTableInfo(new MapperBuilderAssistant(configuration, ""), TaskEntity.class); } - @InjectMocks - private ReviewServiceImpl reviewService; - @Mock private StudyReportsMapper studyReportsMapper; @@ -68,14 +64,44 @@ class ReviewServiceImplTest { @Mock private TasksMapper tasksMapper; - @Mock - private ReviewRecallRecordMapper reviewRecallRecordMapper; - @Mock private UserReviewPreferencesMapper userReviewPreferencesMapper; + @Mock + private ReviewRecallMapper newRecallMapper; + + /** 三个协作者手工组装:Mockito 只会把 mock 注入本类,新组件的构造要显式给出。 */ + private ReviewFeedService reviewFeedService; + + private ReviewStatsService reviewStatsService; + + private ReviewServiceImpl reviewService; + + @BeforeEach + void wireCollaborators() { + reviewFeedService = new ReviewFeedService( + studyReportsMapper, + studyReportFragmentsMapper, + studySessionsMapper, + tasksMapper, + userReviewPreferencesMapper); + reviewStatsService = new ReviewStatsService( + studyReportsMapper, studyReportFragmentsMapper, studySessionsMapper, tasksMapper, newRecallMapper); + reviewService = new ReviewServiceImpl( + studyReportsMapper, + studyReportFragmentsMapper, + null, + studySessionsMapper, + tasksMapper, + null, + userReviewPreferencesMapper, + null, + reviewFeedService, + reviewStatsService); + } + @Test - void getReviewFeed_smartMode_prefersLowRecallRatioContent() { + void getReviewFeed_smartMode_usesAgeNotLegacyRecallRatio() { LocalDateTime now = LocalDateTime.now(); StudyReportFragmentsEntity oldLowMastery = new StudyReportFragmentsEntity(); @@ -103,30 +129,33 @@ class ReviewServiceImplTest { // 复习-03:随机取样改为「主键区间 + 顺序取窗口」,因此需要提供 id 区间 when(studyReportFragmentsMapper.selectIdRange()).thenReturn(idRange(1, 2)); - when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of(oldLowMastery, freshHighMastery)); + when(studyReportFragmentsMapper.selectPage(any(), any())).thenAnswer(inv -> { + IPage page = inv.getArgument(0); + page.setRecords(List.of(oldLowMastery, freshHighMastery)); + return page; + }); when(tasksMapper.selectList(any())).thenReturn(List.of(taskLow, taskHigh)); // 复习-01:排序档位从偏好表读取,未设置时回落默认 when(userReviewPreferencesMapper.selectOne(any())).thenReturn(null); - // 复习-04:覆盖率改由 SQL 按任务分组取最新 - TaskRecallRatio highRatio = new TaskRecallRatio(); - highRatio.setTaskNum("T_HIGH"); - highRatio.setRecallRatio(1.0); - when(reviewRecallRecordMapper.selectLatestRatioByTask(any())).thenReturn(List.of(highRatio)); - List items = reviewService.getReviewFeed(1, "smart"); - - // 采样是概率性的,多次运行统计低掌握内容被选中的频率应显著更高 - int lowMasteryWins = 0; - for (int i = 0; i < 200; i++) { - List sample = reviewService.getReviewFeed(1, "smart"); - if (!sample.isEmpty() && "T_LOW".equals(sample.get(0).getTaskNum())) { - lowMasteryWins++; - } - } assertEquals(1, items.size()); - // 低掌握内容权重约为高掌握内容的 5 倍以上,200 次中至少应赢 120 次 - org.junit.jupiter.api.Assertions.assertTrue(lowMasteryWins > 120, - "低掌握内容被选中次数应显著更多,实际: " + lowMasteryWins + "/200"); + ReviewFeedItem old = new ReviewFeedItem(); + old.setCreatedTime(now.minusDays(60)); + ReviewFeedItem fresh = new ReviewFeedItem(); + fresh.setCreatedTime(now); + double oldWeight = org.springframework.test.util.ReflectionTestUtils.invokeMethod( + reviewFeedService, + "reviewNeedWeight", + old, + now, + com.guo.learningprogresstracker.enums.ReviewSortPresetEnum.TIME_FIRST); + double freshWeight = org.springframework.test.util.ReflectionTestUtils.invokeMethod( + reviewFeedService, + "reviewNeedWeight", + fresh, + now, + com.guo.learningprogresstracker.enums.ReviewSortPresetEnum.TIME_FIRST); + assertTrue(oldWeight > freshWeight, "只用真实接触时间和明确碎片反馈调整权重"); } @Test @@ -144,7 +173,11 @@ class ReviewServiceImplTest { task.setTaskNum("T1"); task.setTaskName("Task"); - when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of(fragment)); + when(studyReportFragmentsMapper.selectPage(any(), any())).thenAnswer(inv -> { + IPage page = inv.getArgument(0); + page.setRecords(List.of(fragment)); + return page; + }); when(tasksMapper.selectList(any())).thenReturn(List.of(task)); List items = reviewService.getReviewFeed(1, "recent"); @@ -174,11 +207,11 @@ class ReviewServiceImplTest { when(studyReportsMapper.countReportsByTask(any())).thenReturn(List.of(count("T1", 2L))); when(studyReportFragmentsMapper.countFragmentsByTask(any())).thenReturn(List.of(count("T1", 3L))); // 聚合结果里出现了不在任务列表中的 taskNum,应被忽略 - when(reviewRecallRecordMapper.sumReviewDurationByTask(any())).thenReturn(List.of( - reviewDuration("T1", 420L), - reviewDuration("T_UNKNOWN", 100L))); + when(newRecallMapper.sumTaskDuration()) + .thenReturn(List.of(reviewDuration("T1", 420L), reviewDuration("T_UNKNOWN", 100L))); - List stats = reviewService.getReviewTaskStats(1, 20, null).getRecords(); + List stats = + reviewService.getReviewTaskStats(1, 20, null).getRecords(); assertEquals(1, stats.size()); assertEquals(600, stats.get(0).getEffectiveTime()); @@ -241,10 +274,11 @@ class ReviewServiceImplTest { return row; } - private static TaskReviewDuration reviewDuration(String taskNum, Long seconds) { - TaskReviewDuration row = new TaskReviewDuration(); + private static com.guo.learningprogresstracker.dto.recall.TaskRecallDuration reviewDuration( + String taskNum, Long seconds) { + var row = new com.guo.learningprogresstracker.dto.recall.TaskRecallDuration(); row.setTaskNum(taskNum); - row.setReviewDurationSeconds(seconds); + row.setActiveDurationMs(seconds * 1000); return row; } } 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 b60891b..c8c46b4 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/StandardMindMapServiceImplTest.java @@ -4,189 +4,46 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.mapper.*; -import com.guo.learningprogresstracker.service.MindMapAiClient; -import com.guo.learningprogresstracker.utils.CompareResult; -import com.guo.learningprogresstracker.utils.MindMapNode; 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 org.springframework.test.util.ReflectionTestUtils; - -import java.util.Collections; -import java.util.List; - +import java.util.Map; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +import com.guo.learningprogresstracker.service.ai.MindMapOutlineGenerator; +import com.guo.learningprogresstracker.service.ai.MindMapReportContextLoader; -@ExtendWith(MockitoExtension.class) class StandardMindMapServiceImplTest { + ReviewStandardMindMapMapper maps = mock(ReviewStandardMindMapMapper.class); + TasksMapper tasks = mock(TasksMapper.class); + StandardMindMapServiceImpl service = new StandardMindMapServiceImpl(maps, tasks, mock(TaskApplicationMapper.class), + mock(StudyReportFragmentsMapper.class), mock(MindMapOutlineGenerator.class), mock(MindMapReportContextLoader.class), new ObjectMapper()); - @InjectMocks - private StandardMindMapServiceImpl service; - - @Mock - private ReviewStandardMindMapMapper standardMindMapMapper; - @Mock - private ReviewRecallRecordMapper recallRecordMapper; - @Mock - private TasksMapper tasksMapper; - @Mock - private TaskApplicationMapper taskApplicationMapper; - @Mock - private StudyReportFragmentsMapper studyReportFragmentsMapper; - @Mock - private MindMapOutlineGenerator outlineGenerator; - @Mock - private MindMapReportContextLoader reportContextLoader; - @Mock - private AiServiceClient aiServiceClient; - - private final ObjectMapper objectMapper = new ObjectMapper(); - - // ============ normalize / fuzzyMatch / bigramSet ============ - - @Test - void normalize_shouldStripPunctuationAndLowercase() { - assertEquals("javaconcurrency", StandardMindMapServiceImpl.normalize("Java Concurrency")); - assertEquals("测试abc", StandardMindMapServiceImpl.normalize("测试,ABC!?")); - assertEquals("helloworld", StandardMindMapServiceImpl.normalize(" Hello, World! ")); - assertEquals("", StandardMindMapServiceImpl.normalize(null)); - assertEquals("", StandardMindMapServiceImpl.normalize("")); + @Test void missingTaskIsRejected() { + when(tasks.exists(any())).thenReturn(false); + assertThrows(NotFindEntitiesException.class, () -> service.getExisting("missing")); } - - @Test - void normalize_shouldStripCompareMarkers() { - assertEquals("thread", StandardMindMapServiceImpl.normalize("MATCHED|Thread")); - assertEquals("thread", StandardMindMapServiceImpl.normalize("MISSED|Thread")); + @Test void existingMapIsReadWithoutGeneratingOrWriting() throws Exception { + when(tasks.exists(any())).thenReturn(true); + ReviewStandardMindMapEntity existing = new ReviewStandardMindMapEntity(); existing.setId(1); existing.setTitle("已有导图"); + when(maps.selectOne(any())).thenReturn(existing); + assertSame(existing, service.getExisting("T1")); + verify(maps, never()).insert(any()); verify(maps, never()).updateById(any()); } - - @Test - void bigramSet_shouldExtractCharacterPairs() { - java.util.Set set = StandardMindMapServiceImpl.bigramSet("hello"); - assertTrue(set.contains("he")); - assertTrue(set.contains("el")); - assertTrue(set.contains("ll")); - assertTrue(set.contains("lo")); - assertEquals(4, set.size()); + @Test void missingMapCanStillBeCreatedByLearningScreenEditor() throws Exception { + when(tasks.exists(any())).thenReturn(true); + ReviewStandardMindMapEntity saved = service.updateByOutline("T1", "根\n - 子节点"); + assertEquals("T1", saved.getTaskNum()); assertEquals("USER", saved.getGenerator()); + assertTrue(saved.getContent().contains("子节点")); verify(maps).insert(saved); } - - @Test - void bigramSet_shouldReturnEmptyForShortStrings() { - assertTrue(StandardMindMapServiceImpl.bigramSet("a").isEmpty()); - assertTrue(StandardMindMapServiceImpl.bigramSet("").isEmpty()); + @Test void existingMapEditorOverwritesCurrentContent() throws Exception { + when(tasks.exists(any())).thenReturn(true); + ReviewStandardMindMapEntity existing = new ReviewStandardMindMapEntity(); existing.setId(1); + when(maps.selectOne(any())).thenReturn(existing); + service.updateByOutline("T1", "新根\n - 新内容"); + assertEquals("新根", existing.getTitle()); verify(maps).updateById(existing); verify(maps, never()).insert(any()); } - - // ============ compareTrees ============ - - @Test - void compareTrees_perfectMatch() { - service = createService(); - - MindMapNode standard = new MindMapNode("学习Java"); - standard.setChildren(List.of(new MindMapNode("线程基础"), new MindMapNode("锁机制"))); - - MindMapNode recall = new MindMapNode("学习Java"); - recall.setChildren(List.of(new MindMapNode("线程基础"), new MindMapNode("锁机制"))); - - CompareResult result = service.compareTrees(standard, recall); - - assertEquals(2, result.getMatchedCount()); - assertEquals(0, result.getMissedCount()); - assertEquals(0, result.getExtraCount()); - assertEquals(1.0, result.getRecallRatio(), 0.001); - } - - @Test - void compareTrees_partialMatch() { - service = createService(); - - MindMapNode standard = new MindMapNode("学习Java"); - standard.setChildren(List.of( - new MindMapNode("线程基础"), - new MindMapNode("锁机制"), - new MindMapNode("JVM内存模型") - )); - - MindMapNode recall = new MindMapNode("学习Java"); - recall.setChildren(List.of( - new MindMapNode("线程基础"), - new MindMapNode("SpringBoot") - )); - - CompareResult result = service.compareTrees(standard, recall); - - assertEquals(1, result.getMatchedCount()); - assertEquals(2, result.getMissedCount()); - assertEquals(1, result.getExtraCount()); - } - - @Test - void compareTrees_noMatch() { - service = createService(); - - MindMapNode standard = new MindMapNode("学习Java"); - standard.setChildren(List.of(new MindMapNode("线程基础"), new MindMapNode("锁机制"))); - - MindMapNode recall = new MindMapNode("完全不同"); - recall.setChildren(List.of(new MindMapNode("前端开发"))); - - CompareResult result = service.compareTrees(standard, recall); - - assertEquals(0, result.getMatchedCount()); - assertEquals(2, result.getMissedCount()); - assertEquals(1, result.getExtraCount()); - assertEquals(0.0, result.getRecallRatio(), 0.001); - } - - // ============ 边缘情况 ============ - - @Test - void compareTrees_emptyStandardLeaves() { - service = createService(); - - MindMapNode standard = new MindMapNode("根"); // 无子节点 - MindMapNode recall = new MindMapNode("根"); - recall.setChildren(List.of(new MindMapNode("额外节点"))); - - CompareResult result = service.compareTrees(standard, recall); - - assertEquals(0, result.getMatchedCount()); - assertEquals(0, result.getMissedCount()); - assertEquals(1, result.getExtraCount()); - assertEquals(0.0, result.getRecallRatio(), 0.001); - } - - @Test - void getExisting_shouldThrowWhenTaskNotFound() { - when(tasksMapper.exists(any())).thenReturn(false); - assertThrows(NotFindEntitiesException.class, () -> service.getExisting("NOT_EXIST")); - } - - @Test - void getExisting_shouldReturnExisting() throws Exception { - when(tasksMapper.exists(any())).thenReturn(true); - - ReviewStandardMindMapEntity existing = new ReviewStandardMindMapEntity(); - existing.setId(1); - existing.setTaskNum("T1"); - existing.setTitle("已有导图"); - when(standardMindMapMapper.selectOne(any())).thenReturn(existing); - - ReviewStandardMindMapEntity result = service.getExisting("T1"); - assertEquals("已有导图", result.getTitle()); - verify(standardMindMapMapper, never()).insert(any()); - } - - // ============ 辅助 ============ - - private StandardMindMapServiceImpl createService() { - StandardMindMapServiceImpl s = new StandardMindMapServiceImpl( - standardMindMapMapper, recallRecordMapper, tasksMapper, - taskApplicationMapper, studyReportFragmentsMapper, - outlineGenerator, reportContextLoader, objectMapper, aiServiceClient); - return s; + @Test void absentMapFindNodeReturnsEmptyResult() throws Exception { + when(tasks.exists(any())).thenReturn(true); + assertEquals(Map.of("path", "", "nodeTitle", "", "score", 0.0), service.findNode("T1", "内容")); } } diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImplTest.java index 0150615..438bbac 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/StudyReportFragmentsServiceImplTest.java @@ -99,15 +99,14 @@ class StudyReportFragmentsServiceImplTest { existing.setId(9); existing.setContent("旧内容"); doReturn(existing).when(studyReportFragmentsService).getById(any()); - doReturn(true).when(studyReportFragmentsService).updateById(any(StudyReportFragmentsEntity.class)); + doReturn(true).when(studyReportFragmentsService).update(any(StudyReportFragmentsEntity.class), any()); UpdateFragmentsRequest request = new UpdateFragmentsRequest(); request.setContent("更新后的内容"); studyReportFragmentsService.updateFragments(9, request); - verify(studyReportFragmentsService).updateById(argThat(entity -> - Integer.valueOf(9).equals(entity.getId()) - && "更新后的内容".equals(entity.getContent()))); + verify(studyReportFragmentsService) + .update(any(StudyReportFragmentsEntity.class), any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)); } /** diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImplTest.java index 091d1a2..dd0ade1 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImplTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/StudySessionsServiceImplTest.java @@ -1,8 +1,16 @@ package com.guo.learningprogresstracker.service.impl; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import com.baomidou.mybatisplus.core.MybatisConfiguration; import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.guo.learningprogresstracker.common.StudyTimePolicy; import com.guo.learningprogresstracker.dto.ReportSections; +import com.guo.learningprogresstracker.dto.response.StudySessionResponse; import com.guo.learningprogresstracker.entity.StudyReportsEntity; import com.guo.learningprogresstracker.entity.StudySessionsEntity; import com.guo.learningprogresstracker.entity.TaskEntity; @@ -13,26 +21,23 @@ import com.guo.learningprogresstracker.mapper.StudyReportsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; import com.guo.learningprogresstracker.service.StudyExpectationsService; import com.guo.learningprogresstracker.service.StudyReportFragmentsService; +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import org.apache.ibatis.builder.MapperBuilderAssistant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; - -import java.io.Serializable; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; +import com.guo.learningprogresstracker.service.session.StudySessionConvergenceService; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) @@ -69,6 +74,8 @@ class StudySessionsServiceImplTest { @BeforeEach void setUp() { + TableInfoHelper.initTableInfo( + new MapperBuilderAssistant(new MybatisConfiguration(), ""), StudySessionsEntity.class); // stub updateById,避免调用真实的 getBaseMapper() doReturn(true).when(studySessionsService).updateById(any()); // stub 条件更新(结束会话抢占),默认视为抢占成功 @@ -77,6 +84,11 @@ class StudySessionsServiceImplTest { doReturn(true).when(studySessionsService).removeById(any(Serializable.class)); // 收敛路径直接使用 ServiceImpl 的 baseMapper 字段,必须显式注入(Mockito 不会填父类字段) ReflectionTestUtils.setField(studySessionsService, "baseMapper", studySessionsMapper); + // 收敛已挪到独立组件:用真实实现 + 同一批 mock 装进去,委托链路才跑得到 + ReflectionTestUtils.setField( + studySessionsService, + "studySessionConvergenceService", + new StudySessionConvergenceService(studySessionsMapper, studyTimePolicy)); } private StudySessionsEntity createSession(String state, int minutesAgo) { @@ -165,10 +177,9 @@ class StudySessionsServiceImplTest { studySessionsService.endedStudySession("SESSION_TEST", new ReportSections(null, null, "测试报告内容")); - verify(studyReportsMapper).insert(argThat(report -> - "SESSION_TEST".equals(((StudyReportsEntity) report).getSessionNum()) - && "测试报告内容".equals(((StudyReportsEntity) report).getFreeSummary()) - )); + verify(studyReportsMapper) + .insert(argThat(report -> "SESSION_TEST".equals(((StudyReportsEntity) report).getSessionNum()) + && "测试报告内容".equals(((StudyReportsEntity) report).getFreeSummary()))); } /** @@ -192,8 +203,9 @@ class StudySessionsServiceImplTest { void endedStudySession_sessionNotFound_shouldThrowException() { doReturn(Optional.empty()).when(studySessionsService).getOneOpt(any(Wrapper.class)); - assertThrows(Exception.class, () -> - studySessionsService.endedStudySession("NOT_EXIST", new ReportSections(null, null, "内容"))); + assertThrows( + Exception.class, + () -> studySessionsService.endedStudySession("NOT_EXIST", new ReportSections(null, null, "内容"))); } /** @@ -224,7 +236,8 @@ class StudySessionsServiceImplTest { session.setActualTime(0); mockGetOneOpt(session); - String message = studySessionsService.endedStudySession("SESSION_INSTANT", new ReportSections(null, null, "内容")); + String message = + studySessionsService.endedStudySession("SESSION_INSTANT", new ReportSections(null, null, "内容")); assertEquals("本次有效学习时间不足10分钟,不计入总学习时间", message); assertEquals(0, session.getEffectiveTime()); @@ -270,8 +283,8 @@ class StudySessionsServiceImplTest { StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5); mockGetOneOpt(session); - ErrorParameterException ex = assertThrows(ErrorParameterException.class, () -> - studySessionsService.abortStudySession("SESSION_TEST", "我不是确认语")); + ErrorParameterException ex = assertThrows( + ErrorParameterException.class, () -> studySessionsService.abortStudySession("SESSION_TEST", "我不是确认语")); assertEquals("确认语输入不正确,请核对后重新输入", ex.getMessage()); verify(studyExpectationsService, never()).deleteBySessionNum(any()); @@ -288,8 +301,8 @@ class StudySessionsServiceImplTest { mockGetOneOpt(session); doReturn(0L).when(studyReportFragmentsMapper).selectCount(any()); - studySessionsService.abortStudySession("SESSION_TEST", - " " + StudySessionsServiceImpl.MISOPERATION_CONFIRMATION + " "); + studySessionsService.abortStudySession( + "SESSION_TEST", " " + StudySessionsServiceImpl.MISOPERATION_CONFIRMATION + " "); verify(studyExpectationsService).deleteBySessionNum("SESSION_TEST"); verify(studySessionsService).removeById(2); @@ -304,8 +317,10 @@ class StudySessionsServiceImplTest { mockGetOneOpt(session); doReturn(1L).when(studyReportFragmentsMapper).selectCount(any()); - ErrorParameterException ex = assertThrows(ErrorParameterException.class, () -> - studySessionsService.abortStudySession("SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION)); + ErrorParameterException ex = assertThrows( + ErrorParameterException.class, + () -> studySessionsService.abortStudySession( + "SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION)); assertEquals("这次学习已经产生了学习残片,不能按误操作结束了哦", ex.getMessage()); verify(studyExpectationsService, never()).deleteBySessionNum(any()); @@ -320,8 +335,10 @@ class StudySessionsServiceImplTest { StudySessionsEntity session = createSession(StudySessionStateEnum.ENDED.name(), 5); mockGetOneOpt(session); - ErrorParameterException ex = assertThrows(ErrorParameterException.class, () -> - studySessionsService.abortStudySession("SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION)); + ErrorParameterException ex = assertThrows( + ErrorParameterException.class, + () -> studySessionsService.abortStudySession( + "SESSION_TEST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION)); assertEquals("这次学习会话已经结束,不能再误操作结束了", ex.getMessage()); verify(studySessionsService, never()).removeById(any()); @@ -334,8 +351,10 @@ class StudySessionsServiceImplTest { void abortStudySession_sessionNotFound_shouldThrow() { doReturn(Optional.empty()).when(studySessionsService).getOneOpt(any(Wrapper.class)); - assertThrows(ErrorParameterException.class, () -> - studySessionsService.abortStudySession("NOT_EXIST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION)); + assertThrows( + ErrorParameterException.class, + () -> studySessionsService.abortStudySession( + "NOT_EXIST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION)); } // ============ 会话-01:结算路径统一 ============ @@ -431,7 +450,7 @@ class StudySessionsServiceImplTest { @Test void convergeStaleSessionsOfCurrentUser_staleOngoing_shouldPauseTruncateAndMark() { StudySessionsEntity stale = createSession(StudySessionStateEnum.ONGOING.name(), 180); - doReturn(List.of(stale)).when(studySessionsService).list(any(Wrapper.class)); + when(studySessionsMapper.selectList(any())).thenReturn(List.of(stale)); when(studySessionsMapper.convergeStaleSession(any())).thenReturn(1); int converged = studySessionsService.convergeStaleSessionsOfCurrentUser(); @@ -445,7 +464,7 @@ class StudySessionsServiceImplTest { @Test void convergeStaleSessionsOfCurrentUser_freshOngoing_shouldNotWrite() { StudySessionsEntity fresh = createSession(StudySessionStateEnum.ONGOING.name(), 10); - doReturn(List.of(fresh)).when(studySessionsService).list(any(Wrapper.class)); + when(studySessionsMapper.selectList(any())).thenReturn(List.of(fresh)); int converged = studySessionsService.convergeStaleSessionsOfCurrentUser(); @@ -457,7 +476,7 @@ class StudySessionsServiceImplTest { @Test void convergeStaleSessionsOfCurrentUser_concurrentClaimLost_shouldCountZero() { StudySessionsEntity stale = createSession(StudySessionStateEnum.ONGOING.name(), 180); - doReturn(List.of(stale)).when(studySessionsService).list(any(Wrapper.class)); + when(studySessionsMapper.selectList(any())).thenReturn(List.of(stale)); // 条件更新未命中:说明已被其他请求收敛 when(studySessionsMapper.convergeStaleSession(any())).thenReturn(0); @@ -486,4 +505,85 @@ class StudySessionsServiceImplTest { // 惰性收敛先按状态 + last_start_time 查一次悬挂会话 verify(studySessionsMapper, atLeastOnce()).selectList(any()); } + + @Test + void getActiveSession_shouldFindNonExcludedSessionEvenWhenItIsLatestResult() { + StudySessionsEntity otherTaskSession = createSession(StudySessionStateEnum.PAUSED.name(), 5); + otherTaskSession.setTaskNum("OTHER_TASK"); + doReturn(otherTaskSession).when(studySessionsService).getOne(argThat(wrapper -> { + assertTrue(wrapper.getSqlSegment().contains("task_num <>"), "excludeTaskNum 应在查询条件中排除,而不是查询后丢弃结果"); + return true; + })); + when(tasksServiceImpl.getOneOpt(any(Wrapper.class))).thenReturn(Optional.empty()); + + StudySessionResponse response = studySessionsService.getActiveSession("TARGET_TASK"); + + assertNotNull(response, "排除目标任务后仍有其它任务会话时不应返回空"); + assertEquals("OTHER_TASK", response.getTaskNum()); + } + + @Test + void pauseStudySession_futureEndTime_shouldRejectWithoutWriting() { + StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5); + session.setLastStartTime(LocalDateTime.now().minusMinutes(1)); + mockGetOneOpt(session); + + ErrorParameterException exception = assertThrows( + ErrorParameterException.class, + () -> studySessionsService.pauseStudySession( + "SESSION_TEST", LocalDateTime.now().plusSeconds(30))); + + assertEquals("暂停时间不能晚于当前时间", exception.getMessage()); + verify(studySessionsService, never()).updateById(any()); + } + + @Test + void pauseStudySession_pastEndTimeBeforeSegmentStart_shouldRejectWithoutWriting() { + StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5); + session.setLastStartTime(LocalDateTime.now().minusMinutes(1)); + mockGetOneOpt(session); + + ErrorParameterException exception = assertThrows( + ErrorParameterException.class, + () -> studySessionsService.pauseStudySession( + "SESSION_TEST", session.getLastStartTime().minusSeconds(1))); + + assertEquals("暂停时间不能早于本次学习开始时间", exception.getMessage()); + verify(studySessionsService, never()).updateById(any()); + } + + @Test + void startOrContinueStudySession_conflictingOtherTask_shouldRejectBeforeCreating() { + TaskEntity target = new TaskEntity(); + target.setTaskNum("TARGET_TASK"); + target.setTaskName("目标任务"); + when(tasksServiceImpl.getOneOpt(any(Wrapper.class))).thenReturn(Optional.of(target)); + + StudySessionsEntity otherTaskSession = createSession(StudySessionStateEnum.ONGOING.name(), 5); + otherTaskSession.setTaskNum("OTHER_TASK"); + doReturn(otherTaskSession).when(studySessionsService).getOne(any(Wrapper.class)); + + ErrorParameterException exception = assertThrows( + ErrorParameterException.class, () -> studySessionsService.startOrContinueStudySession("TARGET_TASK")); + + assertEquals("已有其他学习会话未结束,请先处理后再开始新的学习", exception.getMessage()); + verify(studySessionsService, never()).save(any(StudySessionsEntity.class)); + } + + @Test + void continueStudySession_conflictingOtherTask_shouldRejectBeforeUpdating() { + StudySessionsEntity target = createSession(StudySessionStateEnum.PAUSED.name(), 5); + target.setTaskNum("TARGET_TASK"); + mockGetOneOpt(target); + + StudySessionsEntity otherTaskSession = createSession(StudySessionStateEnum.ONGOING.name(), 5); + otherTaskSession.setTaskNum("OTHER_TASK"); + doReturn(otherTaskSession).when(studySessionsService).getOne(any(Wrapper.class)); + + ErrorParameterException exception = assertThrows( + ErrorParameterException.class, () -> studySessionsService.continueStudySession("SESSION_TEST")); + + assertEquals("已有其他学习会话未结束,请先处理后再开始新的学习", exception.getMessage()); + verify(studySessionsService, never()).updateById(any()); + } } diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java index 17c84f8..d0d671c 100644 --- a/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java +++ b/src/test/java/com/guo/learningprogresstracker/service/impl/TagMindMapIntegrationTest.java @@ -5,16 +5,12 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.guo.learningprogresstracker.dto.AiTaskResponse; import com.guo.learningprogresstracker.dto.MindMapFragmentPayload; import com.guo.learningprogresstracker.dto.MindMapReportContext; -import com.guo.learningprogresstracker.dto.RecallCompareOutcome; import com.guo.learningprogresstracker.dto.ReviewTiming; -import com.guo.learningprogresstracker.dto.TaskRecallRatio; -import com.guo.learningprogresstracker.dto.TaskReviewDuration; import com.guo.learningprogresstracker.dto.TagMindMapSummary; import com.guo.learningprogresstracker.dto.TagScope; import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest; import com.guo.learningprogresstracker.dto.request.CreateFragmentsRequest; import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest; -import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.ReviewTagMindMapEntity; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; import com.guo.learningprogresstracker.entity.StudyReportsEntity; @@ -22,11 +18,9 @@ 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.ReviewScopeTypeEnum; import com.guo.learningprogresstracker.enums.TagCombineModeEnum; import com.guo.learningprogresstracker.exception.ErrorParameterException; import com.guo.learningprogresstracker.exception.OperationFailedException; -import com.guo.learningprogresstracker.mapper.ReviewRecallRecordMapper; import com.guo.learningprogresstracker.mapper.ReviewTagMindMapMapper; import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.StudyReportsMapper; @@ -65,6 +59,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; /** * 标签导图与标签范围回忆对比的落库集成测试(闭环-04)。 @@ -90,8 +85,6 @@ class TagMindMapIntegrationTest { @Autowired private ReviewTagMindMapMapper tagMindMapMapper; - @Autowired - private ReviewRecallRecordMapper recallRecordMapper; @Autowired private MarkerService markerService; @@ -195,6 +188,21 @@ class TagMindMapIntegrationTest { // ============ 取材:并集 / 交集 ============ + @Test + void longEscapedTagRangeRoundTripsCurrentMapTitle() throws Exception { + List labels = java.util.stream.IntStream.range(0, 10) + .mapToObj(i -> i + "中\"\\".repeat(84) + "尾字").toList(); + assertTrue(labels.stream().allMatch(label -> label.length() == 255)); + TagScope scope = tagMindMapService.resolveScope(labels, "UNION"); + String outline = "- " + scope.displayName() + "\n - 知识点"; + ReviewTagMindMapEntity saved = tagMindMapService.updateByOutline(scope, outline); + ReviewTagMindMapEntity loaded = tagMindMapService.query(scope).getMap(); + assertEquals(saved.getId(), loaded.getId()); + assertEquals(scope.displayName(), loaded.getTitle()); + assertEquals(scope.tags(), TagScopeTool.parseStoredTags(loaded.getTagNames())); + assertTrue(loaded.getTagNames().length() > 2550); + } + @Test void unionAndIntersect_pickDifferentFragments() throws Exception { String taskNum = saveTask("标签取材任务-" + SEQ.incrementAndGet()); @@ -378,71 +386,6 @@ class TagMindMapIntegrationTest { assertFalse(map.getOutline().contains("其他用户的碎片")); } - // ============ 标签范围回忆对比与范围列 ============ - - @Test - void tagScopeRecallCompare_persistsRecordWithRangeAndDuration() throws Exception { - String taskNum = saveTask("标签回忆任务-" + SEQ.incrementAndGet()); - String tagA = tag("标签回忆A"); - addTag(createFragment(taskNum, "标签回忆碎片"), tagA); - TagScope scope = scope("UNION", tagA); - tagMindMapService.regenerate(scope); - - RecallCompareOutcome outcome = tagMindMapService.recallCompare(scope, "- 标签回忆碎片", null, - new ReviewTiming(LocalDateTime.now().minusMinutes(10), LocalDateTime.now(), 300)); - - ReviewRecallRecordEntity record = recallRecordMapper.selectById(outcome.recallRecordId()); - assertNotNull(record); - assertNull(record.getTaskNum(), "标签范围的复习不挂任务"); - assertEquals(ReviewScopeTypeEnum.TAG.name(), record.getScopeType()); - assertEquals(scope.scopeKey(), record.getScopeKey()); - assertEquals(scope.tags(), TagScopeTool.parseStoredTags(record.getScopeTags())); - assertEquals(TagCombineModeEnum.UNION.name(), record.getScopeMode()); - assertEquals(300, record.getReviewDurationSeconds().intValue(), "复习耗时按既有口径结算并落库"); - assertNotNull(record.getRecallRatio()); - assertEquals(tagMindMapService.query(scope).getMap().getId(), record.getStandardMapId(), - "记录能追溯回对比用的标签导图"); - - // 历史与最新结果都可查 - List history = tagMindMapService.listRecallRecords(scope); - assertEquals(1, history.size()); - assertEquals(record.getId(), history.get(0).getId()); - assertEquals(record.getId(), tagMindMapService.query(scope).getLatestRecallRecord().getId()); - } - - @Test - void taskScopeQueriesAndStats_areNotAffectedByTagRecords() throws Exception { - // 任务范围的一条记录:耗时 120 秒 - String taskNum = saveTask("任务口径任务-" + SEQ.incrementAndGet()); - addTag(createFragment(taskNum, "任务口径碎片"), tag("任务口径-" + SEQ.incrementAndGet())); - standardMindMapService.recallCompare(taskNum, "- 任一回忆", null, - new ReviewTiming(LocalDateTime.now().minusMinutes(10), LocalDateTime.now(), 120)); - - // 标签范围的一条记录:耗时 600 秒,task_num 为空 - String tagA = tag("统计隔离A"); - String tagTaskNum = saveTask("统计隔离任务-" + SEQ.incrementAndGet()); - addTag(createFragment(tagTaskNum, "统计隔离碎片"), tagA); - TagScope scope = scope("UNION", tagA); - tagMindMapService.regenerate(scope); - tagMindMapService.recallCompare(scope, "- 统计隔离碎片", null, - new ReviewTiming(LocalDateTime.now().minusMinutes(10), LocalDateTime.now(), 600)); - - // 任务维度的既有查询与统计只看带 task_num 的行 - List ratios = recallRecordMapper.selectLatestRatioByTask(Set.of(taskNum)); - assertEquals(1, ratios.size()); - assertEquals(taskNum, ratios.get(0).getTaskNum()); - - List durations = recallRecordMapper.sumReviewDurationByTask(Set.of(taskNum)); - assertEquals(1, durations.size()); - assertEquals(120L, durations.get(0).getReviewDurationSeconds().longValue(), - "标签范围的复习耗时不并入任务统计"); - - // 标签范围的记录仍可追溯 - List tagRecords = tagMindMapService.listRecallRecords(scope); - assertEquals(1, tagRecords.size()); - assertNull(tagRecords.get(0).getTaskNum()); - } - // ============ AI 任务链路(前端实际接线路径) ============ @Test @@ -485,28 +428,9 @@ class TagMindMapIntegrationTest { } @Test - void tagRecallCompareTask_persistsRecordAndReturnsOutcome() throws Exception { - String taskNum = saveTask("标签对比任务-" + SEQ.incrementAndGet()); - String tagA = tag("标签对比A"); - addTag(createFragment(taskNum, "标签对比碎片"), tagA); - TagScope scope = scope("UNION", tagA); - tagMindMapService.regenerate(scope); - - AiTaskResponse done = awaitTerminal(aiTaskService.submit(request("TAG_RECALL_COMPARE", scope.scopeKey(), - Map.of("tags", scope.tags(), - "combineMode", "UNION", - "recallOutline", "- 标签对比碎片", - "reviewStartedAt", LocalDateTime.now().minusMinutes(2).toString(), - "reviewDurationSeconds", 111))).getTaskNum()); - - assertEquals(AiTaskStatusEnum.SUCCEEDED.name(), done.getStatus(), done.getErrorMessage()); - Integer recordId = (Integer) done.getResult().get("recallRecordId"); - assertNotNull(recordId); - ReviewRecallRecordEntity record = recallRecordMapper.selectById(recordId); - assertEquals(ReviewScopeTypeEnum.TAG.name(), record.getScopeType()); - assertEquals(scope.scopeKey(), record.getScopeKey()); - assertEquals(111, record.getReviewDurationSeconds().intValue()); - assertNull(record.getTaskNum()); + void tagRecallCompareTask_rejectsLegacyScoreWrites() { + assertThrows(com.guo.learningprogresstracker.exception.ErrorParameterException.class, + () -> aiTaskService.submit(request("TAG_RECALL_COMPARE", "old-tag-scope", Map.of("recallOutline", "旧表达")))); } // ============ 已有导图列表(按标签复习的主入口) ============ @@ -675,7 +599,7 @@ class TagMindMapIntegrationTest { 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")); + () -> tagMindMapService.resolveScope(List.of("x".repeat(256)), "UNION")); } @Test diff --git a/src/test/java/com/guo/learningprogresstracker/service/recall/RecallReferenceLoaderTest.java b/src/test/java/com/guo/learningprogresstracker/service/recall/RecallReferenceLoaderTest.java new file mode 100644 index 0000000..55f7d1f --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/recall/RecallReferenceLoaderTest.java @@ -0,0 +1,86 @@ +package com.guo.learningprogresstracker.service.recall; + +import cn.dev33.satoken.stp.StpUtil; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import com.guo.learningprogresstracker.entity.*; +import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; +import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.service.MarkerService; +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.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; +import com.guo.learningprogresstracker.service.ai.RecallAiClient; + +/** 复习参考资料只由知识碎片组成:两种范围都不再并入学习报告或任务应用。 */ +@SpringBootTest +class RecallReferenceLoaderTest { + @Autowired RecallReferenceLoader loader; + @Autowired TasksMapper tasks; + @Autowired StudySessionsMapper sessions; + @Autowired StudyReportsMapper reports; + @Autowired StudyReportFragmentsMapper fragments; + @Autowired TaskApplicationMapper applications; + @Autowired MarkerService markers; + @MockBean AiTaskRunner runner; + @MockBean RecallAiClient client; + + @BeforeEach void login() { StpUtil.login("recall-reference-" + UUID.randomUUID()); } + + @Test void tagScopeSnapshotContainsOnlyFragments() throws Exception { + String tag = UUID.randomUUID().toString(); + StudyReportFragmentsEntity review = fragment(null, "REVIEW", "review-" + UUID.randomUUID(), "碎片一"); + StudyReportFragmentsEntity session = fragment(null, "SESSION", "session-" + UUID.randomUUID(), "碎片二"); + marker(review, tag); marker(session, tag); + report(session.getContextNum(), "同源学习报告"); + + ReferenceSnapshot snapshot = loader.snapshot(loader.scope(new ScopeInput("TAG", null, List.of(tag), "UNION"))); + + assertEquals(List.of("fragment:" + review.getId(), "fragment:" + session.getId()), + snapshot.sources().stream().map(ReferenceSource::sourceId).toList()); + assertOnlyFragments(snapshot); + assertEquals("AVAILABLE", snapshot.status()); + assertEquals(List.of("资料可能有遗漏或相互冲突,不作为标准答案。"), snapshot.limitations()); + } + + @Test void taskScopeSnapshotContainsOnlyFragments() throws Exception { + TaskEntity task = new TaskEntity(); task.setTaskNum(UUID.randomUUID().toString()); task.setTaskName("任务"); tasks.insert(task); + StudySessionsEntity session = StudySessionsEntity.initNewSession(); session.setTaskNum(task.getTaskNum()); sessions.insert(session); + StudyReportFragmentsEntity owned = fragment(task.getTaskNum(), "SESSION", session.getSessionNum(), "归属碎片"); + report(session.getSessionNum(), "同源学习报告"); + application(task.getTaskNum(), "补充资料"); + + ReferenceSnapshot snapshot = loader.snapshot(loader.scope(new ScopeInput("TASK", task.getTaskNum(), List.of(), null))); + + assertEquals(List.of("fragment:" + owned.getId()), snapshot.sources().stream().map(ReferenceSource::sourceId).toList()); + assertOnlyFragments(snapshot); + assertEquals("AVAILABLE", snapshot.status()); + assertEquals(List.of("资料可能有遗漏或相互冲突,不作为标准答案。"), snapshot.limitations()); + } + + private void assertOnlyFragments(ReferenceSnapshot snapshot) { + assertTrue(snapshot.sources().stream().allMatch(s -> "FRAGMENT".equals(s.type())), snapshot.sources().toString()); + assertTrue(snapshot.units().stream().allMatch(u -> u.sourceId().startsWith("fragment:"))); + } + + StudyReportFragmentsEntity fragment(String ownerTaskNum, String contextType, String contextNum, String text) { + StudyReportFragmentsEntity f = new StudyReportFragmentsEntity(); + f.setOwnerTaskNum(ownerTaskNum); f.setContextType(contextType); f.setContextNum(contextNum); + f.setContent(text); f.setCreatedTime(LocalDateTime.now()); fragments.insert(f); return f; + } + void marker(StudyReportFragmentsEntity f, String tag) throws Exception { markers.addUserTag(MarkerObjectTypeEnum.FRAGMENT, f.getId().toString(), tag); } + void report(String sessionNum, String summary) { + StudyReportsEntity r = new StudyReportsEntity(); r.setSessionNum(sessionNum); r.setSessionSummary(summary); reports.insert(r); + } + void application(String taskNum, String title) { + TaskApplicationEntity a = new TaskApplicationEntity(); a.setTaskNum(taskNum); a.setTitle(title); a.setDescription(title); applications.insert(a); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java new file mode 100644 index 0000000..48659d2 --- /dev/null +++ b/src/test/java/com/guo/learningprogresstracker/service/recall/ReviewRecallServiceIntegrationTest.java @@ -0,0 +1,249 @@ +package com.guo.learningprogresstracker.service.recall; + +import cn.dev33.satoken.stp.StpUtil; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.guo.learningprogresstracker.dto.AiTaskResponse; +import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest; +import com.guo.learningprogresstracker.dto.recall.RecallDtos.*; +import com.guo.learningprogresstracker.entity.*; +import com.guo.learningprogresstracker.enums.MarkerObjectTypeEnum; +import com.guo.learningprogresstracker.exception.RecallBusinessException; +import com.guo.learningprogresstracker.mapper.*; +import com.guo.learningprogresstracker.service.*; +import org.junit.jupiter.api.*; +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.Instant; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; +import com.guo.learningprogresstracker.service.ai.AiTaskRunner; +import com.guo.learningprogresstracker.service.ai.RecallAiClient; +import com.guo.learningprogresstracker.service.ai.RecallAiService; +import com.guo.learningprogresstracker.service.ai.RecallJson; + +/** Real migrations, current-only persistence, tenant isolation, AI terminal cleanup and source deletion. */ +@SpringBootTest +class ReviewRecallServiceIntegrationTest { + @Autowired ReviewRecallService service; + @Autowired RecallAiService ai; + @Autowired AiTaskService aiTasks; + @Autowired ReviewRecallMapper recalls; + @Autowired ReviewRecallRequestMapper requests; + @Autowired AiTaskMapper taskMapper; + @Autowired StudyReportFragmentsMapper fragments; + @Autowired MarkerService markers; + @Autowired StudyReportFragmentsService fragmentService; + @Autowired RecallJson json; + @Autowired ObjectMapper mapper; + @MockBean AiTaskRunner runner; + @MockBean RecallAiClient client; + @BeforeEach void login() { StpUtil.login("current-recall-test-" + UUID.randomUUID()); } + String id() { return UUID.randomUUID().toString(); } + StudyReportFragmentsEntity fragment(String text, String... tags) throws Exception { + StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity(); fragment.setContent(text); + fragment.setContextType("REVIEW"); fragment.setContextNum(id()); fragments.insert(fragment); + for (String tag : tags) markers.addUserTag(MarkerObjectTypeEnum.FRAGMENT, fragment.getId().toString(), tag); + return fragment; + } + ScopeInput scope(String... tags) { return new ScopeInput("TAG", null, List.of(tags), "UNION"); } + RecallDetail create(ScopeInput scope) { return service.create(new CreateRecallRequest(id(), "editor", scope, null)); } + Expression expression(String title) { return new Expression(1, new ExpressionNode("root", title, "", List.of(), null, List.of())); } + SaveDraftRequest draft(RecallDetail detail, String title) { return new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), expression(title), new Timing(0, null)); } + RecallDetail save(RecallDetail detail, String title) { return service.draft(detail.getRecallNum(), draft(detail, title)); } + RecallDetail end(RecallDetail detail) { return service.end(detail.getRecallNum(), new EndRequest(id(), detail.getEditorId(), detail.getWriteToken(), detail.getExpression(), new Timing(0, null))); } + AiTaskResponse submit(RecallDetail detail, String type) { + var request = new AiTaskSubmitRequest(); request.setType(type); request.setTargetNum(detail.getRecallNum()); + request.setParams(mapper.convertValue(new AiParams(1, id(), detail.getEditorId(), detail.getWriteToken(), "RECALL_HINT".equals(type) ? "KEYWORD" : null), new TypeReference>() {})); + return ai.submit(request); + } + AiTaskEntity claim(AiTaskResponse response) { + var row = taskMapper.selectOne(Wrappers.lambdaQuery().eq(AiTaskEntity::getTaskNum, response.getTaskNum())); + return aiTasks.claimTask(row.getId()).orElseThrow(); + } + Map result(RecallAiParams input) { + var unit = input.units().get(0); var citation = new Citation(unit.unitId(), unit.start(), unit.end(), unit.text()); + var result = new RecallAiResult(1, "CHECK", "controlled-stub", "COMPLETE", + List.of(new UnitAssessment(unit.unitId(), "ANALYZED", "内容核对", null, List.of())), List.of(), + List.of(new Finding("f", "POSSIBLY_MISSING", "回想条件", "仅针对本次资料", List.of(citation), List.of())), List.of()); + return mapper.convertValue(result, new TypeReference>() {}); + } + @Test void repeatedSavesOverwriteOneExpressionAndNeverPersistEarlierText() throws Exception { + fragment("资料", "A"); var detail = create(scope("A")); + detail = save(detail, "首次输入不可保留"); detail = save(detail, "最终内容"); + var row = recalls.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallEntity::getRecallNum, detail.getRecallNum())); + assertEquals(1, recalls.selectCount(Wrappers.lambdaQuery()).intValue()); + assertFalse(row.getDocumentJson().contains("首次输入不可保留")); + var stored = json.tree(json.readStored(row.getDocumentJson(), Object.class)); + assertTrue(stored.path("detail").has("expression")); assertTrue(stored.has("reference")); + for (String key : List.of("expressionVersions", "expressionVersion", "referenceVersion", "privacyVersion", "revision", "notes")) assertFalse(stored.path("detail").has(key), key); + assertFalse(stored.has("references")); assertFalse(stored.path("reference").has("version")); + assertEquals("最终内容", service.get(detail.getRecallNum()).getExpression().root().title()); + } + @Test void createAutomaticallyCarriesMostRecentCompletedMapOnlyForExactScope() throws Exception { + fragment("资料", "A", "B"); var previous = save(create(scope("A", "B")), "上次导图"); end(previous); + var next = create(scope(" b ", "a")); assertEquals("上次导图", next.getExpression().root().title()); + assertTrue(next.getRequests().isEmpty()); assertEquals(0, next.getActiveDurationMs()); + assertEquals("", create(scope("A")).getExpression().root().title()); + var intersection = create(new ScopeInput("TAG", null, List.of("A", "B"), "INTERSECT")); assertEquals("", intersection.getExpression().root().title()); + } + @Test void actualDurationAccumulatesAcrossSegmentsAndNeverDropsBelowActive() throws Exception { + fragment("资料", "A"); var detail = create(scope("A")); + assertEquals(0L, detail.getActualDurationMs().longValue()); + detail = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), detail.getExpression(), new Timing(1000, 1200L, Instant.now()))); + assertEquals(1000L, detail.getActiveDurationMs()); assertEquals(1200L, detail.getActualDurationMs().longValue()); + detail = service.resume(detail.getRecallNum(), new ResumeRequest(id(), detail.getEditorId(), detail.getWriteToken())); + detail = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), detail.getExpression(), new Timing(500, 700L, Instant.now()))); + assertEquals(1500L, detail.getActiveDurationMs()); assertEquals(1900L, detail.getActualDurationMs().longValue()); + var current = detail; + assertThrows(RecallBusinessException.class, () -> service.draft(current.getRecallNum(), new SaveDraftRequest(id(), current.getEditorId(), current.getWriteToken(), current.getExpression(), new Timing(600, 550L, Instant.now())))); + assertThrows(RecallBusinessException.class, () -> service.draft(current.getRecallNum(), new SaveDraftRequest(id(), current.getEditorId(), current.getWriteToken(), current.getExpression(), new Timing(500, 86_400_000L, Instant.now())))); + var legacy = service.draft(current.getRecallNum(), new SaveDraftRequest(id(), current.getEditorId(), current.getWriteToken(), current.getExpression(), new Timing(800, null))); + assertEquals(1800L, legacy.getActiveDurationMs()); assertEquals(2000L, legacy.getActualDurationMs().longValue()); + var missing = service.draft(legacy.getRecallNum(), new SaveDraftRequest(id(), legacy.getEditorId(), legacy.getWriteToken(), legacy.getExpression(), new Timing(900, null, Instant.now()))); + assertEquals(1900L, missing.getActiveDurationMs()); assertEquals(2100L, missing.getActualDurationMs().longValue()); + } + @Test void expressionColorsAreOptionalAndLimitedToHexPairs() throws Exception { + fragment("资料", "A"); var detail = create(scope("A")); + var styled = new Expression(1, new ExpressionNode("root", "标题", "", List.of(), new NodeStyle("#fff8e1", "#856404"), List.of())); + var saved = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), styled, new Timing(0, null))); + assertEquals("#fff8e1", saved.getExpression().root().style().background()); + var bad = new Expression(1, new ExpressionNode("root", "标题", "", List.of(), new NodeStyle("red", "#856404"), List.of())); + assertThrows(RecallBusinessException.class, () -> service.draft(saved.getRecallNum(), new SaveDraftRequest(id(), saved.getEditorId(), saved.getWriteToken(), bad, new Timing(0, null)))); + } + @Test void aiInputStripsPresentationStylesWhileTheDraftKeepsThem() throws Exception { + fragment("资料", "A"); var detail = create(scope("A")); + var styled = new Expression(1, new ExpressionNode("root", "标题", "", List.of(), new NodeStyle("#fff8e1", "#856404"), List.of())); + var saved = service.draft(detail.getRecallNum(), new SaveDraftRequest(id(), detail.getEditorId(), detail.getWriteToken(), styled, new Timing(0, null))); + var response = submit(saved, "RECALL_HINT"); + var association = requests.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallRequestEntity::getTaskNum, response.getTaskNum())); + assertNotNull(association.getParamsJson()); + assertFalse(association.getParamsJson().contains("style")); + assertFalse(association.getParamsJson().contains("#fff8e1")); + assertEquals("#fff8e1", service.get(saved.getRecallNum()).getExpression().root().style().background()); + } + @Test void legacyDocumentsAreDeletedInsteadOfSkippedAndNewRecallStartsEmpty() throws Exception { + fragment("资料", "A"); + var detail = end(save(create(scope("A")), "旧版内容")); + var other = end(save(create(scope("A")), "另一旧版")); + for (String num : List.of(detail.getRecallNum(), other.getRecallNum())) { + var row = recalls.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallEntity::getRecallNum, num)); + row.setDocumentJson("{not valid json"); + recalls.updateById(row); + } + var failure = assertThrows(RecallBusinessException.class, () -> service.get(detail.getRecallNum())); + assertEquals("STORED_DATA_INVALID", failure.getData().reason()); + var page = service.list(1, 20, null, "TAG", null, List.of("A"), "UNION"); + assertEquals(0, page.total()); + assertTrue(page.records().isEmpty()); + assertEquals("", create(scope("A")).getExpression().root().title()); + } + @Test void creationIsIdempotentAndCurrentDraftRetryUsesSameRequest() throws Exception { + fragment("资料", "A"); var body = new CreateRecallRequest(id(), "editor", scope("A"), null); + var first = service.create(body); assertEquals(first.getRecallNum(), service.create(body).getRecallNum()); + var save = draft(first, "幂等内容"); var saved = service.draft(first.getRecallNum(), save); + assertEquals(saved.getWriteToken(), service.draft(first.getRecallNum(), save).getWriteToken()); + assertThrows(RecallBusinessException.class, () -> service.draft(first.getRecallNum(), new SaveDraftRequest(save.clientRequestId(), save.editorId(), save.writeToken(), expression("不同正文"), save.timing()))); + } + @Test void staleTokenAndReplacedEditorCannotOverwriteCurrentMap() throws Exception { + fragment("资料", "A"); var first = create(scope("A")); var stale = draft(first, "旧页面"); + var saved = save(first, "当前图"); + assertEquals("REVISION_CONFLICT", assertThrows(RecallBusinessException.class, () -> service.draft(first.getRecallNum(), stale)).getData().reason()); + service.resume(saved.getRecallNum(), new ResumeRequest(id(), "another-editor", saved.getWriteToken())); + assertEquals("EDITOR_REPLACED", assertThrows(RecallBusinessException.class, () -> save(saved, "旧页面覆盖")).getData().reason()); + assertEquals("当前图", service.get(first.getRecallNum()).getExpression().root().title()); + } + @Test void materialsArePagedAndDetailContainsNoWholeBodyOrHistory() throws Exception { + for (int index = 0; index < 23; index++) fragment("资料" + index + "😀".repeat(300), "A"); + var detail = create(scope("A")); assertEquals(23, detail.getReference().total()); + assertFalse(json.write(detail).contains("sources")); assertFalse(json.write(detail).contains("units")); + var first = service.references(detail.getRecallNum(), 1, 10); var second = service.references(detail.getRecallNum(), 2, 10); + assertEquals(10, first.records().size()); assertEquals(10, second.records().size()); assertEquals(23, second.total()); + assertNotEquals(first.records().get(0).sourceId(), second.records().get(0).sourceId()); + var source = service.source(detail.getRecallNum(), first.records().get(0).sourceId()); + assertTrue(source.content().startsWith("资料")); assertFalse(source.content().equals(first.records().get(0).preview())); + } + @Test void aiUsesAllSelectedMaterialsOrFailsWithoutClipping() throws Exception { + for (int index = 0; index < 41; index++) fragment("资料" + index, "A"); + var detail = create(scope("A")); var failed = submit(detail, "RECALL_CHECK"); + assertEquals("FAILED", failed.getStatus()); assertEquals("INPUT_TOO_LARGE", failed.getErrorCode()); assertNull(failed.getResult()); + var association = requests.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallRequestEntity::getTaskNum, failed.getTaskNum())); + assertNull(association.getParamsJson()); assertEquals(41, service.references(detail.getRecallNum(), 1, 50).total()); + } + @Test void aiInputExistsOnlyUntilSettlementAndLateResultDoesNotOverwriteMap() throws Exception { + fragment("当前知识", "A"); var detail = save(create(scope("A")), "提交时内容"); + var response = submit(detail, "RECALL_CHECK"); var task = claim(response); var input = ai.prepare(task.getTaskNum()); + assertEquals("提交时内容", input.expression().root().title()); + save(detail, "继续编辑后的内容"); + aiTasks.markSucceeded(task, result(input)); + var association = requests.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallRequestEntity::getTaskNum, task.getTaskNum())); + assertNull(association.getParamsJson()); assertEquals("SUCCEEDED", aiTasks.getByTaskNum(task.getTaskNum()).getStatus()); + assertEquals("继续编辑后的内容", service.get(detail.getRecallNum()).getExpression().root().title()); + assertFalse(json.write(service.get(detail.getRecallNum())).contains("提交时内容")); + } + @Test void failedAiAlsoClearsTransientInput() throws Exception { + fragment("知识", "A"); var detail = create(scope("A")); var response = submit(detail, "RECALL_CHECK"); var task = claim(response); + task.setErrorCode("AI_OUTPUT_LIMIT"); aiTasks.markFailed(task, "provider text must not leak"); + var association = requests.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallRequestEntity::getTaskNum, task.getTaskNum())); + assertNull(association.getParamsJson()); assertEquals("AI_OUTPUT_LIMIT", aiTasks.getByTaskNum(task.getTaskNum()).getErrorCode()); + } + @Test void deletingSourceRemovesCurrentMaterialAndAiResultsWithoutRemovingPersonalMap() throws Exception { + var fragment = fragment("私有资料", "A"); var detail = save(create(scope("A")), "个人回忆"); + var response = submit(detail, "RECALL_CHECK"); var task = claim(response); var input = ai.prepare(task.getTaskNum()); aiTasks.markSucceeded(task, result(input)); + fragmentService.deleteFragment(fragment.getId()); + var read = service.get(detail.getRecallNum()); assertEquals("个人回忆", read.getExpression().root().title()); + assertNull(service.source(detail.getRecallNum(), "fragment:" + fragment.getId()).content()); + assertEquals("SOURCE_REDACTED", read.getRequests().get(0).errorCode()); assertNull(read.getRequests().get(0).result()); + } + @Test void tenantIsolationPreventsReadingOrAutoCarryAcrossAccounts() throws Exception { + fragment("私有资料", "A"); var previous = save(create(scope("A")), "私有图"); end(previous); + StpUtil.login("other-" + id()); fragment("另一个账号的资料", "A"); + assertEquals("", create(scope("A")).getExpression().root().title()); + assertThrows(RecallBusinessException.class, () -> service.get(previous.getRecallNum())); + } + @Test void documentsWithRetiredExposureNodesStayReadableEditableAndDeletable() throws Exception { + fragment("资料", "A"); var detail = save(create(scope("A")), "历史内容"); + var row = recalls.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallEntity::getRecallNum, detail.getRecallNum())); + var document = (ObjectNode) json.tree(json.readStored(row.getDocumentJson(), Object.class)); + ((ObjectNode) document.path("detail")).setAll((ObjectNode) mapper.readTree("{\"exposures\":[{\"exposureId\":\"EXPOSE-1\",\"kind\":\"SOURCE_TEXT\"," + + "\"sourceId\":\"fragment:1\",\"itemIds\":[],\"displayedText\":\"旧的已查看正文\",\"status\":\"AVAILABLE\"}]}")); + row.setDocumentJson(json.write(document)); recalls.updateById(row); + + var read = service.get(detail.getRecallNum()); + assertEquals("历史内容", read.getExpression().root().title()); + var saved = service.draft(read.getRecallNum(), new SaveDraftRequest(id(), read.getEditorId(), read.getWriteToken(), read.getExpression(), new Timing(0, null))); + assertEquals("历史内容", saved.getExpression().root().title()); + assertFalse(recalls.selectById(row.getId()).getDocumentJson().contains("exposures")); + service.delete(saved.getRecallNum()); + assertEquals("NOT_FOUND", assertThrows(RecallBusinessException.class, () -> service.get(saved.getRecallNum())).getData().reason()); + // 暂存的 AI 输入同样带过 exposures:读存储一律忽略未知字段,不能因为旧节点读不出来就丢掉待结算任务。 + var legacyInput = json.readStored("{\"schemaVersion\":1,\"promptVersion\":\"recall-v1\",\"units\":[]," + + "\"exposures\":[{\"kind\":\"HINT\",\"displayedText\":\"旧提示\"}]," + + "\"limits\":{\"maxHintItems\":3,\"maxHintNodes\":5,\"maxFindings\":12},\"limitations\":[]}", RecallAiParams.class); + assertEquals(1, legacyInput.schemaVersion()); assertTrue(legacyInput.units().isEmpty()); + } + @Test void emptyMapCanCompleteWithoutAiOrNotes() throws Exception { + fragment("", "A"); var detail = create(scope("A")); var done = end(detail); + assertEquals("ENDED", done.getStatus()); assertEquals("", done.getExpression().root().title()); + assertNotNull(done.getEndedAt()); + } + @Test void legacyReportAndApplicationSourcesLeaveSummaryAndPaging() throws Exception { + fragment("资料", "A"); var detail = create(scope("A")); + var row = recalls.selectOne(Wrappers.lambdaQuery().eq(ReviewRecallEntity::getRecallNum, detail.getRecallNum())); + var document = (ObjectNode) json.tree(json.readStored(row.getDocumentJson(), Object.class)); + var sources = (com.fasterxml.jackson.databind.node.ArrayNode) document.path("reference").path("sources"); + sources.addObject().put("sourceId", "report:9").put("type", "REPORT").put("id", "9") + .put("title", "同源学习报告").put("content", "报告正文").put("role", "CONTEXT").put("status", "AVAILABLE"); + sources.addObject().put("sourceId", "application:9").put("type", "APPLICATION").put("id", "9") + .put("title", "应用场景").put("content", "场景内容").put("role", "CONTEXT").put("status", "AVAILABLE"); + row.setDocumentJson(json.write(document)); recalls.updateById(row); + + assertEquals(1, service.get(detail.getRecallNum()).getReference().total()); + var page = service.references(detail.getRecallNum(), 1, 10); + assertEquals(1, page.total()); assertEquals(1, page.records().size()); + assertTrue(page.records().stream().allMatch(item -> item.sourceId().startsWith("fragment:"))); + } +} diff --git a/src/test/java/com/guo/learningprogresstracker/support/TestHttpServer.java b/src/test/java/com/guo/learningprogresstracker/support/TestHttpServer.java index b1f7125..bd8fc14 100644 --- a/src/test/java/com/guo/learningprogresstracker/support/TestHttpServer.java +++ b/src/test/java/com/guo/learningprogresstracker/support/TestHttpServer.java @@ -14,6 +14,7 @@ import java.util.Locale; import java.util.List; import java.util.Map; import java.util.zip.GZIPOutputStream; +import com.guo.learningprogresstracker.service.ai.AiServiceClient; /** * 测试用本地 HTTP 服务器(JDK 内置 HttpServer),用于覆盖 TitleFetcher / AiServiceClient 等网络代码。 diff --git a/src/test/java/com/guo/learningprogresstracker/utils/MindMapTreeToolTest.java b/src/test/java/com/guo/learningprogresstracker/utils/MindMapTreeToolTest.java index 0465ebd..14d1784 100644 --- a/src/test/java/com/guo/learningprogresstracker/utils/MindMapTreeToolTest.java +++ b/src/test/java/com/guo/learningprogresstracker/utils/MindMapTreeToolTest.java @@ -1,16 +1,8 @@ package com.guo.learningprogresstracker.utils; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -18,6 +10,13 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + class MindMapTreeToolTest { /** 构建带可变 children 列表的节点 */ @@ -55,31 +54,22 @@ class MindMapTreeToolTest { @Test void parseOutline_indentAndMarkers_buildHierarchyWithBacktracking() { - String outline = String.join("\n", - "项目导图", - "- 分支A", - " * 子A1", - " + 孙A1a", - "- 分支B", - "1. 分支C", - "* 1. 组合标记"); + String outline = String.join("\n", "项目导图", "- 分支A", " * 子A1", " + 孙A1a", "- 分支B", "1. 分支C", "* 1. 组合标记"); MindMapNode root = MindMapTreeTool.parseOutline(outline); assertEquals("项目导图", root.getTitle()); assertEquals(List.of("分支A", "分支B", "分支C", "组合标记"), titles(root.getChildren())); assertEquals(List.of("子A1"), titles(root.getChildren().get(0).getChildren())); - assertEquals(List.of("孙A1a"), titles(root.getChildren().get(0).getChildren().get(0).getChildren())); + assertEquals( + List.of("孙A1a"), + titles(root.getChildren().get(0).getChildren().get(0).getChildren())); // 深层节点被解析时均被显式挂上 children 列表 assertNotNull(root.getChildren().get(0).getChildren().get(0).getChildren()); } @Test void parseOutline_tabIndent_levels() { - String outline = String.join("\n", - "根", - "\t一级A", - "\t\t二级A1", - "\t一级B"); + String outline = String.join("\n", "根", "\t一级A", "\t\t二级A1", "\t一级B"); MindMapNode root = MindMapTreeTool.parseOutline(outline); assertEquals(List.of("一级A", "一级B"), titles(root.getChildren())); assertEquals(List.of("二级A1"), titles(root.getChildren().get(0).getChildren())); @@ -87,17 +77,14 @@ class MindMapTreeToolTest { @Test void parseOutline_hashLevels_andPopBack() { - String outline = String.join("\n", - "根", - "# 一级", - "## 二级", - "### 三级", - "## 二级B"); + String outline = String.join("\n", "根", "# 一级", "## 二级", "### 三级", "## 二级B"); MindMapNode root = MindMapTreeTool.parseOutline(outline); // 实际弹栈语义:## 二级B 出栈到 level<2 时父级是一级 assertEquals(List.of("一级"), titles(root.getChildren())); assertEquals(List.of("二级", "二级B"), titles(root.getChildren().get(0).getChildren())); - assertEquals(List.of("三级"), titles(root.getChildren().get(0).getChildren().get(0).getChildren())); + assertEquals( + List.of("三级"), + titles(root.getChildren().get(0).getChildren().get(0).getChildren())); } @Test @@ -149,8 +136,8 @@ class MindMapTreeToolTest { @Test void flatten_countNodes_maxDepth() { MindMapNode leaf = new MindMapNode(); - leaf.setChildren(null); // 叶子:children 为 null - MindMapNode empty = new MindMapNode("e"); // children 为空列表 + leaf.setChildren(null); // 叶子:children 为 null + MindMapNode empty = new MindMapNode("e"); // children 为空列表 MindMapNode root = node("r", node("a", node("a1")), node("b")); @@ -214,7 +201,7 @@ class MindMapTreeToolTest { assertNull(MindMapTreeTool.extractSubtree(null, "Root")); assertNull(MindMapTreeTool.extractSubtree(root, null)); assertNull(MindMapTreeTool.extractSubtree(root, " ")); - assertNull(MindMapTreeTool.extractSubtree(root, "Root / X")); // 中途失配 + assertNull(MindMapTreeTool.extractSubtree(root, "Root / X")); // 中途失配 assertNull(MindMapTreeTool.extractSubtree(root, "Root / A / A1 / 更深")); // 末端失配 } @@ -223,7 +210,7 @@ class MindMapTreeToolTest { @Test void findClosestNode_titleMatch() { MindMapNode root = node("Root", node("Java 并发"), node("完全无关")); - MindMapNode best = MindMapTreeTool.findClosestNode(root, "java并发"); + MindMapNode best = MindMapMatchTool.findClosestNode(root, "java并发"); assertNotNull(best); assertEquals("Java 并发", best.getTitle()); } @@ -234,7 +221,7 @@ class MindMapTreeToolTest { hit.setNotes("数据库索引优化详解"); MindMapNode root = node("Root", hit, node("另一个")); - MindMapNode best = MindMapTreeTool.findClosestNode(root, "数据库索引优化"); + MindMapNode best = MindMapMatchTool.findClosestNode(root, "数据库索引优化"); assertNotNull(best); assertEquals("完全无关", best.getTitle()); } @@ -242,10 +229,10 @@ class MindMapTreeToolTest { @Test void findClosestNode_lowScoresOrInvalidInputsReturnNull() { MindMapNode root = node("Root", new MindMapNode(), node(" "), node("abcd")); - assertNull(MindMapTreeTool.findClosestNode(root, "zzzz")); // 全部低于阈值 - assertNull(MindMapTreeTool.findClosestNode(null, "x")); - assertNull(MindMapTreeTool.findClosestNode(root, null)); - assertNull(MindMapTreeTool.findClosestNode(root, " ")); + assertNull(MindMapMatchTool.findClosestNode(root, "zzzz")); // 全部低于阈值 + assertNull(MindMapMatchTool.findClosestNode(null, "x")); + assertNull(MindMapMatchTool.findClosestNode(root, null)); + assertNull(MindMapMatchTool.findClosestNode(root, " ")); } // ============ getPath ============ @@ -253,33 +240,33 @@ class MindMapTreeToolTest { @Test void getPath_hitAndMissAndNulls() { MindMapNode root = node("Root", node("A"), node("B", node("C"))); - assertEquals("Root / B / C", MindMapTreeTool.getPath(root, "C")); - assertEquals("Root", MindMapTreeTool.getPath(root, "ROOT")); // normalize 后命中根 - assertEquals("", MindMapTreeTool.getPath(root, "不存在")); - assertEquals("", MindMapTreeTool.getPath(null, "x")); - assertEquals("", MindMapTreeTool.getPath(root, null)); + assertEquals("Root / B / C", MindMapMatchTool.getPath(root, "C")); + assertEquals("Root", MindMapMatchTool.getPath(root, "ROOT")); // normalize 后命中根 + assertEquals("", MindMapMatchTool.getPath(root, "不存在")); + assertEquals("", MindMapMatchTool.getPath(null, "x")); + assertEquals("", MindMapMatchTool.getPath(root, null)); } @Test void getPath_handlesNullTitlesAlongPath() { MindMapNode root = node("Root", new MindMapNode()); - assertEquals("Root", MindMapTreeTool.getPath(root, "Root")); - assertEquals("", MindMapTreeTool.getPath(root, "不在树中")); + assertEquals("Root", MindMapMatchTool.getPath(root, "Root")); + assertEquals("", MindMapMatchTool.getPath(root, "不在树中")); } // ============ similarityScore ============ @Test void similarityScore_variousCases() { - assertEquals(1.0, MindMapTreeTool.similarityScore("Java 并发", "java并发"), 1e-9); - assertEquals(0.9, MindMapTreeTool.similarityScore("java concurrency guide", "concurrency"), 1e-9); + assertEquals(1.0, MindMapMatchTool.similarityScore("Java 并发", "java并发"), 1e-9); + assertEquals(0.9, MindMapMatchTool.similarityScore("java concurrency guide", "concurrency"), 1e-9); // bigram Jaccard:{ab,bc,cd} 与 {ab,bc,ce} 交 2 / 并 4 - assertEquals(0.5, MindMapTreeTool.similarityScore("abcd", "abce"), 1e-9); - assertEquals(0.0, MindMapTreeTool.similarityScore("", "x"), 1e-9); - assertEquals(0.0, MindMapTreeTool.similarityScore(null, "x"), 1e-9); - assertEquals(0.0, MindMapTreeTool.similarityScore("x", null), 1e-9); - assertEquals(0.0, MindMapTreeTool.similarityScore("a", "b"), 1e-9); // 双方 bigram 均为空 - assertEquals(0.9, MindMapTreeTool.similarityScore("a", "ab"), 1e-9); // 子串匹配优先于 bigram + assertEquals(0.5, MindMapMatchTool.similarityScore("abcd", "abce"), 1e-9); + assertEquals(0.0, MindMapMatchTool.similarityScore("", "x"), 1e-9); + assertEquals(0.0, MindMapMatchTool.similarityScore(null, "x"), 1e-9); + assertEquals(0.0, MindMapMatchTool.similarityScore("x", null), 1e-9); + assertEquals(0.0, MindMapMatchTool.similarityScore("a", "b"), 1e-9); // 双方 bigram 均为空 + assertEquals(0.9, MindMapMatchTool.similarityScore("a", "ab"), 1e-9); // 子串匹配优先于 bigram } // ============ mergeTrees ============ @@ -288,8 +275,8 @@ class MindMapTreeToolTest { void mergeTrees_nullSideReturnsOther() { MindMapNode oldTree = node("旧"); MindMapNode newTree = node("新"); - assertSame(newTree, MindMapTreeTool.mergeTrees(null, newTree)); - assertSame(oldTree, MindMapTreeTool.mergeTrees(oldTree, null)); + assertSame(newTree, MindMapMatchTool.mergeTrees(null, newTree)); + assertSame(oldTree, MindMapMatchTool.mergeTrees(oldTree, null)); } @Test @@ -303,7 +290,7 @@ class MindMapTreeToolTest { newChild.setChildren(new ArrayList<>(List.of(node("新子")))); MindMapNode newTree = node("新根", newChild, node("新增")); - MindMapNode merged = MindMapTreeTool.mergeTrees(oldTree, newTree); + MindMapNode merged = MindMapMatchTool.mergeTrees(oldTree, newTree); assertEquals("根", merged.getTitle()); // 保留旧树根标题 assertEquals(List.of("任务,一", "新增", "旧独有"), titles(merged.getChildren())); @@ -323,7 +310,7 @@ class MindMapTreeToolTest { MindMapNode oldNoKids = new MindMapNode(); oldNoKids.setChildren(null); MindMapNode newWithKids = node("新", node("k1")); - MindMapNode merged = MindMapTreeTool.mergeTrees(oldNoKids, newWithKids); + MindMapNode merged = MindMapMatchTool.mergeTrees(oldNoKids, newWithKids); assertNull(merged.getTitle()); assertEquals(List.of("k1"), titles(merged.getChildren())); @@ -331,7 +318,7 @@ class MindMapTreeToolTest { MindMapNode oldWithKids = node("旧", node("k2")); MindMapNode newNoKids = new MindMapNode("新2"); newNoKids.setChildren(null); - MindMapNode merged2 = MindMapTreeTool.mergeTrees(oldWithKids, newNoKids); + MindMapNode merged2 = MindMapMatchTool.mergeTrees(oldWithKids, newNoKids); assertEquals(List.of("k2"), titles(merged2.getChildren())); assertSame(oldWithKids.getChildren().get(0), merged2.getChildren().get(0)); } @@ -359,12 +346,12 @@ class MindMapTreeToolTest { @Test void fromJson_parsesValidJson_andFallsBackOnInvalid() { MindMapNode ok = MindMapTreeTool.fromJson( - "{\"title\":\"根\",\"children\":[{\"title\":\"子\",\"nodes\":[]}]}", - new ObjectMapper()); + "{\"title\":\"根\",\"children\":[{\"title\":\"子\",\"nodes\":[]}]}", new ObjectMapper()); assertEquals("根", ok.getTitle()); assertEquals("子", ok.getChildren().get(0).getTitle()); - assertEquals("解析失败", MindMapTreeTool.fromJson("not json", new ObjectMapper()).getTitle()); + assertEquals( + "解析失败", MindMapTreeTool.fromJson("not json", new ObjectMapper()).getTitle()); assertEquals("解析失败", MindMapTreeTool.fromJson(null, new ObjectMapper()).getTitle()); } }