Author SHA1 Message Date
cat-shark eb3da2e74a fix: 部署流水线改用 https 拉取代码(Gitea 已不再监听 80 端口) 2026-11-08 14:48:26 +08:00
cat-shark ddf0256210 docs: 同步 API 端点总览 2026-10-22 21:59:53 +08:00
cat-shark 0618c3970a test: 测试数据改为按目录组织,不再放进 Flyway 迁移 2026-10-22 21:59:53 +08:00
cat-shark c59efa3676 feat: 新增任务下拉选项接口 2026-10-22 21:59:53 +08:00
cat-shark 05939e3f08 feat: 新增标签导图列表接口 2026-10-22 21:59:40 +08:00
cat-shark a0a35faec8 feat: 复习总览分页与全局汇总 2026-10-22 21:59:30 +08:00
cat-shark c4017cc964 fix: 分页拦截器改到租户拦截器之后注册 2026-10-22 21:59:03 +08:00
cat-shark 13e12ba4da feat: 报告作为思维导图生成的参考上下文 2026-10-22 21:58:50 +08:00
cat-shark 6075839937 fix: 索引键长守卫漏检 CREATE INDEX
守卫一直没真正生效,两个独立缺陷:

1. CREATE INDEX 用 matches() 匹配,语句行尾的分号让它整条不匹配 ——
   仓库里 8 条独立 CREATE INDEX(含 V20261009_1 那批业务索引)全被静默跳过;
2. 多行 ALTER TABLE 的子句写在下一行,逐行解析拿到的 rest 是空的,
   由它新增的列从未登记;且守卫是在所有迁移解析完之后才解析列,
   用最终 schema 去解析早期索引,列被后续迁移改名时会误报「列无法解析」。

改为:ALTER TABLE 拼回续行、列类型在索引声明当时记录。
已用三个探针验证:引用不存在的列被拦、4080 字节超长被拦、真实迁移全绿。
2026-10-10 20:28:17 +08:00
cat-shark 1ba3ae5a04 feat: 用量统计支持用户维度报表
- 新增 ai_usage_records.user_id 与 (user_id, occurred_at) 索引,NULL 表示未归属
- 归属标记跟着请求走:AiServiceClient 提交任务时带上顶层 callerRef(当前用户 id),
  lpt-ai 原样透传,上报后落到 user_id。取不到身份就不带,绝不让 AI 调用因此失败
- breakdown 支持 groupBy=user,新增 label(登录名,未归属为「未归属」);
  summary/series/breakdown 支持 userId 过滤
2026-10-10 20:28:04 +08:00
cat-shark 650b0956de feat: 新增 AI 用量落库与统计接口
- 新增 ai_usage_records 表(系统级表,不按租户过滤)与幂等上报接口
- 新增按时间/任务类型/模型的汇总、趋势、明细查询,仅白名单用户可见
- 登录响应返回 aiAdmin,供前端决定是否展示入口
2026-10-10 18:46:01 +08:00
cat-shark 02d5c24946 fix: 标签移除后再打同名标签不再撞唯一键 2026-10-10 16:41:27 +08:00
cat-shark 4b30c88b7f feat: 标签范围回忆对比与记录口径 2026-10-10 16:08:48 +08:00
cat-shark 6a30022af5 feat: 新增标签导图存储与生成 2026-10-10 15:28:06 +08:00
cat-shark d282f1b10a docs: 移除与 meta 重复的提交规范正文 2026-10-10 15:10:06 +08:00
cat-shark 8065550924 docs: 规则分离到 roles 目录 2026-10-10 15:08:37 +08:00
cat-shark 6ea408e558 feat: 新增标签字典与打标签候选接口 2026-10-10 14:59:06 +08:00
cat-shark 99290d9fae feat: 残片归属时自动打任务名标签 2026-10-10 14:58:14 +08:00
cat-shark 7acfc7effa fix: 任务主键改由数据库自增 2026-10-10 14:55:46 +08:00
cat-shark 6bbb2362d3 docs: 通用规则收口径到 meta 的 .agents/roles 2026-10-10 14:38:43 +08:00
cat-shark f1a078ce64 docs: 补充并行与委派规则 2026-10-10 14:27:43 +08:00
cat-shark a558e2a08a fix: 学习引导不再复用进行中的任务 2026-10-10 10:52:11 +08:00
cat-shark 7fc08ebef3 fix: 透传 lpt-ai 的失败原因,避免误导成「AI 没有回应」 2026-10-10 10:41:14 +08:00
cat-shark 935a4fac00 docs: 补充 H2 与 MySQL 的迁移差异与守卫测试 2026-10-09 21:00:45 +08:00
cat-shark e5b3ef8eb6 fix: 缩短标记唯一键避免超出 InnoDB 索引长度上限 2026-10-09 21:00:33 +08:00
cat-shark dbeafba23c perf: Feed 只返回摘要与原文长度 2026-10-09 19:35:15 +08:00
cat-shark 4da3b78fa4 docs: 明确报告分段顺序 2026-10-09 19:32:50 +08:00
cat-shark e6e47e31b0 docs: 补充标记与学习引导约定并更新端点清单 2026-10-09 19:31:25 +08:00
cat-shark b51a6216ce feat: 新增学习引导链路与来源标记 2026-10-09 19:30:59 +08:00
cat-shark c6258fa6d7 feat: 新增统一标记存储与单一标记筛选 2026-10-09 19:25:34 +08:00
cat-shark 63824b26a0 feat: 新增复习反馈动作与排序三档偏好 2026-10-09 19:21:26 +08:00
cat-shark 1a99263876 test: 放宽异步投递用例的等待窗口避免抖动 2026-10-09 19:16:39 +08:00
cat-shark 3dda26307d perf: 覆盖率查询改为按任务分组取最新 2026-10-09 19:14:36 +08:00
cat-shark 7408be26c0 docs: 更新端点清单并补内容归属约定 2026-10-09 19:12:35 +08:00
cat-shark c74f73ac3c feat: 拆分记录上下文与内容归属并把报告改为结构化 2026-10-09 19:12:04 +08:00
cat-shark 9a86eadb52 chore: 移除测试控制器与测试表相关代码 2026-10-09 17:55:32 +08:00
cat-shark bad7d6b9c9 docs: 补充 AI 入站令牌配置说明 2026-10-09 15:52:39 +08:00
cat-shark 251a46887c feat: 复习 Feed 随机取样改用主键区间并固定 actuator 清单 2026-10-09 15:51:50 +08:00
cat-shark cb450b6f47 docs: 补充 AI 异步链路约定与端点变更 2026-10-09 15:07:43 +08:00
cat-shark cf380c5f09 feat: AI 调用改为异步任务并支持结果重复获取 2026-10-09 15:07:15 +08:00
cat-shark 0b695f54bf perf: 复习统计聚合下推到数据库 2026-10-09 14:56:36 +08:00
cat-shark db552182ae feat: 悬挂学习会话惰性收敛与定时兜底 2026-10-09 12:32:11 +08:00
cat-shark faaaa132c1 feat: 新增学习数据导出接口 2026-10-09 12:20:36 +08:00
cat-shark 3cc3be1c8b fix: 业务编号追加随机位并加唯一约束 2026-10-09 12:20:36 +08:00
cat-shark 67c8711eee refactor: 复习耗时聚合改为强类型结果并补充数据访问规范 2026-10-09 11:53:41 +08:00
cat-shark 3b33cd8396 feat: 新增复习耗时统计与按任务汇总 2026-10-09 11:12:37 +08:00
cat-shark af13bd57b7 fix: 生产环境不再打印全部 SQL 2026-10-09 10:52:20 +08:00
cat-shark e506c4d751 perf: 为业务主表补充索引 2026-10-09 10:52:20 +08:00
cat-shark d8c8b76c32 fix: 统一学习会话结算并修正结束幂等 2026-10-09 10:48:12 +08:00
250 changed files with 16984 additions and 1205 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ on:
env:
REGISTRY: 192.168.123.199:5000
APP: lpt-be
REPO_URL: http://git.cat-shark.xyz/cat-shark/lpt-be.git
REPO_URL: https://git.cat-shark.xyz/cat-shark/lpt-be.git
jobs:
build-and-deploy:
+75 -70
View File
@@ -2,10 +2,16 @@
> Java Spring Boot 后端,提供 REST API、数据库访问、认证鉴权。
## Git 提交规范
## 规则与技能位置
- 提交信息必须简短且使用中文,不要使用英文长句。
- 格式:`类型: 简述`,例如 `feat: 新增用户登录接口`、`fix: 修复多租户拦截器空指针`、`docs: 补充API文档`。
- 通用规则(跨仓库):meta 仓库 `.agents/roles/`(本仓库的 Git 提交规范也统一在其中的 `commit-convention.md`,本文件不再重复)
- 本仓库专属规则:`roles/`
- `roles/database-migration.md`:数据库迁移(Flyway Migration)
- `roles/data-access.md`:编码规范 · 数据访问层
- `roles/api-response.md`:响应规范、DTO 转换
- `roles/ownership-and-markers.md`:内容归属与结构化报告(归属-01 / 报告-01)、标记(标记-01)
- `roles/ai-integration.md`:学习引导(复习-06)、AI 异步链路(AI-02)
- 本仓库专属技能:`skills/`(如 `comment-cleanup`)
## 技术栈
@@ -44,21 +50,35 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
- entity 使用 `@TableName`、`@TableField` 映射数据库字段。
- mapStruct 承载 DTO 转换。
## API 端点总览(44 个)
## API 端点总览(86 个)
| 模块 | 端点数 | 端点 |
|------|--------|------|
| 登录认证 | 2 | `POST /login`, `POST /logout` |
| 学习会话 | 11 | `PUT /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}`, `POST /study-sessions/{sessionNum}/study-sessions/continue`, `POST /study-sessions/{sessionNum}/study-sessions/pause`, `POST /study-sessions/{sessionNum}/study-sessions/ended`, `GET /study-sessions/{sessionNum}/all-fragments`, `GET /study-sessions/{sessionNum}/report-draft`, `GET /study-sessions/tasks/{taskNum}/fragments`, `GET /study-sessions/tasks/{taskNum}/reports`, `GET /study-sessions/active` |
| 任务管理 | 13 | `GET/POST /tasks`, `GET/PUT/DELETE /tasks/{taskId}`, `GET/PUT /tasks/priority-weights`, `GET/POST /tasks/{taskNum}/applications`, `PUT/DELETE /tasks/applications/{id}`, `GET /tasks/{taskNum}/study-sessions/start-or-continue`, `GET /tasks/{taskNum}/not-ended-study-session` |
| 复习与导图 | 13 | `GET /review/feed`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/regenerate`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/recall`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}` |
| 学习残片 | 3 | `POST /report-fragments`, `PUT /report-fragments/{id}`, `GET /report-fragments/session/{sessionNum}` |
| 学习会话 | 11 | `PUT /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}/expectation`, `GET /study-sessions/{sessionNum}`, `POST /study-sessions/{sessionNum}/study-sessions/continue`, `POST /study-sessions/{sessionNum}/study-sessions/pause`, `POST /study-sessions/{sessionNum}/study-sessions/ended`, `POST /study-sessions/{sessionNum}/study-sessions/abort`, `GET /study-sessions/{sessionNum}/all-fragments`, `GET /study-sessions/tasks/{taskNum}/fragments`, `GET /study-sessions/tasks/{taskNum}/reports`, `GET /study-sessions/active` |
| 任务管理 | 15 | `GET/POST /tasks`, `GET/PUT/DELETE /tasks/{taskId}`, `GET/PUT /tasks/priority-weights`, `GET /tasks/options`, `GET/POST /tasks/{taskNum}/applications`, `PUT/DELETE /tasks/applications/{id}`, `GET /tasks/{taskNum}/study-sessions/start-or-continue`, `GET /tasks/{taskNum}/not-ended-study-session`, `GET /tasks/{taskId}/deletion-preview` |
| 复习与导图 | 19 | `GET /review/feed`, `PUT /review/feed/{fragmentId}/feedback`, `POST /review/feed/{fragmentId}/touched`, `GET /review/sort-preference`, `PUT /review/sort-preference`, `GET /review/summary`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/report/{id}/structured`, `PUT /review/report/{id}`, `DELETE /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}` |
| 标签导图 | 4 | `POST /review/tag-mind-map/query`, `PUT /review/tag-mind-map`, `GET /review/tag-mind-map/list`, `POST /review/tag-mind-map/recall-records` |
| 知识碎片 | 6 | `POST /report-fragments`, `PUT /report-fragments/{id}`, `PUT /report-fragments/{id}/ownership`, `DELETE /report-fragments/{id}`, `GET /report-fragments/session/{sessionNum}`, `GET /report-fragments/pending-ownership` |
| 数据导出 | 2 | `GET /export/task/{taskNum}`, `GET /export/range` |
| 学习引导 | 5 | `POST /review/guidance`, `POST /review/guidance/{guidanceNum}/turns`, `GET /review/guidance/{guidanceNum}`, `POST /review/guidance/{guidanceNum}/fragments`, `DELETE /review/guidance/{guidanceNum}` |
| 统一标记 | 12 | `GET /markers`, `POST /markers`, `POST /markers/batch`, `DELETE /markers/{id}`, `PUT /markers/rename`, `GET /markers/filter`, `GET /markers/tags`, `GET/POST /markers/tags/dictionary`, `PUT/DELETE /markers/tags/dictionary/{id}`, `GET /markers/tags/candidates` |
| AI 异步任务 | 3 | `POST /ai/tasks`, `GET /ai/tasks/{taskNum}`, `GET /ai/tasks/latest` |
| AI 用量统计 | 5 | `GET /ai/usage/permission`, `GET /ai/usage/summary`, `GET /ai/usage/series`, `GET /ai/usage/breakdown`, `GET /ai/usage/balance` |
| 内部(服务间) | 1 | `POST /internal/ai-usage/records` |
| 工具 | 1 | `GET /utils/fetch-title?url=...` |
| 测试 | 1 | `GET /test/{id}` |
## 数据库(10 个核心表)
> 「AI 用量统计」只对 `lpt.ai-usage.admin-usernames` 白名单用户开放:`permission` 用 `allowed=false`
> 让前端静默隐藏入口,其余 4 个接口直接拒绝。`POST /internal/ai-usage/records` 是 lpt-ai 的上报入口,
> 没有登录态,在 `WebMvcConfig` 里排除了 Sa-Token,改用 `x-api-token` 与 `lpt.ai-usage.report-token` 比对。
`users`, `tasks`, `study_sessions`, `study_reports`, `study_report_fragments`, `study_expectations`, `task_applications`, `review_standard_mind_maps`, `review_recall_records`, `user_priority_weights`
## 数据库(11 个核心表)
`users`, `tasks`, `study_sessions`, `study_reports`, `study_report_fragments`, `study_expectations`, `task_applications`, `review_standard_mind_maps`, `review_recall_records`, `user_priority_weights`, `ai_usage_records`
> `ai_usage_records` 是**系统级表**,已加入 `MybatisPlusConfig.EXCLUDE_TABLES`:
> 记录由 lpt-ai 上报、没有登录用户,而且用量是运维口径(面板要看全部调用)。
> 若按 `created_by` 过滤,管理员只能看到自己触发的那几次,面板等于永远是空的。
## 关键机制
@@ -68,20 +88,26 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
- 响应格式:`CommonResult<T>` 统一包装 `{ code, message, data }`。
- CORS:可配置,local profile 允许所有来源。
## 响应规范
### 行级数据隔离(多租户拦截器)
- 成功:`CommonResult.success(data)`,code=200。
- 业务错误:`CommonResult.error(msg)`,code=400,HTTP 200。
- 未登录:`GlobalExceptionHandler.handleNotLogin()`,HTTP 401 + code=401。
- 参数校验失败:`MethodArgumentNotValidException`,code=400。
- 用户可见错误文案必须口语化、可理解,避免“无法生成”“不存在”等技术化表述;技术细节写入日志。例如无学习报告时应提示“这个任务还没开始学习哦,学习后产生学习报告后再来吧”,而不是“没有学习报告,无法生成思维导图”。
- **配置类:** `MybatisPlusConfig` 注册 `TenantLineInnerInterceptor`
- **租户字段:** `created_by`(每个业务表的创建人字段)
- **租户值来源:** `StpUtil.getLoginIdAsString()`(当前登录用户)
- **自动注入:** 所有 SELECT/UPDATE/DELETE 语句自动追加 `WHERE created_by = #{当前用户}`
- **归属校验:** 查询单条记录时拦截器自动校验 `created_by`,非本人数据直接返回空
- **排除表:** `user`、`flyway_schema_history`、`databasechangelog`、`databasechangeloglock`、`ai_usage_records`
(`ai_usage_records` 是系统级表,用量要统计全部调用,不能按 `created_by` 切分)
## DTO 转换
### 自动填充(MetaObjectHandler)
- MapStruct 编译期生成 `*ConvertImpl.java`,同名属性自动映射。
- 默认 `unmappedTargetPolicy = IGNORE`。
- 自定义映射使用 `@Mapping(source, target)`。
- 增删 DTO 字段后必须重新编译,否则生成代码不含新字段。
- **created_by / updated_by:** 插入/更新时自动填充为当前登录用户
- **created_time / updated_time:** 插入/更新时自动填充当前时间
### 认证鉴权(Sa-Token)
- **会话管理:** 基于 `StpUtil` 的登录/登出/会话查询
- **权限校验:** `@SaCheckPermission` 注解式权限控制
- **未登录处理:** 全局异常处理器捕获 `NotLoginException` 返回 401
## CORS
@@ -112,8 +138,35 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
- 配置:`lpt.ai-service.url=http://localhost:5199`
- 超时:600s
- 入站令牌(安全-03):`lpt.ai-service.token`,空表示 lpt-ai 未启用令牌校验。
部署侧用 `LPT_AI-SERVICE_TOKEN`(`lpt-secrets/lpt-ai-token`,`optional: true`)注入;
注意变量名带连字符才能映射到 `lpt.ai-service.token`,与既有的 `LPT_AI-SERVICE_URL` 保持一致。
- AI 服务不可用时自动降级到内置规则引擎(`BuiltinMindMapGenerator`)
## AI 用量统计
- **数据来源**:lpt-ai 每次任务结算后上报一条记录(`POST /internal/ai-usage/records`,按 `record_id` 幂等)。
上报失败由 lpt-ai 侧本地 outbox 重试;4xx 属于确定性拒绝,lpt-ai 会丢弃这批并计数,不会无限重试。
- **token 的 null 语义**:`prompt_tokens` 等列为 `NULL` 表示上游没上报,`0` 表示上游明确上报为 0。
两者必须区分(`unreported_usage_calls` 就是靠它算的),**不得用 0 顶替 null**。
- **计价在 lpt-ai 侧冻结**:`cost_usd` 是上报时按当期价目算好的,本服务只做聚合与汇率换算,
改价不会重写历史账。汇率走 `lpt.ai-usage.usd-to-cny`。
- **口径**:只统计 `is_llm_call = 1` 的记录(`/fetch-title` 这类不消耗 LLM)。
- **分组维度**:`breakdown?groupBy=taskType|model|user`。用户维度下 `key` 是用户 id
(未归属为 `null`)、`label` 是登录名(未归属为「未归属」,查不到登录名时回退为 `key`);
其它维度下 `label` 等于 `key`,前端统一渲染 `label` 即可。用户筛选用 `userId` 参数。
- **归属链路(callerRef)**:lpt-ai 不知道调用方是谁,所以归属标记跟着请求走——
`AiServiceClient` 提交任务时把当前用户 id 作为**顶层** `callerRef` 带上(取不到身份就不带,
记为未归属,绝不让 AI 调用因此失败),lpt-ai 原样透传,上报后落到 `user_id`。
标记在 LLM 调用之前就已确定,因此没有「上报先到、归属还没写回」的竞态。
**`callerRef` 不能放进 `params`**:params 会喂给 prompt 模板、也参与 lpt-ai 的幂等键。
- **`user_id` 不是租户列**:本表在 `EXCLUDE_TABLES` 中,`user_id` 只用于分组与筛选。
改成租户过滤会让管理员只能看到自己触发的调用,面板等于永远是空的。
- 配置:`lpt.ai-usage.admin-usernames`(白名单,部署用 `LPT_AI-USAGE_ADMIN-USERNAMES`)、
`lpt.ai-usage.report-token`(上报令牌,部署用 `LPT_AI-USAGE_REPORT-TOKEN`,与 lpt-ai 的
`LPT_AI_REPORT_TOKEN` 共用 `lpt-secrets/lpt-ai-report-token`)。
- 前端入口:`lpt-fe` 的 `/ai-usage`,入口按钮在「退出登录」左侧,显隐由登录响应里的 `aiAdmin` 决定。
## 启动命令
```bash
@@ -127,51 +180,3 @@ mvn spring-boot:run # 启动(默认 profile: local)
|------|------|------|------|
| lpt-fe | `../lpt-fe/` | 5158 | Vue 3 前端,通过 `/api` 代理调用本服务 |
| lpt-ai | `../lpt-ai/` | 5199 | AI 服务,本服务通过 HTTP 调用其异步任务接口 |
## 项目规范
## 数据库迁移(Flyway Migration)
### 命名规则
- 脚本格式:`V{YYYYMMDD}_{序号}__{描述}.sql`
- 日期必须使用**实际编写日期**,不得使用过去的日期
- 序号从 1 开始,同一天多个脚本递增
- 描述使用下划线分隔的英文短语
### 核心原则
- **不可变性**:已执行的迁移脚本永远不得修改
- **只增不减**:数据库变更只能通过新增迁移脚本实现
- **向后兼容**:新脚本应兼容已有数据
### 操作规范
- 删除表:创建新迁移脚本,使用 `DROP TABLE IF EXISTS`
- 修改表结构:使用 `ALTER TABLE` 语句
- 新增表:创建新迁移脚本,使用 `CREATE TABLE`
## 框架机制
### 行级数据隔离(多租户拦截器)
- **配置类:** `MybatisPlusConfig` 注册 `TenantLineInnerInterceptor`
- **租户字段:** `created_by`(每个业务表的创建人字段)
- **租户值来源:** `StpUtil.getLoginIdAsString()`(当前登录用户)
- **自动注入:** 所有 SELECT/UPDATE/DELETE 语句自动追加 `WHERE created_by = #{当前用户}`
- **归属校验:** 查询单条记录时拦截器自动校验 `created_by`,非本人数据直接返回空
- **排除表:** `user`、`flyway_schema_history`、`databasechangelog`、`databasechangeloglock`
### 自动填充(MetaObjectHandler)
- **created_by / updated_by:** 插入/更新时自动填充为当前登录用户
- **created_time / updated_time:** 插入/更新时自动填充当前时间
### 认证鉴权(Sa-Token)
- **会话管理:** 基于 `StpUtil` 的登录/登出/会话查询
- **权限校验:** `@SaCheckPermission` 注解式权限控制
- **未登录处理:** 全局异常处理器捕获 `NotLoginException` 返回 401
## 编码规范
### 数据访问层
- **优先使用纯 MyBatis-Plus Java API**(`Wrappers.<T>lambdaQuery()`、`selectList`、`selectById` 等),避免手写 XML SQL
- 复杂查询通过 `Wrappers` 链式构建条件,必要时使用 `.apply()` 拼接原生 SQL 片段
+24
View File
@@ -0,0 +1,24 @@
# AI 集成
- **功能**:约束学习引导与 AI 异步生成链路的实现方式。
- **何时用**:接入或改动 AI 相关功能、新增后台任务、处理生成类能力时。
## 学习引导(复习-06)
一次引导是一次**复习行为**,有自己的记录实体 `review_guidance_conversations`:
- 产出的知识碎片以它作为**记录上下文**(`context_type=REVIEW`),默认内容归属为被引导概念所属任务,并带 `FROM_GUIDANCE` 系统标记。
- 复习耗时记在会话行上(与回忆对比同一口径)。
- 多轮对话复用 AI 异步任务:每轮提交一个 `GUIDANCE` 任务,前端轮询取回复;AI 回复会写回会话轮次,供下一轮作为上下文。
- **没有降级形态**:AI 不可用时该链路直接失败,前端把入口置为不可用。
## AI 异步链路(AI-02)
生成类能力(回忆对比、标准导图、报告草稿)不在请求线程里等 AI:
- 前端 `POST /ai/tasks` 提交,秒级拿到 `taskNum`;随后轮询 `GET /ai/tasks/{taskNum}` 直到 `SUCCEEDED`/`FAILED`。
- 结果写在 `ai_tasks.result_payload`,按 `taskNum` 可重复获取,刷新或离开页面都不丢。
- 同一用户 + 同一类型 + 同一目标已有进行中任务时复用该任务(AI-04),不重复生成。
- 执行器在 `ai-task-*` 线程池里跑;提交后立即投递,`@Scheduled` 兜底扫描接手投递失败或进程重启的任务。
- **后台线程必须显式声明身份**:执行线程没有 Web 上下文,租户拦截器与 `MetaObjectHandler` 字段自动填充都取不到当前用户。执行器用 `TenantContext.callAs(task.createdBy, ...)` 绑定任务所属用户;请求线程不受影响(没有绑定时仍走 `StpUtil`)。新增后台任务时必须照此处理,否则会抛 `NotWebContextException`。
- 禁止在 `@Transactional` 方法内调用 AI:等待 AI 期间不得占用数据库连接。
+19
View File
@@ -0,0 +1,19 @@
# 响应规范与 DTO 转换
- **功能**:统一 API 的响应形态、错误文案风格与 DTO 转换方式。
- **何时用**:新增或修改接口返回值、处理异常、增删 DTO 字段或自定义映射时。
## 响应规范
- 成功:`CommonResult.success(data)`,code=200。
- 业务错误:`CommonResult.error(msg)`,code=400,HTTP 200。
- 未登录:`GlobalExceptionHandler.handleNotLogin()`,HTTP 401 + code=401。
- 参数校验失败:`MethodArgumentNotValidException`,code=400。
- 用户可见错误文案必须口语化、可理解,避免“无法生成”“不存在”等技术化表述;技术细节写入日志。例如无学习报告时应提示“这个任务还没开始学习哦,学习后产生学习报告后再来吧”,而不是“没有学习报告,无法生成思维导图”。
## DTO 转换
- MapStruct 编译期生成 `*ConvertImpl.java`,同名属性自动映射。
- 默认 `unmappedTargetPolicy = IGNORE`。
- 自定义映射使用 `@Mapping(source, target)`。
- 增删 DTO 字段后必须重新编译,否则生成代码不含新字段。
+19
View File
@@ -0,0 +1,19 @@
# 数据访问层编码规范
- **功能**:规定数据访问层的实现方式,避免手写 SQL 与字符串 key 取值带来的跨库隐患。
- **何时用**:编写 Mapper 或查询逻辑、需要聚合或联表、评审数据访问代码时。
## 编码规范
### 数据访问层
- **优先使用纯 MyBatis-Plus Java API**(`Wrappers.<T>lambdaQuery()`、`selectList`、`selectById` 等),避免手写 XML SQL
- 复杂查询通过 `Wrappers` 链式构建条件,必要时使用 `.apply()` 拼接原生 SQL 片段
- **查询结果一律用类承载,禁止 `selectMaps` + 字符串 key 取值**
- MyBatis 对 Map 结果直接用 JDBC 列名作 key,不做属性映射:`map-underscore-to-camel-case` 与「属性名大小写不敏感」只对类结果生效。而数据库的标识符大小写规则各不相同(MySQL 保留别名、H2/PostgreSQL 转小写、Oracle 转大写),`row.get("taskNum")` 会在部分库上静默取到 null,表现为「数据莫名变 0」而不是报错
- 单列聚合用 `selectObjs`,多列聚合用下面的自定义 Mapper 方法
- **`Wrapper` 表达不了的查询(`SUM`/`GROUP BY`/多表 `JOIN`)收敛到 Mapper 层**,用自定义方法 + **显式结果类**(`dto/` 下的类或实体),参考 `ReviewRecallRecordMapper.sumReviewDurationByTask` → `dto/TaskReviewDuration` + `resources/mapper/ReviewRecallRecordMapper.xml`
- 结果映射:列名与属性能对应时可用自动映射,但 `map-underscore-to-camel-case` 必须在 `application.yml` 里显式声明(已配置),不要依赖框架默认值;出现别名、计算列或列名与属性不一致时必须写显式 `<resultMap>`
- **自定义 SQL 不会被 `@TableLogic` 自动追加逻辑删除条件**,必须显式写 `deleted = 0`;租户条件 `created_by = ?` 仍由 `TenantLineInnerInterceptor` 自动追加
- 上述两条不能只靠 mock 单测,需落库集成测试守住(参考 `ReviewDurationIntegrationTest`)
- 反向约束:`Wrapper` 能表达的查询不要为「类型安全」提前下沉为自定义 SQL;确实要下沉时,SQL 只留在 Mapper 层,不要在 service 里拼字符串
+35
View File
@@ -0,0 +1,35 @@
# 数据库迁移
- **功能**:约束 Flyway 迁移脚本的写法,让数据库结构变更可追溯、可部署。
- **何时用**:新增或修改表结构、编写迁移脚本、调整索引、部署前核对历史数据时。
## 数据库迁移(Flyway Migration)
### 测试用 H2、部署用 MySQL:这几件事 H2 测不出来
迁移脚本在测试里跑的是 H2(`MODE=MySQL`),它与真实 MySQL 的差异会造成「测试全绿、部署起不来」:
- **索引键长度上限**:InnoDB 对索引键有 3072 字节硬上限(DYNAMIC 行格式),超了直接报 error 1071;
utf8mb4 下 `VARCHAR(n)` 要按 `4n` 字节算,多列唯一键很容易越界。**H2 不校验**。
→ 改动任何索引后跑 `MigrationIndexKeyLengthTest`(它直接读迁移文件复算键长)。
- **整型显示宽度**:`TINYINT(1)` 在 MySQL 8.0.17 起被标记弃用(MySQL 9.7 文档确认**尚未移除**,只是弃用)。
这里刻意保留 `TINYINT(1)`:它正是 JDBC 把列映射成 `Boolean` 的惯用声明,换成裸 `TINYINT` 会让布尔字段的映射行为依赖连接参数。
- **遇脏数据要响亮失败**:`V20261009_3`(业务编号唯一约束)与 `V20261009_5`(计时列类型修正)
在历史数据不干净时会直接让启动失败。这是有意的——宁可失败也不静默跳过约束。部署前先按迁移注释里的核对 SQL 检查。
### 命名规则
- 脚本格式:`V{YYYYMMDD}_{序号}__{描述}.sql`
- 日期必须使用**实际编写日期**,不得使用过去的日期
- 序号从 1 开始,同一天多个脚本递增
- 描述使用下划线分隔的英文短语
### 核心原则
- **不可变性**:已执行的迁移脚本永远不得修改
- **只增不减**:数据库变更只能通过新增迁移脚本实现
- **向后兼容**:新脚本应兼容已有数据
### 操作规范
- 删除表:创建新迁移脚本,使用 `DROP TABLE IF EXISTS`
- 修改表结构:使用 `ALTER TABLE` 语句
- 新增表:创建新迁移脚本,使用 `CREATE TABLE`
+31
View File
@@ -0,0 +1,31 @@
# 内容归属与标记
- **功能**:区分知识碎片的「记录上下文」与「内容归属」两个维度,并统一管理标记元信息。
- **何时用**:改动碎片归属、生成或查看报告、取材导图、新增或检索标记时。
## 内容归属与结构化报告(归属-01 / 报告-01)
知识碎片有两个**互相独立**的维度,改动任何一处都要先分清是哪一维:
- **记录上下文**(`context_type` + `context_num`):产生于哪次学习会话或复习行为。由系统确定、**不可变、不可为空**;用于时间统计与「这份报告里有哪些碎片」。
- **内容归属**(`owner_task_num`):内容在知识结构上属于哪个任务。由用户确定、**可变、可为空**(为空即待归类);用于导图取材、按任务检索与统计。
由此得出的几条硬约束:
- **导图、按任务检索、碎片计数一律按内容归属**(`owner_task_num`),不再用「该任务的会话所产生的报告/碎片」。
- **报告按会话生成**,报告的任务来自它所属会话——这与上一条是两个视角,是有意为之,不是重复。
- 新建碎片时内容归属默认取该会话所属任务;用户可以改到别的任务或清空为待归类。
- 归属变化(或碎片删除)会把**原任务与新任务**的标准导图标记为 `needs_update=1`;重建由用户手动触发,不自动跑 AI。
- 报告只落库三段文本(`session_summary` / `expectation_verdict` / `free_summary`);「按归属分组的碎片」**不落库**,查看时按当前归属实时聚合,以免与导图取材出现两套口径。文档里的展示顺序是:会话摘要 → 预期达成判断 → 按归属分组的碎片 → 自由总结。
- 删除报告**不**连带删除碎片;删除任务时碎片保留并把归属置空(进入待归类),其余(会话、报告、导图、回忆记录、应用场景)随任务软删除。
## 标记(标记-01)
标记是附加在对象上的轻量元信息,**统一存放**,新增一种标记不改各功能表结构。
- **可挂对象只有知识碎片与学习任务**:报告是会话的派生结果且已有「按归属分组」这一维度;会话是时间轴对象,其流程性信息留在主体上。
- **两类彻底分开**:系统标记走 `SystemMarkerEnum` 固定词表、由系统写入、用户只读;用户标签自由增删改。分开的理由是「找出所有来自 X 的内容」这类检索必须可靠。
- **系统标记成对(名 = 值)**,用户标签只有名(标签名本身就是全部信息)。
- 检索只提供**单一标记筛选**;标记对用户全部可见,标签可改名可删除(改名安全:标记不参与聚合口径)。
- **标记不是状态**:会话状态、报告可否修订、导图是否待更新这类流程判断留在主体上。碎片上的复习反馈(已掌握/稍后再看)也因此落在碎片自身字段,不进标记表。
- 对象被删除时清理其标记(`MarkerService.removeAllMarkers`)。
@@ -0,0 +1,64 @@
package com.guo.learningprogresstracker.common;
import lombok.Getter;
/**
* 学习会话的时间口径(会话-04 起改为可配置的值对象)。
*
* <p>番茄钟长度、遗忘判定阈值、硬兜底阈值与有效时间下限集中在此处,避免阈值散落在实体与服务的各个角落。
* 生产路径由 Spring 从 {@code lpt.study-time} 配置构建并注入;{@link #DEFAULT} 只保留设计口径的默认值,
* 供实体自身的默认重载与单测使用,不要在服务里直接用它。</p>
*/
@Getter
public class StudyTimePolicy {
/** 与 lpt-docs 设计口径一致的默认值 */
public static final StudyTimePolicy DEFAULT = new StudyTimePolicy(25, 50, 120, 600);
/**
* 番茄钟长度(分钟)。
*/
private final int workDurationMinutes;
/**
* 遗忘判定阈值(分钟):通常为 2 × 番茄钟。
*/
private final int forgetThresholdMinutes;
/**
* 硬兜底阈值(分钟):进行中的会话超过该时长未收敛,服务端强制暂停。
*/
private final int forcePauseMinutes;
/**
* 有效学习时间下限(秒)。
*/
private final long minEffectiveTimeSeconds;
public StudyTimePolicy(int workDurationMinutes, int forgetThresholdMinutes,
int forcePauseMinutes, long minEffectiveTimeSeconds) {
if (workDurationMinutes <= 0) {
throw new IllegalArgumentException("番茄钟长度必须大于 0 分钟");
}
if (forgetThresholdMinutes < workDurationMinutes) {
throw new IllegalArgumentException("遗忘判定阈值不能小于番茄钟长度");
}
if (forcePauseMinutes < forgetThresholdMinutes) {
throw new IllegalArgumentException("硬兜底阈值不能小于遗忘判定阈值");
}
if (minEffectiveTimeSeconds < 0) {
throw new IllegalArgumentException("有效学习时间下限不能为负数");
}
this.workDurationMinutes = workDurationMinutes;
this.forgetThresholdMinutes = forgetThresholdMinutes;
this.forcePauseMinutes = forcePauseMinutes;
this.minEffectiveTimeSeconds = minEffectiveTimeSeconds;
}
/**
* 番茄钟长度(毫秒)。
*/
public long workDurationMillis() {
return workDurationMinutes * 60_000L;
}
}
@@ -0,0 +1,56 @@
package com.guo.learningprogresstracker.common;
/**
* 显式的租户上下文(AI-02)。
*
* <p>租户拦截器与公共字段自动填充都从 {@code StpUtil} 取当前用户,而它依赖 Web 请求上下文。
* 后台执行线程(AI 任务执行器、定时收敛)没有请求上下文,直接调用会抛
* {@code NotWebContextException};这里让后台线程显式声明「我以哪个用户身份在执行」。</p>
*
* <p>取值优先级:<b>本上下文优先</b>,没有时才回落到 {@code StpUtil}。这样请求线程的行为完全不变,
* 后台线程也只能以任务所属用户的身份执行,不会意外变成「无租户」而看到全部数据。</p>
*/
public final class TenantContext {
/**
* 执行身份。
*
* @param loginId 登录用户
* @param device 设备类型,可为 null(后台任务通常没有设备信息)
*/
public record Identity(String loginId, String device) {
}
private static final ThreadLocal<Identity> CURRENT = new ThreadLocal<>();
private TenantContext() {
}
/** 取当前执行身份;未设置时返回 null(表示应回落到 StpUtil) */
public static Identity get() {
return CURRENT.get();
}
/** 在指定身份下执行;执行结束后恢复原身份,避免线程池复用造成身份串号 */
public static void runAs(String loginId, String device, Runnable action) {
callAs(loginId, device, () -> {
action.run();
return null;
});
}
/** 在指定身份下执行并返回结果(异常原样向外抛,由调用方决定如何回写) */
public static <T> T callAs(String loginId, String device, java.util.function.Supplier<T> action) {
Identity previous = CURRENT.get();
CURRENT.set(new Identity(loginId, device));
try {
return action.get();
} finally {
if (previous == null) {
CURRENT.remove();
} else {
CURRENT.set(previous);
}
}
}
}
@@ -0,0 +1,30 @@
package com.guo.learningprogresstracker.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* AI 任务执行器装配(AI-02)。
* <p>执行线程与请求线程分离,AI 调用不会占用 HTTP 请求线程,也不会持有请求期间打开的数据库连接。</p>
*/
@Configuration
@EnableAsync
public class AiTaskConfig {
public static final String AI_TASK_EXECUTOR = "aiTaskExecutor";
@Bean(name = AI_TASK_EXECUTOR)
public ThreadPoolTaskExecutor aiTaskExecutor(AiTaskProperties properties) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getExecutorCoreSize());
executor.setMaxPoolSize(properties.getExecutorMaxSize());
executor.setQueueCapacity(properties.getExecutorQueueCapacity());
executor.setThreadNamePrefix("ai-task-");
// 队列满时由调用线程执行,避免任务被静默丢弃(定时兜底仍会接手)
executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
@@ -0,0 +1,33 @@
package com.guo.learningprogresstracker.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* AI 异步任务配置(AI-02)。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "lpt.ai-task")
public class AiTaskProperties {
/** 单个任务允许的最长执行时间(秒):超过则视为进程中断,回收后可重试 */
private long stuckTimeoutSeconds = 900;
/** 兜底扫描间隔(毫秒) */
private long scanIntervalMs = 3000;
/** 首次兜底扫描的延迟(毫秒):让「提交后立即投递」先执行 */
private long scanInitialDelayMs = 3000;
/** 单次扫描最多处理多少个任务 */
private int scanBatchSize = 10;
/** 立即投递用的线程池大小 */
private int executorCoreSize = 2;
private int executorMaxSize = 4;
private int executorQueueCapacity = 50;
}
@@ -0,0 +1,29 @@
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;
/**
* AI 用量统计配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "lpt.ai-usage")
public class AiUsageProperties {
/** 可见「AI 用量统计」入口的用户名白名单(按 {@code user.user_name} 精确匹配) */
private List<String> adminUsernames = List.of("admin");
/** lpt-ai 上报用量时携带的令牌;为空表示不校验 */
private String reportToken = "";
/** 代理查询上游余额的超时(秒) */
private int balanceTimeoutSeconds = 10;
/** 费用展示用的美元兑人民币汇率:{@code costCny = costUsd × 该值} */
private BigDecimal usdToCny = BigDecimal.valueOf(7);
}
@@ -2,6 +2,7 @@ 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 lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
@@ -20,18 +21,35 @@ public class AutoTableField implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createdBy", StpUtil::getLoginIdAsString, String.class);
this.strictInsertFill(metaObject, "createdBy", AutoTableField::currentLoginId, String.class);
this.strictInsertFill(metaObject, "createdTime", LocalDateTime::now, LocalDateTime.class);
this.strictInsertFill(metaObject, "lastModifiedBy", StpUtil::getLoginIdAsString, String.class);
this.strictInsertFill(metaObject, "lastModifiedBy", AutoTableField::currentLoginId, String.class);
this.strictInsertFill(metaObject, "lastModifiedTime", LocalDateTime::now, LocalDateTime.class);
this.strictInsertFill(metaObject, "deviceInfo", AutoTableField::currentDevice, String.class);
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "lastModifiedBy", StpUtil::getLoginIdAsString, String.class);
this.strictInsertFill(metaObject, "lastModifiedBy", AutoTableField::currentLoginId, String.class);
this.strictInsertFill(metaObject, "lastModifiedTime", LocalDateTime::now, LocalDateTime.class);
this.strictInsertFill(metaObject,"deviceInfo",StpUtil::getLoginDevice,String.class);
this.strictInsertFill(metaObject, "deviceInfo", AutoTableField::currentDevice, String.class);
}
/**
* 当前登录用户:后台执行线程通过 {@link TenantContext} 显式声明身份,请求线程仍走 StpUtil。
*/
static String currentLoginId() {
TenantContext.Identity identity = TenantContext.get();
return identity != null ? identity.loginId() : StpUtil.getLoginIdAsString();
}
/**
* 当前设备:后台任务通常没有设备信息,返回 null 时跳过该项填充(保持列为空而不是写脏值)。
*/
static String currentDevice() {
TenantContext.Identity identity = TenantContext.get();
return identity != null ? identity.device() : StpUtil.getLoginDevice();
}
}
@@ -1,6 +1,7 @@
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.inner.PaginationInnerInterceptor;
@@ -22,24 +23,34 @@ import java.util.List;
public class MybatisPlusConfig {
/**
* 不需要租户过滤的表(仅排除不含 created_by 的系统表)
* 不需要租户过滤的表(仅排除不含 created_by 或不该按 created_by 过滤的表)
*
* <p>{@code ai_usage_records} 是系统级表:记录由 lpt-ai 通过内部接口上报,请求里没有登录用户,
* created_by 只是审计列;用量又是运维口径——管理员要看的是**全部**调用。
* 若按 created_by 过滤,每个人只能看到自己触发的那几次调用,面板等于永远空的。</p>
*/
private static final List<String> EXCLUDE_TABLES = Arrays.asList(
"user",
"flyway_schema_history",
"databasechangelog",
"databasechangeloglock"
"databasechangeloglock",
"ai_usage_records"
);
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页拦截器必须注册,否则 selectPage 不会生成 LIMIT / COUNT
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
// 顺序很重要:MyBatis-Plus 要求「多租户 → 分页」。
// 分页的 count 语句是从「当前已处理的 SQL」派生的;若分页先注册,
// count 会在租户条件追加之前就派生出来,导致 total 把其他用户的行也算进去
// (records 仍然正确,只有分页总数跨租户,极难发现)。
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
@Override
public Expression getTenantId() {
return new StringValue(StpUtil.getLoginIdAsString());
// 后台执行线程(AI 任务、定时收敛)通过 TenantContext 显式声明身份;
// 请求线程没有设置,仍走 StpUtil,行为完全不变
TenantContext.Identity identity = TenantContext.get();
return new StringValue(identity != null ? identity.loginId() : StpUtil.getLoginIdAsString());
}
@Override
@@ -52,6 +63,8 @@ public class MybatisPlusConfig {
return EXCLUDE_TABLES.contains(tableName.toLowerCase());
}
}));
// 分页拦截器必须注册,否则 selectPage 不会生成 LIMIT / COUNT
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
@@ -0,0 +1,24 @@
package com.guo.learningprogresstracker.config;
import com.guo.learningprogresstracker.common.StudyTimePolicy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 学习会话的时间口径装配(会话-04)。
* <p>阈值来自 {@link StudyTimeProperties};非法组合在启动时直接失败,避免运行期出现「兜底阈值比遗忘阈值还小」这类矛盾配置。</p>
*/
@Configuration
@EnableScheduling
public class StudyTimeConfig {
@Bean
public StudyTimePolicy studyTimePolicy(StudyTimeProperties properties) {
return new StudyTimePolicy(
properties.getWorkDurationMinutes(),
properties.getForgetThresholdMinutes(),
properties.getForcePauseMinutes(),
properties.getMinEffectiveTimeSeconds());
}
}
@@ -0,0 +1,35 @@
package com.guo.learningprogresstracker.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 学习会话的时间口径配置(会话-04)。
*
* <p>番茄钟长度、遗忘判定阈值、硬兜底阈值与有效时间下限集中在这里,改口径不需要改代码。
* 默认值与 `lpt-docs` 的设计口径一致:25 分钟番茄钟、50 分钟遗忘判定、2 小时硬兜底。</p>
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "lpt.study-time")
public class StudyTimeProperties {
/** 番茄钟长度(分钟):单个学习段落的上限 */
private int workDurationMinutes = 25;
/** 遗忘判定阈值(分钟):超过该时长无操作,按「忘了点暂停/结束」只结算一个番茄钟 */
private int forgetThresholdMinutes = 50;
/** 硬兜底阈值(分钟):进行中的会话超过该时长仍未结算,由服务端强制收敛 */
private int forcePauseMinutes = 120;
/** 有效学习时间下限(秒):低于该值的一次学习不计入总学习时间 */
private long minEffectiveTimeSeconds = 600;
/** 低频定时收敛扫描的间隔(毫秒) */
private long scanIntervalMs = 600_000;
/** 是否开启低频定时收敛(测试环境可关掉,避免与用例互相干扰) */
private boolean scanEnabled = true;
}
@@ -28,7 +28,9 @@ public class WebMvcConfig implements WebMvcConfigurer {
StpUtil.checkLogin();
}))
.addPathPatterns("/**")
.excludePathPatterns("/login");
// /login:登录接口本身不能要求登录态;
// /internal/**:服务间接口(lpt-ai 用量上报),调用方没有登录态,改用 x-api-token 自校验
.excludePathPatterns("/login", "/internal/**");
}
@Override
@@ -0,0 +1,56 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.AiTaskResponse;
import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
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.*;
/**
* AI 异步任务控制层(AI-02)。
*
* <p>提交与查询分离:提交接口秒级返回任务标识,前端随后轮询查询接口拿结果。
* 这样刷新或离开页面都不会丢结果,AI 已消耗的 token 也不会白费。</p>
*/
@RequestMapping("/ai/tasks")
@RestController
@Validated
@RequiredArgsConstructor
public class AiTaskController {
private final AiTaskService aiTaskService;
/**
* 提交 AI 任务。
* <p>同一目标已有进行中任务时直接返回该任务(AI-04:对外是任务状态,而不是可能为空的实体)。</p>
*/
@PostMapping
public CommonResult<AiTaskResponse> submit(@Valid @RequestBody AiTaskSubmitRequest request)
throws ErrorParameterException, NotFindEntitiesException {
return CommonResult.success(aiTaskService.submit(request));
}
/**
* 查询任务状态与结果;结果可重复获取。
*/
@GetMapping("/{taskNum}")
public CommonResult<AiTaskResponse> getTask(@PathVariable String taskNum) throws NotFindEntitiesException {
return CommonResult.success(aiTaskService.getByTaskNum(taskNum));
}
/**
* 查询某目标最近的 AI 任务,用于离开页面再回来时恢复生成状态。
*
* @return 无任务时 data 为 null
*/
@GetMapping("/latest")
public CommonResult<AiTaskResponse> getLatestTask(@RequestParam String type,
@RequestParam String targetNum) {
return CommonResult.success(aiTaskService.findLatest(type, targetNum));
}
}
@@ -0,0 +1,72 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.AiUsageBalance;
import com.guo.learningprogresstracker.dto.AiUsageBreakdownItem;
import com.guo.learningprogresstracker.dto.AiUsagePermission;
import com.guo.learningprogresstracker.dto.AiUsageSeriesPoint;
import com.guo.learningprogresstracker.dto.AiUsageSummary;
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 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)。
*
* <p>用量记录是系统级数据,只有白名单用户能看:{@code permission} 用 {@code allowed=false}
* 让前端静默隐藏入口,其余接口直接拒绝,避免入口藏起来了、接口却谁都能拉。</p>
*/
@RestController
@RequestMapping("/ai/usage")
@RequiredArgsConstructor
public class AiUsageController {
private static final String NO_PERMISSION_MESSAGE = "没有查看权限";
private final AiUsageService aiUsageService;
/** 当前用户能否查看用量面板;非白名单返回 200 + allowed=false */
@GetMapping("/permission")
public CommonResult<AiUsagePermission> permission() {
return CommonResult.success(new AiUsagePermission(aiUsageService.isAdmin()));
}
@GetMapping("/summary")
public CommonResult<AiUsageSummary> summary(AiUsageQuery query) {
if (!aiUsageService.isAdmin()) {
return CommonResult.error(NO_PERMISSION_MESSAGE);
}
return CommonResult.success(aiUsageService.summary(query));
}
@GetMapping("/series")
public CommonResult<List<AiUsageSeriesPoint>> series(AiUsageQuery query) throws ErrorParameterException {
if (!aiUsageService.isAdmin()) {
return CommonResult.error(NO_PERMISSION_MESSAGE);
}
return CommonResult.success(aiUsageService.series(query));
}
@GetMapping("/breakdown")
public CommonResult<List<AiUsageBreakdownItem>> breakdown(AiUsageQuery query) throws ErrorParameterException {
if (!aiUsageService.isAdmin()) {
return CommonResult.error(NO_PERMISSION_MESSAGE);
}
return CommonResult.success(aiUsageService.breakdown(query));
}
/** 上游余额;lpt-ai 未配置或查询失败时返回 {@code configured=false},不算错误 */
@GetMapping("/balance")
public CommonResult<AiUsageBalance> balance() {
if (!aiUsageService.isAdmin()) {
return CommonResult.error(NO_PERMISSION_MESSAGE);
}
return CommonResult.success(aiUsageService.balance());
}
}
@@ -0,0 +1,62 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.config.AiUsageProperties;
import com.guo.learningprogresstracker.dto.AiUsageIngestResult;
import com.guo.learningprogresstracker.dto.request.AiUsageRecordRequest;
import com.guo.learningprogresstracker.dto.request.AiUsageReportRequest;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.service.AiUsageService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
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)。
*
* <p>这是服务间接口,不是用户接口:调用方是 lpt-ai 进程,没有登录态,
* 因此 {@code /internal/**} 已在 {@code WebMvcConfig} 中排除 Sa-Token 登录校验,
* 改用 {@code x-api-token} 与 {@code lpt.ai-usage.report-token} 比对(配置为空表示不校验)。</p>
*/
@RestController
@RequestMapping("/internal/ai-usage")
@RequiredArgsConstructor
public class AiUsageInternalController {
/** 契约 1:单次最多 200 条 */
static final int MAX_RECORDS_PER_REPORT = 200;
private final AiUsageService aiUsageService;
private final AiUsageProperties properties;
/**
* 上报用量记录。
*
* <p>按 {@code recordId} 幂等:重复上报不报错,只在结果里体现为 {@code duplicated}。</p>
*/
@PostMapping("/records")
public CommonResult<AiUsageIngestResult> report(
@RequestHeader(name = "x-api-token", required = false) String apiToken,
@Valid @RequestBody AiUsageReportRequest request) throws ErrorParameterException {
if (!isTokenAccepted(apiToken)) {
return CommonResult.error("上报令牌不正确");
}
List<AiUsageRecordRequest> records = request.getRecords();
if (records.size() > MAX_RECORDS_PER_REPORT) {
return CommonResult.error("单次最多上报 " + MAX_RECORDS_PER_REPORT + " 条记录");
}
return CommonResult.success(aiUsageService.ingest(records));
}
/** 契约 1:report-token 为空表示 lpt-ai 未启用令牌校验,直接放行 */
private boolean isTokenAccepted(String apiToken) {
String expected = properties.getReportToken();
return expected == null || expected.isBlank() || expected.equals(apiToken);
}
}
@@ -0,0 +1,50 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.ExportResult;
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 lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
/**
* 数据导出控制层(导出-01):把学习报告、知识碎片与任务统计导出为 Markdown / JSON。
*/
@RequestMapping("/export")
@RestController
@Validated
@RequiredArgsConstructor
public class ExportController {
private final ExportService exportService;
/**
* 导出单个学习任务的全部学习记录
* @param format markdown(默认)或 json
*/
@GetMapping("/task/{taskNum}")
public CommonResult<ExportResult> exportTask(
@PathVariable String taskNum,
@RequestParam(defaultValue = "markdown") String format)
throws NotFindEntitiesException, OperationFailedException {
return CommonResult.success(exportService.exportTask(taskNum, format));
}
/**
* 按时间范围导出学习记录(起止日期都可省略,都省略为全部时间)
* @param format markdown(默认)或 json
*/
@GetMapping("/range")
public CommonResult<ExportResult> exportRange(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
@RequestParam(defaultValue = "markdown") String format)
throws OperationFailedException {
return CommonResult.success(exportService.exportRange(startDate, endDate, format));
}
}
@@ -0,0 +1,123 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.ReviewTiming;
import com.guo.learningprogresstracker.dto.request.AiTaskSubmitRequest;
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 java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 学习引导控制层(复习-06)。
*
* <p>多轮对话复用 AI 异步任务(AI-02):每一轮提交一个 {@code GUIDANCE} 任务,前端轮询拿回复。
* 因此生成期间可以离开页面,回来继续;一轮的耗时也不会占用请求线程。</p>
*
* <p>产出的知识碎片走碎片既有逻辑,只是记录上下文是这次复习行为、并带「来自学习引导」系统标记。</p>
*/
@RequestMapping("/review/guidance")
@RestController
@Validated
@RequiredArgsConstructor
public class GuidanceController {
private final GuidanceService guidanceService;
private final AiTaskService aiTaskService;
/**
* 开启一次学习引导并提交第一个问题(AI 任务)。
*/
@PostMapping
@Operation(summary = "开启学习引导:返回引导编号与首个 AI 任务编号")
public CommonResult<Map<String, Object>> start(@RequestBody Map<String, String> body)
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);
Map<String, Object> result = new LinkedHashMap<>();
result.put("guidanceNum", conversation.getGuidanceNum());
result.put("taskNum", conversation.getTaskNum());
result.put("concept", conversation.getConcept());
result.put("aiTaskNum", submitTurn(conversation.getGuidanceNum()).getTaskNum());
return CommonResult.success(result);
}
/**
* 继续一轮:提交用户的回答/追问,返回本轮 AI 任务编号
*/
@PostMapping("/{guidanceNum}/turns")
public CommonResult<AiTaskResponse> continueTurn(@PathVariable String guidanceNum,
@RequestBody Map<String, String> body)
throws NotFindEntitiesException, ErrorParameterException {
guidanceService.appendUserTurn(guidanceNum, body == null ? null : body.get("message"));
return CommonResult.success(submitTurn(guidanceNum));
}
/**
* 读取这次引导的当前状态(含对话轮次),用于离开页面后回来继续
*/
@GetMapping("/{guidanceNum}")
public CommonResult<ReviewGuidanceConversationEntity> getConversation(@PathVariable String guidanceNum)
throws NotFindEntitiesException {
return CommonResult.success(guidanceService.getByGuidanceNum(guidanceNum));
}
/**
* 用户确认产出:把这次引导的收获记成一条知识碎片。
* <p>不确认就不产生任何数据。</p>
*/
@PostMapping("/{guidanceNum}/fragments")
public CommonResult<StudyReportFragmentsEntity> confirmFragment(@PathVariable String guidanceNum,
@RequestBody Map<String, Object> body)
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));
}
/**
* 放弃这次引导:不产出任何数据
*/
@DeleteMapping("/{guidanceNum}")
public CommonResult<Void> abandon(@PathVariable String guidanceNum) throws NotFindEntitiesException {
guidanceService.abandon(guidanceNum);
return CommonResult.success();
}
/** 提交一轮学习引导任务:targetNum 是引导编号,执行器会带上会话里的历史轮次 */
private AiTaskResponse submitTurn(String guidanceNum) throws ErrorParameterException, NotFindEntitiesException {
AiTaskSubmitRequest request = new AiTaskSubmitRequest();
request.setType("GUIDANCE");
request.setTargetNum(guidanceNum);
return aiTaskService.submit(request);
}
private static LocalDateTime parseTime(Object value) {
if (!(value instanceof String text) || text.isBlank()) {
return null;
}
try {
return LocalDateTime.parse(text.trim());
} catch (DateTimeParseException e) {
return null;
}
}
}
@@ -1,8 +1,10 @@
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.exception.AppException;
import com.guo.learningprogresstracker.service.AiUsageService;
import com.guo.learningprogresstracker.service.LoginService;
import com.guo.learningprogresstracker.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
@@ -20,14 +22,17 @@ public class LoginController {
private final LoginService loginService;
private final UserService userServiceImpl;
private final AiUsageService aiUsageService;
@Operation(summary = "登录API")
@PostMapping("/login")
public CommonResult<String> login(@RequestBody LoginBody loginBody) throws AppException {
public CommonResult<LoginResult> login(@RequestBody LoginBody loginBody) throws AppException {
String userId = userServiceImpl.authenticate(loginBody.getUsername(), loginBody.getPassword());
String token = loginService.login(userId);
// 用量面板的入口是否显示由服务端白名单决定,前端只读这个布尔值
boolean aiAdmin = aiUsageService.isAdmin();
//todo 参数传递未加密
return CommonResult.success("登录成功!", token);
return CommonResult.success("登录成功!", new LoginResult(token, aiAdmin));
}
@Operation(summary = "退出登录API")
@@ -0,0 +1,154 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.MarkerUsage;
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 java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* 统一标记控制层(标记-01)。
*
* <p>标记对用户全部可见;用户标签可增删改,系统标记只读。
* 检索只提供「单一标记筛选」,不做多标记组合——标签的唯一作用就是检索,而组合筛选目前没有真实场景。</p>
*/
@RequestMapping("/markers")
@RestController
@Validated
@RequiredArgsConstructor
public class MarkerController {
private final MarkerService markerService;
/**
* 列出某个对象上的全部标记(系统标记与用户标签一起返回,前端按 kind 区分展示)
*/
@GetMapping
public CommonResult<List<MarkerEntity>> listByObject(@RequestParam String objectType,
@RequestParam String objectNum) {
return CommonResult.success(markerService.listByObject(MarkerObjectTypeEnum.parse(objectType), objectNum));
}
/**
* 批量列出多个对象的标记(列表页一次取回一页,避免逐个请求)
*/
@PostMapping("/batch")
public CommonResult<Map<String, List<MarkerEntity>>> listByObjects(
@RequestParam String objectType,
@RequestBody Collection<String> objectNums) {
return CommonResult.success(
markerService.listByObjects(MarkerObjectTypeEnum.parse(objectType), objectNums));
}
/**
* 给对象打一个用户标签(幂等)
*/
@PostMapping
@Operation(summary = "打用户标签;系统标记只能由系统写入,不开放此接口")
public CommonResult<MarkerEntity> addUserTag(@RequestBody Map<String, String> body)
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));
}
/**
* 删除一个用户标签;系统标记不可删除
*/
@DeleteMapping("/{id}")
public CommonResult<Void> deleteMarker(@PathVariable Integer id)
throws ErrorParameterException, NotFindEntitiesException {
markerService.deleteMarker(id);
return CommonResult.success();
}
/**
* 重命名一个用户标签(影响所有带该标签的对象)
*/
@PutMapping("/rename")
public CommonResult<Integer> renameUserTag(@RequestBody Map<String, String> body)
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));
}
/**
* 按标记筛选对象(点标签即筛选):返回带该标记的对象标识列表
*/
@GetMapping("/filter")
public CommonResult<List<String>> 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));
}
/**
* 当前用户用过的标签及使用情况(标签管理入口)
*/
@GetMapping("/tags")
public CommonResult<List<MarkerUsage>> listUserTagUsage() {
return CommonResult.success(markerService.listUserTagUsage());
}
/**
* 标签字典:打标签的候选标签(尚未挂在任何对象上的也算)
*/
@GetMapping("/tags/dictionary")
public CommonResult<List<UserTagEntity>> listDictionaryTags() {
return CommonResult.success(markerService.listDictionaryTags());
}
/**
* 往字典里新建一个(空)标签;同名(按去空格、大小写不敏感)已存在时幂等返回既有项
*/
@PostMapping("/tags/dictionary")
public CommonResult<UserTagEntity> createDictionaryTag(@RequestBody Map<String, String> body)
throws ErrorParameterException {
String tagName = body == null ? null : body.get("tagName");
return CommonResult.success(markerService.createDictionaryTag(tagName));
}
/**
* 字典标签改名:只影响候选,不改动任何对象上已经打好的标记
*/
@PutMapping("/tags/dictionary/{id}")
public CommonResult<UserTagEntity> renameDictionaryTag(@PathVariable Integer id,
@RequestBody Map<String, String> body)
throws ErrorParameterException, NotFindEntitiesException {
String newName = body == null ? null : body.get("newName");
return CommonResult.success(markerService.renameDictionaryTag(id, newName));
}
/**
* 删除字典标签:只影响候选,不改动任何对象上已经打好的标记
*/
@DeleteMapping("/tags/dictionary/{id}")
public CommonResult<Void> deleteDictionaryTag(@PathVariable Integer id) throws NotFindEntitiesException {
markerService.deleteDictionaryTag(id);
return CommonResult.success();
}
/**
* 打标签的候选/建议:字典标签 ∪ 已使用过的用户标签(含自动任务名标签),支持关键字过滤
*/
@GetMapping("/tags/candidates")
public CommonResult<List<String>> listTagCandidates(@RequestParam(required = false) String keyword) {
return CommonResult.success(markerService.listTagCandidates(keyword));
}
}
@@ -1,9 +1,14 @@
package com.guo.learningprogresstracker.controller;
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.request.RecallCompareRequest;
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.ReviewFeedbackRequest;
import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity;
import com.guo.learningprogresstracker.entity.ReviewStandardMindMapEntity;
@@ -45,11 +50,66 @@ public class ReviewController {
}
/**
* 获取任务维度的复习统计汇总
* 提交复习反馈动作(复习-02):标记或取消「已掌握」「稍后再看」。
* <p>只调整出现概率,不产生状态展示、不统计总数、不做待复习列表。</p>
*/
@PutMapping("/feed/{fragmentId}/feedback")
public CommonResult<ReviewFeedbackRequest> submitFeedback(
@PathVariable Integer fragmentId,
@RequestBody ReviewFeedbackRequest request) throws NotFindEntitiesException {
return CommonResult.success(reviewService.submitFeedback(fragmentId, request));
}
/**
* 记录一次「接触」(展开查看 / 进入回忆对比时调用):刷新最近接触时间,作为排序的第三个信号。
*/
@PostMapping("/feed/{fragmentId}/touched")
public CommonResult<Void> touchFragment(@PathVariable Integer fragmentId) throws NotFindEntitiesException {
reviewService.touchFragment(fragmentId);
return CommonResult.success();
}
/**
* 读取复习排序偏好(复习-01)
*/
@GetMapping("/sort-preference")
public CommonResult<ReviewSortPreference> getSortPreference() {
return CommonResult.success(reviewService.getSortPreference());
}
/**
* 保存复习排序偏好(复习-01):三档预设,不做精确权重。
*/
@PutMapping("/sort-preference")
public CommonResult<ReviewSortPreference> saveSortPreference(@RequestBody Map<String, String> body) {
String preset = body == null ? null : body.get("preset");
return CommonResult.success(reviewService.saveSortPreference(preset));
}
/**
* 复习总览的全局汇总(任务/报告/碎片总数)。
*
* <p>列表接口分页后,前端只能看到当前页;把每页相加会得到「本页合计」而不是总数,
* 因此汇总单独出接口,口径不受分页影响。</p>
*/
@GetMapping("/summary")
public CommonResult<ReviewSummary> summary() {
return CommonResult.success(reviewService.summary());
}
/**
* 分页获取任务维度的复习统计汇总。
*
* <p>分页不只为了排版:聚合(时长/报告数/碎片数)只算当前这一页的任务,
* 不再对全部任务做 IN 聚合。{@code markerName} 把「点标签即筛选」下推到服务端,
* 否则客户端只能筛当前页、total 也会不对。</p>
*/
@GetMapping("/tasks")
public CommonResult<List<ReviewTaskStats>> getReviewTaskStats() {
return CommonResult.success(reviewService.getReviewTaskStats());
public CommonResult<Page<ReviewTaskStats>> getReviewTaskStats(
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
@RequestParam(value = "markerName", required = false) String markerName) {
return CommonResult.success(reviewService.getReviewTaskStats(pageNum, pageSize, markerName));
}
/**
@@ -69,13 +129,42 @@ public class ReviewController {
}
/**
* 获取报告详情
* 获取报告详情(原始实体)
*/
@GetMapping("/report/{id}")
public CommonResult<StudyReportsEntity> getReportDetail(@PathVariable int id) throws NotFindEntitiesException {
return CommonResult.success(reviewService.getReportDetail(id));
}
/**
* 获取学习报告详情:三段文本 + 按当前内容归属实时聚合的碎片分组(归属-01)
*/
@GetMapping("/report/{id}/structured")
public CommonResult<StudyReportDetail> getReportDetailStructured(@PathVariable int id)
throws NotFindEntitiesException {
return CommonResult.success(reviewService.getReportDetailStructured(id));
}
/**
* 修改学习报告的三段文本
*/
@PutMapping("/report/{id}")
public CommonResult<Void> updateReport(@PathVariable int id,
@RequestBody UpdateStudyReportRequest request)
throws NotFindEntitiesException {
reviewService.updateReport(id, request);
return CommonResult.success();
}
/**
* 删除学习报告(软删除)。不连带删除知识碎片:碎片是独立原料,可能已归属到其他任务。
*/
@DeleteMapping("/report/{id}")
public CommonResult<Void> deleteReport(@PathVariable int id) throws NotFindEntitiesException {
reviewService.deleteReport(id);
return CommonResult.success();
}
/**
* 获取残片详情
*/
@@ -87,26 +176,15 @@ public class ReviewController {
// ============ 标准思维导图与回忆对比 ============
/**
* 获取或自动生成任务的标准思维导图
* 获取任务的标准思维导图。
*
* <p>读取不触发生成(AI-02):不存在时 data 为 null,由前端提交
* {@code POST /ai/tasks}(type=MIND_MAP)后轮询结果。</p>
*/
@GetMapping("/standard-mind-map/{taskNum}")
public CommonResult<ReviewStandardMindMapEntity> getStandardMindMap(
@PathVariable String taskNum) throws NotFindEntitiesException, OperationFailedException {
return CommonResult.success(standardMindMapService.getOrGenerate(taskNum));
}
/**
* 强制重新生成任务的标准思维导图
* @param mode 生成模式:full(全量覆盖,默认)或 incremental(增量合并)
*/
@PostMapping("/standard-mind-map/{taskNum}/regenerate")
public CommonResult<ReviewStandardMindMapEntity> regenerateStandardMindMap(
@PathVariable String taskNum,
@RequestParam(defaultValue = "full") String mode) throws NotFindEntitiesException, OperationFailedException {
if ("incremental".equals(mode)) {
return CommonResult.success(standardMindMapService.incrementalGenerate(taskNum));
}
return CommonResult.success(standardMindMapService.regenerate(taskNum));
@PathVariable String taskNum) throws NotFindEntitiesException {
return CommonResult.success(standardMindMapService.getExisting(taskNum));
}
/**
@@ -119,16 +197,6 @@ public class ReviewController {
return CommonResult.success(standardMindMapService.updateByOutline(taskNum, request.getOutline()));
}
/**
* 用户提交回忆大纲,与标准导图对比
*/
@PostMapping("/standard-mind-map/{taskNum}/recall")
public CommonResult<ReviewStandardMindMapEntity> recallCompare(
@PathVariable String taskNum,
@Valid @RequestBody RecallCompareRequest request) throws NotFindEntitiesException, OperationFailedException {
return CommonResult.success(standardMindMapService.recallCompare(taskNum, request.getRecallOutline(), request.getFocusPath()));
}
/**
* 在标准导图中查找与给定内容最匹配的节点
*/
@@ -90,7 +90,9 @@ public class StudySessionController {
@PostMapping("/{sessionNum}/study-sessions/ended")
public CommonResult<Void> endedStudySession(@PathVariable("sessionNum") String sessionNum,
@Valid @RequestBody EndedStudySessionRequest request) throws ErrorParameterException {
String message = studySessionsServiceImpl.endedStudySession(sessionNum, request.getContent());
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();
}
@@ -114,14 +116,6 @@ public class StudySessionController {
}
/**
* 生成学习报告草稿:AI 聚合残片(不可用时降级为拼接),返回给前端作为编辑起点
*/
@GetMapping("/{sessionNum}/report-draft")
public CommonResult<String> getReportDraft(@PathVariable("sessionNum") String sessionNum) throws ErrorParameterException {
return CommonResult.success("请求成功", studySessionsServiceImpl.generateReportDraft(sessionNum));
}
/** 分页查询任务的残片历史 */
@GetMapping("/tasks/{taskNum}/fragments")
public CommonResult<Page<StudyReportFragmentsEntity>> getTaskFragments(
@@ -0,0 +1,83 @@
package com.guo.learningprogresstracker.controller;
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.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.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;
/**
* 标签导图控制层(闭环-04)。
*
* <p>按标签复习与按任务复习并存:任务导图仍走 {@code /review/standard-mind-map/{taskNum}},
* 这里只负责以「标签集合 + 取数模式」为范围的那一半。</p>
*
* <p>生成与回忆对比都不在请求线程里等 AI:由前端提交 {@code POST /ai/tasks}
* (type=TAG_MIND_MAP / TAG_RECALL_COMPARE)后轮询结果,与既有 AI 任务链路同一约定。</p>
*/
@RequestMapping("/review/tag-mind-map")
@RestController
@Validated
@RequiredArgsConstructor
public class TagMindMapController {
private final ReviewTagMindMapService reviewTagMindMapService;
/**
* 读取该范围的状态:范围键、标签集合、已有导图与最近一次回忆对比。
*
* <p>读取不触发生成:没有导图时 {@code map} 为 null,由前端提交生成任务。
* 用请求体而不是查询参数,是因为标签名由用户自由输入、可能含逗号。</p>
*/
@PostMapping("/query")
public CommonResult<TagMindMapView> query(@Valid @RequestBody TagScopeRequest request)
throws ErrorParameterException {
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
return CommonResult.success(reviewTagMindMapService.query(scope));
}
/**
* 用户编辑标签导图(大纲文本形式);该范围还没有导图时保存即为新建。
*/
@PutMapping
public CommonResult<ReviewTagMindMapEntity> updateTagMindMap(
@Valid @RequestBody UpdateTagMindMapRequest request) throws ErrorParameterException {
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
return CommonResult.success(reviewTagMindMapService.updateByOutline(scope, request.getOutline()));
}
/**
* 分页列出已经生成过导图的标签范围:「按标签复习」的主入口。
*
* <p>用户先看到已有导图(标签集合 + 取数模式),可直接进入复习或把新碎片补充进去,
* 不必先选标签再判断这个范围有没有导图。读取不触发生成。</p>
*/
@GetMapping("/list")
public CommonResult<Page<TagMindMapSummary>> list(
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
return CommonResult.success(reviewTagMindMapService.listMaps(pageNum, pageSize));
}
/**
* 该范围的回忆对比记录(倒序,最近一次在最前);范围里没有记录时返回空列表。
*/
@PostMapping("/recall-records")
public CommonResult<List<ReviewRecallRecordEntity>> listRecallRecords(
@Valid @RequestBody TagScopeRequest request) throws ErrorParameterException {
TagScope scope = reviewTagMindMapService.resolveScope(request.getTags(), request.getMode());
return CommonResult.success(reviewTagMindMapService.listRecallRecords(scope));
}
}
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.protobuf.ServiceException;
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;
@@ -84,8 +85,15 @@ public class TaskController {
return CommonResult.success();
}
@GetMapping("/{taskId}/deletion-preview")
@Operation(summary = "删除任务前的影响范围:将删除什么、将保留什么(碎片进入待归类)")
public CommonResult<com.guo.learningprogresstracker.dto.TaskDeletionSummary> previewDeletion(
@PathVariable("taskId") String taskId) {
return CommonResult.success(tasksService.previewDeletion(taskId));
}
@DeleteMapping("/{taskId}")
@Operation(summary = "删除指定任务")
@Operation(summary = "删除指定任务(保留其知识碎片并进入待归类)")
public CommonResult<Void> deleteTask(@PathVariable("taskId") String taskId) throws ServerException {
tasksService.deleteTask(taskId);
return CommonResult.success();
@@ -121,6 +129,12 @@ public class TaskController {
return CommonResult.success();
}
@GetMapping("/options")
@Operation(summary = "全部任务的最小选项(归类下拉用)")
public CommonResult<List<TaskOption>> taskOptions() {
return CommonResult.success(tasksService.taskOptions());
}
@GetMapping
@Operation(summary = "获取所有任务列表")
public CommonResult<Page<TaskInfo>> tasksList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@@ -1,37 +0,0 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.entity.TestTableEntity;
import com.guo.learningprogresstracker.exception.AppException;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
import com.guo.learningprogresstracker.service.TestTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class TestController {
@Autowired
TestTableService testTableService;
@GetMapping("/test/{id}")
public CommonResult<TestTableEntity> getTestEntityById(@PathVariable("id") String id) throws Exception {
log.info("testGet请求访问");
if ("1".equals(id)) {
throw new AppException("测试AppException");
} else if ("2".equals(id)) {
throw new ErrorParameterException("测试ErrorParameterException");
}else if ("3".equals(id)) {
throw new NotFindEntitiesException("测试NotFindEntitiesException");
}else if ("4".equals(id)) {
throw new OperationFailedException("测试OperationFailedException");
}
TestTableEntity testTableEntity = testTableService.getTestEntityById(id);
return CommonResult.success(testTableEntity);
}
}
@@ -12,9 +12,10 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 学习残片控制层
* 知识碎片控制层(归属-01 起同时承载「内容归属」的调整动作)。
*/
@RequestMapping("/report-fragments")
@RestController
@@ -24,7 +25,7 @@ public class reportFragmentsController {
private final StudyReportFragmentsServiceImpl studyReportFragmentsServiceImpl;
/**
* 创建学习残片
* 创建知识碎片(记录上下文为当前学习会话,内容归属默认取该会话所属任务)
*/
@PostMapping
public CommonResult<Void> createFragments(@Valid @RequestBody CreateFragmentsRequest request) throws NotFindEntitiesException {
@@ -33,21 +34,49 @@ public class reportFragmentsController {
}
/**
* 更新学习残片
* 修改知识碎片正文与内容归属(记录上下文不可变)
*/
@PutMapping("/{id}")
public CommonResult<Void> updateFragments(@PathVariable Integer id,
@Valid @RequestBody UpdateFragmentsRequest request) throws NotFindEntitiesException {
@RequestBody UpdateFragmentsRequest request) throws NotFindEntitiesException {
studyReportFragmentsServiceImpl.updateFragments(id, request);
return CommonResult.success();
}
/**
* 获取指定会话的所有学习残片
* 调整内容归属;body 传 {"ownerTaskNum": "TASK-xxx"},传空字符串表示清空归属(回到待归类)
*/
@PutMapping("/{id}/ownership")
public CommonResult<Void> assignOwnership(@PathVariable Integer id,
@RequestBody Map<String, String> body) throws NotFindEntitiesException {
String ownerTaskNum = body == null ? null : body.get("ownerTaskNum");
studyReportFragmentsServiceImpl.assignOwnership(id, ownerTaskNum);
return CommonResult.success();
}
/**
* 删除知识碎片(软删除)
*/
@DeleteMapping("/{id}")
public CommonResult<Void> deleteFragment(@PathVariable Integer id) throws NotFindEntitiesException {
studyReportFragmentsServiceImpl.deleteFragment(id);
return CommonResult.success();
}
/**
* 获取指定会话产生的所有知识碎片(记录上下文为会话)
*/
@GetMapping("/session/{sessionNum}")
public CommonResult<List<StudyReportFragmentsEntity>> getFragmentsBySession(@PathVariable String sessionNum) {
List<StudyReportFragmentsEntity> fragments = studyReportFragmentsServiceImpl.getFragmentsBySession(sessionNum);
return CommonResult.success(fragments);
}
/**
* 待归类内容:还没有确定内容归属的碎片
*/
@GetMapping("/pending-ownership")
public CommonResult<List<StudyReportFragmentsEntity>> getPendingOwnershipFragments() {
return CommonResult.success(studyReportFragmentsServiceImpl.getPendingOwnershipFragments());
}
}
@@ -0,0 +1,54 @@
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;
/**
* AI 任务对外视图(AI-02)。
* <p>提交与查询都返回它:前端只依赖 {@code status} 与 {@code result},
* 不需要在请求线程里等 AI(也就不会出现「AI 成功了但客户端已超时」)。</p>
*/
@Data
public class AiTaskResponse {
@Schema(description = "AI 任务编号")
private String taskNum;
@Schema(description = "任务类型:RECALL_COMPARE / MIND_MAP / REPORT_DRAFT")
private String type;
@Schema(description = "目标编号:学习任务编号或学习会话编号")
private String targetNum;
@Schema(description = "状态:PENDING / RUNNING / SUCCEEDED / FAILED")
private String status;
@Schema(description = "失败原因(用户可见文案)")
private String errorMessage;
@Schema(description = "提交时间")
private LocalDateTime createdTime;
@Schema(description = "结束时间")
private LocalDateTime finishedTime;
@Schema(description = "成功结果,随任务类型不同;未完成时为 null")
private Map<String, Object> result;
public static AiTaskResponse from(AiTaskEntity entity, Map<String, Object> result) {
AiTaskResponse response = new AiTaskResponse();
response.setTaskNum(entity.getTaskNum());
response.setType(entity.getAiType());
response.setTargetNum(entity.getTargetNum());
response.setStatus(entity.getStatus());
response.setErrorMessage(entity.getErrorMessage());
response.setCreatedTime(entity.getCreatedTime());
response.setFinishedTime(entity.getFinishedTime());
response.setResult(result);
return response;
}
}
@@ -0,0 +1,35 @@
package com.guo.learningprogresstracker.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
/**
* DeepSeek 账户余额(契约 2.5,{@code GET /ai/usage/balance})。
*
* <p>由 lpt-be 代理 lpt-ai 的 {@code GET /admin/usage/balance};上游未配置或调用失败时只有
* {@code configured=false} 一个字段,因此这里用 {@code NON_NULL} 让其余字段直接不出现,
* 与契约给的响应体形状一致。</p>
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AiUsageBalance {
/** 上游是否可用:false 表示 lpt-ai 未配置 API Key 或本次查询失败 */
private boolean configured;
private String currency;
private String totalBalance;
private String grantedBalance;
private String toppedUpBalance;
/** 上游取数时间(ISO 8601 UTC) */
private String fetchedAt;
/** 上游不可用时的唯一响应:{@code {"configured": false}} */
public static AiUsageBalance notConfigured() {
return new AiUsageBalance();
}
}
@@ -0,0 +1,41 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* 用量按任务类型 / 模型 / 用户分组的一项(契约 2.4、v2 第 4.2 节,{@code GET /ai/usage/breakdown})。
*/
@Data
public class AiUsageBreakdownItem {
/**
* 分组键:{@code groupBy=taskType} 时是任务类型,{@code groupBy=model} 时是模型名,
* {@code groupBy=user} 时是用户 id(未归属的记录为 null)。
*/
private String key;
/**
* 展示名:{@code groupBy=user} 时是登录名(未归属为「未归属」,查不到登录名时回退为 {@code key}),
* 其它分组维度下等于 {@code key}——前端统一渲染 {@code label} 即可,不必按维度分支。
*/
private String label;
private Long calls;
private Long successCalls;
private Long failedCalls;
private Long promptTokens;
private Long completionTokens;
private Long cacheHitTokens;
private BigDecimal costUsd;
/** 平均调用耗时(毫秒);该分组无调用时为 null */
private Long avgDurationMs;
}
@@ -0,0 +1,32 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* 用量按任务类型 / 模型分组的聚合结果(Mapper 层直接映射,契约 2.4)。
*/
@Data
public class AiUsageBreakdownRow {
/** 分组键:{@code groupBy=taskType} 时是任务类型,{@code groupBy=model} 时是模型名 */
private String groupKey;
private Long calls;
private Long successCalls;
private Long failedCalls;
private Long promptTokens;
private Long completionTokens;
private Long cacheHitTokens;
private BigDecimal costUsd;
/** SQL 的 AVG 结果,由 service 取整后返回 */
private Double avgDurationMs;
}
@@ -0,0 +1,18 @@
package com.guo.learningprogresstracker.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 用量上报结果(契约 1):本次请求实际落库与因幂等跳过的条数。
*/
@Data
@AllArgsConstructor
public class AiUsageIngestResult {
/** 本次新落库的条数 */
private int accepted;
/** 因 {@code recordId} 已存在而跳过的条数 */
private int duplicated;
}
@@ -0,0 +1,18 @@
package com.guo.learningprogresstracker.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 当前用户能否查看「AI 用量统计」(契约 2.1,{@code GET /ai/usage/permission})。
*
* <p>非白名单也返回 HTTP 200 + {@code allowed=false},前端据此静默隐藏入口,
* 不需要为一个「看不见的按钮」处理报错。</p>
*/
@Data
@AllArgsConstructor
public class AiUsagePermission {
/** 用户名是否命中 {@code lpt.ai-usage.admin-usernames} */
private boolean allowed;
}
@@ -0,0 +1,27 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* 用量趋势的一个分桶(契约 2.3,{@code GET /ai/usage/series})。
*/
@Data
public class AiUsageSeriesPoint {
/** day:{@code yyyy-MM-dd};hour:{@code yyyy-MM-dd HH:00} */
private String bucket;
private Long calls;
private Long successCalls;
private Long failedCalls;
private Long promptTokens;
private Long completionTokens;
private BigDecimal costUsd;
}
@@ -0,0 +1,30 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* 用量趋势的分桶聚合结果(Mapper 层直接映射,契约 2.3)。
*
* <p>{@code bucket} 是计算列(按天/按小时格式化后的字符串),必须由显式
* {@code <resultMap>} 映射。</p>
*/
@Data
public class AiUsageSeriesRow {
/** day:{@code yyyy-MM-dd};hour:{@code yyyy-MM-dd HH:00} */
private String bucket;
private Long calls;
private Long successCalls;
private Long failedCalls;
private Long promptTokens;
private Long completionTokens;
private BigDecimal costUsd;
}
@@ -0,0 +1,47 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* AI 用量汇总(契约 2.2,{@code GET /ai/usage/summary})。
*
* <p>只统计真正消耗 LLM 的调用({@code is_llm_call = 1})。</p>
*/
@Data
public class AiUsageSummary {
private Long totalCalls;
private Long successCalls;
private Long failedCalls;
private Long promptTokens;
private Long completionTokens;
private Long totalTokens;
private Long cacheHitTokens;
private Long cacheMissTokens;
/** 缓存命中率 = 命中 /(命中 + 未命中);分母为 0 时为 null(不是 0,避免被读成「命中率为零」) */
private Double cacheHitRate;
private BigDecimal costUsd;
/** 按 {@code lpt.ai-usage.usd-to-cny} 换算的展示金额 */
private BigDecimal costCny;
/** 平均调用耗时(毫秒);无调用时为 null */
private Long avgDurationMs;
/** P95 调用耗时(毫秒,最近秩法);无调用时为 null */
private Long p95DurationMs;
/** 上游没上报 token 的调用数({@code prompt_tokens IS NULL}),面板据此显示「未上报」 */
private Long unreportedUsageCalls;
}
@@ -0,0 +1,39 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* 用量汇总的聚合结果(Mapper 层直接映射,契约 2.2)。
*
* <p>列名与属性不一致(别名、计算列),因此由 {@code AiUsageRecordMapper.xml} 的显式
* {@code <resultMap>} 承载映射,不依赖下划线转驼峰。</p>
*/
@Data
public class AiUsageSummaryRow {
private Long totalCalls;
private Long successCalls;
private Long failedCalls;
private Long promptTokens;
private Long completionTokens;
private Long totalTokens;
private Long cacheHitTokens;
private Long cacheMissTokens;
/** 未上报用量的调用数({@code prompt_tokens IS NULL}) */
private Long unreportedUsageCalls;
private BigDecimal costUsd;
/** SQL 的 AVG 结果,由 service 取整后返回 */
private Double avgDurationMs;
}
@@ -0,0 +1,29 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 一次导出的完整文档(导出-01)。Markdown 与 JSON 都由它渲染,保证两种格式内容一致。
*/
@Data
public class ExportDocument {
private LocalDateTime generatedTime;
/** TASK / RANGE / ALL */
private String scopeType;
/** 面向读者的范围描述 */
private String scopeLabel;
private LocalDate startDate;
private LocalDate endDate;
private List<ExportTaskSection> tasks = new ArrayList<>();
}
@@ -0,0 +1,22 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 导出的一条内容(学习报告或知识碎片,导出-01)。
*/
@Data
public class ExportEntry {
private Integer id;
/** 记录上下文:产生这条内容的学习会话编号 */
private String sessionNum;
private LocalDateTime createdTime;
/** 报告或碎片的原文 */
private String content;
}
@@ -0,0 +1,25 @@
package com.guo.learningprogresstracker.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 导出结果(导出-01)。
* <p>内容随统一响应体返回,由前端落成文件下载;这样既保持 {@code CommonResult} 的统一包装,
* 也不需要在服务端拼 Content-Disposition。</p>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExportResult {
/** 建议的文件名,含扩展名 */
private String fileName;
/** text/markdown; charset=UTF-8 或 application/json; charset=UTF-8 */
private String contentType;
/** 可独立阅读的导出正文 */
private String content;
}
@@ -0,0 +1,24 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 导出文档中的一个学习任务段落(导出-01)。
*/
@Data
public class ExportTaskSection {
private String taskNum;
private String taskName;
/** 任务维度统计:学习时长、复习耗时、报告/碎片数量等 */
private ReviewTaskStats stats;
private List<ExportEntry> reports = new ArrayList<>();
private List<ExportEntry> fragments = new ArrayList<>();
}
@@ -0,0 +1,19 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 一个碎片命中的标签数(闭环-04 标签导图取材)。
*
* <p>由 Mapper 层的分组查询直接映射:并集取「命中任意一个」的行,交集取「命中数 == 范围标签数」的行。
* 命中数按归一化标签名去重,所以重复打标不会让交集判定失真。</p>
*/
@Data
public class FragmentTagMatch {
/** 碎片 id(标记的 object_num) */
private String objectNum;
/** 命中的标签数(按归一化标签名去重) */
private Integer matchedTagCount;
}
@@ -0,0 +1,26 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 主键区间的聚合结果(复习-03)。
* <p>随机取样需要知道 id 的跨度,才能用「随机起点 + 顺序取窗口」替代 {@code ORDER BY RAND()}。
* 单列聚合可用 {@code selectObjs},这里需要 MIN 与 MAX 两列,因此用显式结果类 + 自定义 SQL。</p>
*/
@Data
public class IdRange {
private Integer minId;
private Integer maxId;
/** 区间内是否存在记录 */
public boolean isEmpty() {
return minId == null || maxId == null;
}
/** 区间宽度(含两端);空区间返回 0 */
public long span() {
return isEmpty() ? 0L : (long) maxId - minId + 1L;
}
}
@@ -0,0 +1,20 @@
package com.guo.learningprogresstracker.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 登录结果。
*
* <p>除 token 外额外下发 {@code aiAdmin}:前端据此决定是否显示「AI 用量统计」入口
* (契约 5,白名单口径在服务端,前端不自己判断)。</p>
*/
@Data
@AllArgsConstructor
public class LoginResult {
private String token;
/** 该用户是否在 {@code lpt.ai-usage.admin-usernames} 白名单里 */
private boolean aiAdmin;
}
@@ -0,0 +1,18 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 用户标签的使用情况(标记-01 的标签管理入口)。
*/
@Data
public class MarkerUsage {
private String markerName;
/** 该标签一共被打了多少次 */
private Long markerCount;
/** 该标签覆盖了多少个对象 */
private Long objectCount;
}
@@ -0,0 +1,10 @@
package com.guo.learningprogresstracker.dto;
/**
* 传给 lpt-ai 的一条碎片素材及其报告关联(报告-02)。
*
* <p>碎片正文之外带一个可空的 {@code reportRef}:指向同源的报告上下文。
* LLM 据此知道哪些碎片来自带报告的那次会话,从而只从中提取与这些碎片相关的内容。</p>
*/
public record MindMapFragmentPayload(String content, String reportRef) {
}
@@ -0,0 +1,36 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* 导图生成的报告参考上下文(报告-02)。
*
* <p>一次总结可能把若干碎片拼接出新的定义与观点,这些内容只存在于报告里、不在碎片里。
* 生成导图时,把碎片所在会话的报告一并带上作为 LLM 的参考,让它自行判断
* 「报告是否实质讨论了这些碎片的同一主题」:只有强相关才提取其内容,
* 只是简单提及或没提及则完全不用。</p>
*
* <p>{@code ref} 是报告所属会话编号,与碎片记录上下文的 {@code contextNum} 对应,
* 用于告诉 LLM 哪份报告与哪批碎片同源;{@code taskName} 帮助它判断领域是否一致。</p>
*/
public record MindMapReportContext(
@Schema(description = "报告所属会话编号,用于与碎片记录上下文关联")
String ref,
@Schema(description = "产生该报告的会话所属任务名(仅作判断领域的参考,报告可能来自旁支任务)")
String taskName,
@Schema(description = "会话摘要:这次实际学了什么")
String sessionSummary,
@Schema(description = "预期达成判断:对照学习预期得出的结论")
String expectationVerdict,
@Schema(description = "自由总结:用户对本次学习的叙述")
String freeSummary) {
/** 三段是否都为空白:全空的报告没有参考价值,不进入导图上下文 */
public boolean isBlank() {
return isBlank(sessionSummary) && isBlank(expectationVerdict) && isBlank(freeSummary);
}
private static boolean isBlank(String text) {
return text == null || text.isBlank();
}
}
@@ -0,0 +1,30 @@
package com.guo.learningprogresstracker.dto;
/**
* 一次回忆对比的结果(AI-02)。
*
* <p>对比在 AI 任务执行器里完成,因此不再把「标准导图实体」直接返回给提交接口;
* 这个结果写进 AI 任务的 {@code result_payload},由前端在轮询到成功后再取详情。</p>
*
* @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<String, Object> toPayload() {
java.util.Map<String, Object> 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;
}
}
@@ -0,0 +1,30 @@
package com.guo.learningprogresstracker.dto;
/**
* 学习报告的三段文本(归属-01 / 报告-01)。
*
* <p>报告的第四部分「按归属分组的碎片」不在此列:它是查看时按当前内容归属实时聚合的视图,不落库。</p>
*
* @param sessionSummary 会话摘要:这次实际学了什么
* @param expectationVerdict 预期达成判断:对照学习预期得出的结论
* @param freeSummary 自由总结:用户对本次学习的叙述
*/
public record ReportSections(String sessionSummary, String expectationVerdict, String freeSummary) {
/** 三段是否都为空 */
public boolean isEmpty() {
return isBlank(sessionSummary) && isBlank(expectationVerdict) && isBlank(freeSummary);
}
private static boolean isBlank(String text) {
return text == null || text.isBlank();
}
/** 报告落库时的兜底:至少保留一段,避免出现完全空的报告 */
public ReportSections orFallbackTo(String fallback) {
if (!isEmpty()) {
return this;
}
return new ReportSections(null, null, fallback);
}
}
@@ -5,15 +5,61 @@ import lombok.Data;
import java.time.LocalDateTime;
/**
* 复习滚动 feed 条目;首页仅使用残片,任务详情仍可同时包含报告和残片
* 复习滚动 feed 条目 / 任务记录条目。
*
* <p>归属-01 之后这里同时承载两个维度,不要混用:</p>
* <ul>
* <li>{@code taskNum} / {@code taskName} 是<b>内容归属</b>:碎片取它自己的归属任务,
* 报告取产生它的会话所属任务(报告按会话生成)。</li>
* <li>{@code contextType} / {@code contextNum} 是<b>记录上下文</b>:这条内容产生于哪次学习会话
* 或复习行为,用于界面按来源分组。</li>
* </ul>
*/
@Data
public class ReviewFeedItem {
private Integer id;
private String sessionNum;
/** REPORT | FRAGMENT */
private String sourceType;
/** 内容归属的任务编号;碎片待归类时为 null */
private String taskNum;
private String taskName;
private String sourceType; // REPORT | FRAGMENT
/**
* 内容摘要(复习-05):Feed 只回摘要,全文由详情接口按需拉取。
* <p>列表只用来触发回忆,全文既拖慢滚动也会让用户跳过「先尝试回忆」这一步。</p>
*/
private String content;
/** 原文总长度(字符数),供界面标注「全文 N 字」 */
private int contentLength;
/** 是否为截断后的摘要 */
private boolean contentTruncated;
private LocalDateTime createdTime;
/** 仅碎片有意义:内容归属为空,等待归类 */
private boolean pendingOwnership;
/** 记录上下文类型:SESSION | REVIEW */
private String contextType;
/** 记录上下文编号:学习会话编号或复习行为编号 */
private String contextNum;
/**
* 反馈与接触时间只参与排序计算,<b>不用于列表展示</b>:
* 复习反馈刻意不产生状态展示,否则会把复习拖回清单模式(复习-02)。
*/
@com.fasterxml.jackson.annotation.JsonIgnore
private Boolean mastered;
@com.fasterxml.jackson.annotation.JsonIgnore
private Boolean revisit;
@com.fasterxml.jackson.annotation.JsonIgnore
private LocalDateTime lastReviewedTime;
}
@@ -0,0 +1,21 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 复习排序偏好(复习-01):对外暴露档位与可选项,避免前端硬编码文案。
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ReviewSortPreference {
@Schema(description = "当前档位:TIME_FIRST / BALANCED / MASTERY_FIRST")
private String preset;
@Schema(description = "档位的中文说明")
private String description;
}
@@ -0,0 +1,23 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* 复习总览的全局汇总。
*
* <p>刻意单独出接口:任务列表已分页,客户端只能看到当前页,
* 再把每页的报告数/碎片数相加会得到一个「看起来是总数、其实是本页合计」的错数字。</p>
*
* <p>口径与 {@code /review/tasks} 的列表完全一致(列表逐页相加 == 这里的汇总):
* 报告按「报告 → 会话 → 任务」归属,碎片按内容归属({@code owner_task_num})统计。
* 因此待归类碎片不计入 {@code fragmentTotal}(由总览的「待归类内容」独立区块展示),
* 任务删除后残留的报告也不计入。</p>
*/
public record ReviewSummary(
@Schema(description = "任务总数")
long taskTotal,
@Schema(description = "学习报告总数")
long reportTotal,
@Schema(description = "学习碎片总数")
long fragmentTotal) {
}
@@ -17,4 +17,6 @@ public class ReviewTaskStats {
private double weekEffectiveTime;
private double avgEffectiveTime;
private double avgEffectivenessRatio;
/** 该任务累计复习耗时(秒):来自回忆对比等复习行为,与学习时长独立统计 */
private long reviewDurationSeconds;
}
@@ -0,0 +1,15 @@
package com.guo.learningprogresstracker.dto;
import java.time.LocalDateTime;
/**
* 一次复习行为的计时信息(复习-07)。
* <p>由前端上报:复习行为开始时刻、最近一次交互时刻、以及按 5 分钟空闲截断后的净耗时。
* 三个字段都可空;服务端会用 {@code utils.ReviewDurationTool} 统一结算并落库。</p>
*
* @param startedAt 行为开始时刻
* @param lastInteractionAt 最近一次交互时刻
* @param durationSeconds 前端结算出的净耗时(秒)
*/
public record ReviewTiming(LocalDateTime startedAt, LocalDateTime lastInteractionAt, Integer durationSeconds) {
}
@@ -0,0 +1,81 @@
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;
/**
* 学习报告详情(归属-01:结构化报告)。
*
* <p>报告由四部分组成,其中前三部分是落库的文本,第四部分是<b>实时聚合</b>出来的视图:</p>
* <ol>
* <li>会话摘要</li>
* <li>预期达成判断</li>
* <li>按内容归属分组的碎片 —— 查看时按碎片的<b>当前</b>归属聚合,不落库。
* 这样它与标准导图的取材口径始终一致,不会出现「报告说属于甲、导图放在乙」。</li>
* <li>自由总结</li>
* </ol>
*/
@Data
public class StudyReportDetail {
private Integer id;
/** 产生这份报告的会话 */
private String sessionNum;
/** 产生这份报告的会话所属任务(报告按会话生成,这是「这次学习属于哪个任务」) */
private String sessionTaskNum;
private String sessionTaskName;
/** 会话对应的学习预期 */
private String sessionExpectation;
@Schema(description = "会话摘要:这次实际学了什么")
private String sessionSummary;
@Schema(description = "预期达成判断:对照学习预期得出的结论")
private String expectationVerdict;
@Schema(description = "自由总结:用户对本次学习的叙述")
private String freeSummary;
private java.time.LocalDateTime createdTime;
@Schema(description = "按当前内容归属分组的碎片")
private List<FragmentGroup> fragmentGroups = new ArrayList<>();
/**
* 一条碎片按内容归属分组的结果。
*/
@Data
public static class FragmentGroup {
/** 归属任务编号;null 表示待归类 */
private String taskNum;
private String taskName;
/** 是否「旁支」:归属不等于本次报告所属会话的任务 */
private boolean branch;
private List<StudyReportFragmentsEntity> fragments = new ArrayList<>();
}
public static StudyReportDetail of(StudyReportsEntity report) {
StudyReportDetail detail = new StudyReportDetail();
detail.setId(report.getId());
detail.setSessionNum(report.getSessionNum());
detail.setSessionSummary(report.getSessionSummary());
detail.setExpectationVerdict(report.getExpectationVerdict());
detail.setFreeSummary(report.getFreeSummary());
detail.setCreatedTime(report.getCreatedTime());
detail.setSessionExpectation(report.getSessionExpectation());
return detail;
}
}
@@ -50,4 +50,9 @@ public class StudySessionsDto {
* 学习会话的状态(进行中、暂停、已结束)
*/
private String sessionState;
/**
* 是否由服务端自动收敛(疑似忘记结束,会话-04)
*/
private Boolean autoConverged;
}
@@ -0,0 +1,46 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 已有标签导图的摘要(闭环-04):用于「已生成的标签导图」列表。
*
* <p>列表是「按标签复习」的主入口:用户先看到已经生成过导图的标签集合,
* 直接进入复习或把新碎片补充进去,不必先选标签再判断这个范围有没有导图。
* 导图生成后标签集合一般不再变化,因此列表只读地还原 {@code tags + mode},
* 前端可直接用它们发起复查或增量生成(与 {@code scopeKey} 一一对应)。</p>
*/
@Data
public class TagMindMapSummary {
@Schema(description = "标签导图 ID")
private Integer id;
@Schema(description = "范围键:标签集合与取数模式的稳定哈希,同时作为 AI 任务的 targetNum")
private String scopeKey;
@Schema(description = "范围的标签集合(展示用,按归一化名排序)")
private List<String> tags;
@Schema(description = "取数模式:UNION=并集 / INTERSECT=交集")
private String mode;
@Schema(description = "导图标题")
private String title;
@Schema(description = "生成来源:BUILTIN/AI/USER/USER_MERGE")
private String generator;
@Schema(description = "取材的碎片数量")
private Integer sourceFragmentCount;
@Schema(description = "素材变化后置 true:有新碎片待整理,重建由用户手动触发")
private Boolean needsUpdate;
@Schema(description = "导图生成时间")
private LocalDateTime generatedTime;
}
@@ -0,0 +1,34 @@
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;
/**
* 一个标签复习范围的当前状态(闭环-04)。
*
* <p>范围键与标签集合总是返回(即使还没有导图),让前端能用同一组参数发起生成任务与回忆对比;
* {@code map} 为空表示该范围还没生成过导图——读取路径不触发生成,生成走
* {@code POST /ai/tasks}(type=TAG_MIND_MAP)异步完成。</p>
*/
@Data
public class TagMindMapView {
@Schema(description = "范围键:标签集合与取数模式的稳定哈希,同时作为 AI 任务的 targetNum")
private String scopeKey;
@Schema(description = "范围的标签集合(展示用,按归一化名排序)")
private List<String> tags;
@Schema(description = "取数模式:UNION=并集 / INTERSECT=交集")
private String mode;
@Schema(description = "该范围已有的标签导图;没有时为 null")
private ReviewTagMindMapEntity map;
@Schema(description = "该范围最近一次回忆对比记录;没复习过时为 null")
private ReviewRecallRecordEntity latestRecallRecord;
}
@@ -0,0 +1,19 @@
package com.guo.learningprogresstracker.dto;
import com.guo.learningprogresstracker.enums.TagCombineModeEnum;
import java.util.List;
/**
* 解析后的复习范围:标签集合 + 取数模式 + 规范键(闭环-04)。
*
* <p>{@code tags} 是展示用标签集合(按归一化名排序、保留输入原样),{@code normalizedTags} 是规范化标签集合,
* {@code scopeKey} 是两者的稳定哈希——集合相同且模式相同即同一张标签导图。</p>
*/
public record TagScope(String scopeKey, List<String> tags, List<String> normalizedTags, TagCombineModeEnum mode) {
/** 范围的展示名:标签以「、」连接,也是标签导图的根节点标题来源 */
public String displayName() {
return String.join("、", tags);
}
}
@@ -0,0 +1,16 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 任务维度的内容条数聚合结果(数据-02):学习报告或知识碎片的条数。
* <p>计数在 SQL 侧按内容归属(学习会话 → 任务)分组完成。</p>
*/
@Data
public class TaskContentCount {
private String taskNum;
/** 该任务下的报告数或碎片数 */
private Long contentCount;
}
@@ -0,0 +1,32 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 删除学习任务的影响范围(归属-01)。
*
* <p>删除确认弹窗必须分别列出「即将删除」与「即将保留」,避免用户以为删干净了:
* 知识碎片会保留下来并进入待归类。</p>
*/
@Data
public class TaskDeletionSummary {
@Schema(description = "将保留的知识碎片条数(内容归属置空,进入待归类)")
private int releasedFragments;
@Schema(description = "将软删除的学习会话数")
private int deletedSessions;
@Schema(description = "将软删除的学习报告数")
private int deletedReports;
@Schema(description = "将软删除的标准思维导图数")
private int deletedMindMaps;
@Schema(description = "将软删除的回忆记录数")
private int deletedRecallRecords;
@Schema(description = "将软删除的应用场景数")
private int deletedApplications;
}
@@ -0,0 +1,19 @@
package com.guo.learningprogresstracker.dto;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* 任务的最小选项(任务编号 + 名称),供「归类到已有任务」这类下拉使用。
*
* <p>刻意不复用 {@code /review/tasks}:那条接口会做复习统计聚合(时长/报告数/碎片数),
* 且现在已按页返回;下拉需要的是全部任务的一个最小列表。也不复用分页的 {@code /tasks},
* 否则任务多起来下拉会悄悄只显示第一页。</p>
*
* <p>排序与任务列表一致(优先级倒序),保证下拉里的顺序稳定。</p>
*/
public record TaskOption(
@Schema(description = "任务编号")
String taskNum,
@Schema(description = "任务名称")
String taskName) {
}
@@ -0,0 +1,19 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 任务最近一次回忆对比的覆盖率(复习-04)。
*
* <p>原先按任务取「最近一条回忆记录」是把该任务的全部回忆记录(含体积较大的
* {@code compare_result} JSON)拉回内存再逐条取第一条。改为在 SQL 侧按任务分组取最新,
* 返回行数等于任务数,不随复习次数增长。</p>
*/
@Data
public class TaskRecallRatio {
private String taskNum;
/** 最近一次回忆对比的覆盖率(0-1);记录里为空时按 0 处理 */
private Double recallRatio;
}
@@ -0,0 +1,16 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 任务维度的复习耗时聚合结果(复习-07)。
* <p>由 Mapper 层的聚合查询直接映射,避免用 Map 承载查询结果。</p>
*/
@Data
public class TaskReviewDuration {
private String taskNum;
/** 该任务累计复习耗时(秒) */
private Long reviewDurationSeconds;
}
@@ -0,0 +1,28 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
/**
* 任务维度的学习会话统计聚合结果(数据-02)。
* <p>由 Mapper 层的 {@code SUM/COUNT + GROUP BY} 直接映射,避免把全部会话行拉回内存再聚合。</p>
*/
@Data
public class TaskSessionStats {
private String taskNum;
/** 该任务的学习会话次数 */
private Long sessionCount;
/** 累计有效学习时间(秒) */
private Double effectiveTime;
/** 有效时间比之和,用于计算平均值(避免在 Java 侧再存一份分母之外的中间量) */
private Double effectivenessRatioSum;
/** 今日有效学习时间(秒),时间窗在 SQL 侧判断 */
private Double todayEffectiveTime;
/** 本周有效学习时间(秒),时间窗在 SQL 侧判断 */
private Double weekEffectiveTime;
}
@@ -0,0 +1,43 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.util.Map;
/**
* 提交 AI 任务请求(AI-02)。
*/
@Data
public class AiTaskSubmitRequest {
@NotBlank(message = "请先指定要处理的类型")
private String type;
@NotBlank(message = "请先指定要处理的对象")
private String targetNum;
/** 类型相关的参数;无需参数时可为空 */
private Map<String, Object> params;
/** 阅读友好度:null 表示不关心 */
public String paramAsString(String key) {
Object value = params == null ? null : params.get(key);
return value == null ? null : String.valueOf(value);
}
public Integer paramAsInteger(String key) {
Object value = params == null ? null : params.get(key);
if (value instanceof Number number) {
return number.intValue();
}
if (value instanceof String text && !text.isBlank()) {
try {
return Integer.valueOf(text.trim());
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
}
@@ -0,0 +1,31 @@
package com.guo.learningprogresstracker.dto.request;
import lombok.Data;
/**
* 用量查询条件(契约 2.2 / 2.3 / 2.4):summary、series、breakdown 共用同一组筛选参数。
*/
@Data
public class AiUsageQuery {
/** 起始时刻(epoch millis);为空表示最近 30 天 */
private Long from;
/** 结束时刻(epoch millis);为空表示「到此刻为止」 */
private Long to;
/** 任务类型,精确匹配;为空表示不限 */
private String taskType;
/** 模型名,精确匹配;为空表示不限 */
private String model;
/** 归属用户 id,精确匹配;为空表示不限 */
private String userId;
/** series 的分桶粒度:day / hour */
private String bucket = "day";
/** breakdown 的分组维度:taskType / model / user */
private String groupBy = "taskType";
}
@@ -0,0 +1,87 @@
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;
/**
* 一条 AI 用量记录(契约 1)。
*
* <p>token 类字段一律包装类型:{@code null} 表示上游未上报,{@code 0} 表示上游明确上报为 0,
* 两者语义不同,不得用 0 顶替 null。</p>
*/
@Data
public class AiUsageRecordRequest {
/** 幂等键,lpt-ai 生成 */
@NotBlank(message = "recordId 不能为空")
private String recordId;
/** 调用发生时间,ISO 8601 UTC,如 {@code 2026-10-10T09:38:23.543Z} */
@NotBlank(message = "occurredAt 不能为空")
private String occurredAt;
@NotBlank(message = "taskType 不能为空")
private String taskType;
private String taskId;
/**
* 归属标记(契约 v2 第 2 节):lpt-be 提交任务时带的用户 id,lpt-ai 原样透传,落库到
* {@code ai_usage_records.user_id}。
*
* <p>刻意不用 {@code @NotBlank}:历史数据、lpt-ai 独立调用、以及调用方没带标记时都是空值,
* 空值只表示「未归属」,不是错误——用 {@code @NotBlank} 会把这类上报整批打成 400。</p>
*/
@Size(max = 64, message = "callerRef 不能超过 64 个字符")
private String callerRef;
/**
* 模型名。
*
* <p>用 {@code @NotNull} 而不是 {@code @NotBlank}:{@code isLlmCall=false} 的记录
* (如 {@code /fetch-title})本来就没调用模型,契约里它的 model 就是空串。
* 用 {@code @NotBlank} 会让这一条把整批上报打成 400,而上报方会把 400 当成可重试错误,
* outbox 被永久堵死。</p>
*/
@NotNull(message = "model 不能为空")
private String model;
@NotNull(message = "attempts 不能为空")
private Integer attempts;
@NotNull(message = "isLlmCall 不能为空")
private Boolean isLlmCall;
@NotBlank(message = "usageSource 不能为空")
private String usageSource;
private Integer promptTokens;
private Integer completionTokens;
private Integer totalTokens;
private Integer cacheHitTokens;
private Integer cacheMissTokens;
private Integer reasoningTokens;
private BigDecimal costUsd;
private String pricingVersion;
private Boolean peak;
@NotNull(message = "durationMs 不能为空")
private Integer durationMs;
@NotNull(message = "status 不能为空")
private Integer status;
private String errorCode;
}
@@ -0,0 +1,19 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.util.List;
/**
* lpt-ai 用量上报请求体(契约 1,{@code POST /internal/ai-usage/records})。
*/
@Data
public class AiUsageReportRequest {
/** 单次最多 200 条(见 {@code AiUsageInternalController.MAX_RECORDS_PER_REPORT}) */
@NotNull(message = "records 不能为空")
@Valid
private List<AiUsageRecordRequest> records;
}
@@ -9,9 +9,9 @@ import lombok.Data;
@Data
public class CreateFragmentsRequest {
/**
* 会话编号
* 记录上下文编号:产生这条碎片的学习会话编号(归属-01 起上下文由类型 + 编号共同描述)
*/
private String sessionNum;
private String contextNum;
/**
* 残片内容,学习内容的描述
@@ -1,13 +1,22 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* @author guo
* 结束学习会话时提交的学习报告(归属-01 起报告为结构化三段)。
*
* <p>三段都可为空,但至少要有一段;第四部分「按归属分组的碎片」是实时聚合的视图,不需要提交。</p>
*/
@Data
public class EndedStudySessionRequest {
@NotBlank(message = "请填写学习报告内容")
private String content;
@Schema(description = "会话摘要:这次实际学了什么")
private String sessionSummary;
@Schema(description = "预期达成判断:对照学习预期得出的结论")
private String expectationVerdict;
@Schema(description = "自由总结:用户对本次学习的叙述")
private String freeSummary;
}
@@ -1,8 +1,11 @@
package com.guo.learningprogresstracker.dto.request;
import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户回忆对比请求
*/
@@ -14,4 +17,15 @@ public class RecallCompareRequest {
/** 复习起点节点路径(以 / 分隔),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;
}
@@ -0,0 +1,20 @@
package com.guo.learningprogresstracker.dto.request;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 复习反馈动作(复习-02)。
*
* <p>两个动作都只调整内容的出现概率,不产生状态展示、不统计总数、不做待复习列表。
* 传 null 表示本次不改该动作。</p>
*/
@Data
public class ReviewFeedbackRequest {
@Schema(description = "标记/取消「已掌握」:降低出现概率但不归零")
private Boolean mastered;
@Schema(description = "标记/取消「稍后再看」:提高出现概率")
private Boolean revisit;
}
@@ -0,0 +1,22 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 标签复习范围(闭环-04):标签集合 + 取数模式。
*
* <p>用于纯范围寻址的读接口(读取该范围的导图、读取该范围的回忆记录)。
* 字段名与 {@code /ai/tasks} 的 params 保持一致,前端两处可以直接复用。</p>
*/
@Data
public class TagScopeRequest {
@NotEmpty(message = "请先选择标签")
private List<String> tags;
/** 取数模式:UNION=并集(默认)/ INTERSECT=交集 */
private String mode;
}
@@ -1,16 +1,20 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* @author guo
* 修改知识碎片:只允许改正文与内容归属,记录上下文不可变。
*/
@Data
public class UpdateFragmentsRequest {
/**
* 残片内容,学习内容的描述
* 残片内容(学习内容的描述);为空表示本次不改正文
*/
@NotBlank(message = "请填写学习内容")
private String content;
/**
* 内容归属的任务编号;不传表示本次不改归属。
* <p>若要清空归属(回到待归类),传空字符串。</p>
*/
private String ownerTaskNum;
}
@@ -0,0 +1,22 @@
package com.guo.learningprogresstracker.dto.request;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 修改学习报告的三段文本(归属-01 / 报告-01)。
*
* <p>不传或传 null 表示本次不改该段;传空字符串表示清空该段。</p>
*/
@Data
public class UpdateStudyReportRequest {
@Schema(description = "会话摘要:这次实际学了什么")
private String sessionSummary;
@Schema(description = "预期达成判断:对照学习预期得出的结论")
private String expectationVerdict;
@Schema(description = "自由总结:用户对本次学习的叙述")
private String freeSummary;
}
@@ -0,0 +1,26 @@
package com.guo.learningprogresstracker.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 用户编辑标签导图(大纲文本形式)请求(闭环-04)。
*
* <p>范围绕「标签集合 + 取数模式」寻址,因此请求里带的是范围本身而不是导图 id;
* 该范围还没有导图时,保存即为新建。</p>
*/
@Data
public class UpdateTagMindMapRequest {
@NotEmpty(message = "请先选择标签")
private List<String> tags;
/** 取数模式:UNION=并集(默认)/ INTERSECT=交集 */
private String mode;
@NotBlank(message = "请填写思维导图大纲")
private String outline;
}
@@ -54,4 +54,7 @@ public class StudySessionResponse {
@Schema(description = "系统提示")
private String systemMessage;
@Schema(description = "是否由服务端自动收敛(疑似忘记结束,会话-04)")
private Boolean autoConverged;
}
@@ -0,0 +1,79 @@
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 com.guo.learningprogresstracker.enums.AiTaskStatusEnum;
import com.guo.learningprogresstracker.utils.GenerateNumTool;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* AI 异步任务(AI-02):提交后立即返回任务标识,结果由执行器回写、按标识重复获取。
*/
@TableName(value = "ai_tasks")
@Data
public class AiTaskEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 对外任务标识 */
@TableField(value = "task_num")
private String taskNum;
/** 任务类型,取值见 {@code AiTaskTypeEnum} */
@TableField(value = "ai_type")
private String aiType;
/** 目标编号:学习任务编号或学习会话编号 */
@TableField(value = "target_num")
private String targetNum;
/** 状态,取值见 {@code AiTaskStatusEnum} */
@TableField(value = "status")
private String status;
/** 提交时的请求参数 JSON */
@TableField(value = "request_payload")
private String requestPayload;
/** 成功结果 JSON */
@TableField(value = "result_payload")
private String resultPayload;
/** 失败原因(用户可见文案) */
@TableField(value = "error_message")
private String errorMessage;
@TableField(value = "started_time")
private LocalDateTime startedTime;
@TableField(value = "finished_time")
private LocalDateTime finishedTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
public static AiTaskEntity initNewTask(String aiType, String targetNum, String requestPayload) {
AiTaskEntity task = new AiTaskEntity();
task.setTaskNum(GenerateNumTool.generateNum("AITASK"));
task.setAiType(aiType);
task.setTargetNum(targetNum);
task.setStatus(AiTaskStatusEnum.PENDING.name());
task.setRequestPayload(requestPayload);
return task;
}
public boolean isActive() {
return AiTaskStatusEnum.ACTIVE.contains(AiTaskStatusEnum.valueOf(status));
}
public boolean isFinished() {
return AiTaskStatusEnum.SUCCEEDED.name().equals(status)
|| AiTaskStatusEnum.FAILED.name().equals(status);
}
}
@@ -0,0 +1,120 @@
package com.guo.learningprogresstracker.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* AI 用量记录:lpt-ai 每完成一次 AI 任务后上报一条,供「AI 用量统计」面板聚合。
*
* <p><b>系统级表</b>:已加入 {@code MybatisPlusConfig.EXCLUDE_TABLES},不做按 {@code created_by}
* 的租户过滤——用量是运维口径,面板展示的是全部调用,而不是当前用户自己触发的那几次。</p>
*
* <p>token 类字段一律用包装类型:{@code null} 表示上游没上报,{@code 0} 表示上游明确上报为 0,
* 两者语义不同,不得用 0 顶替 null(面板要能显示「未上报」的调用数)。</p>
*/
@TableName(value = "ai_usage_records")
@Data
public class AiUsageRecordEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 幂等键:lpt-ai 生成的 UUID,重复上报直接跳过 */
@TableField(value = "record_id")
private String recordId;
/** 调用发生时间(UTC) */
@TableField(value = "occurred_at")
private LocalDateTime occurredAt;
/** 任务类型:aggregate-report/generate-mind-map/compare-recall/guidance/fetch-title */
@TableField(value = "task_type")
private String taskType;
/** lpt-ai 任务 id */
@TableField(value = "task_id")
private String taskId;
/**
* 归属用户:取自上报的 {@code callerRef};null=未归属(历史数据/独立调用/调用方没传)。
*
* <p>只用于分组与筛选,<strong>不是</strong>租户列:本表已在 {@code MybatisPlusConfig.EXCLUDE_TABLES}
* 中,绝不能按它过滤,否则面板只能看到当前管理员自己触发的调用。</p>
*/
@TableField(value = "user_id")
private String userId;
/** 模型名,如 deepseek-flash */
@TableField(value = "model")
private String model;
/** 本次任务实际发起的 LLM 调用次数(含失败重试) */
@TableField(value = "attempts")
private Integer attempts;
/** 是否消耗 LLM;false 表示没调用(如 /fetch-title) */
@TableField(value = "is_llm_call")
private Boolean isLlmCall;
/** 用量来源:upstream=上游返回 / estimated=估算 / missing=上游未给 */
@TableField(value = "usage_source")
private String usageSource;
/** 输入 token;null=未上报 */
@TableField(value = "prompt_tokens")
private Integer promptTokens;
/** 输出 token;null=未上报 */
@TableField(value = "completion_tokens")
private Integer completionTokens;
/** 总 token;null=未上报 */
@TableField(value = "total_tokens")
private Integer totalTokens;
/** 命中缓存的输入 token;null=未上报 */
@TableField(value = "cache_hit_tokens")
private Integer cacheHitTokens;
/** 未命中缓存的输入 token;null=未上报 */
@TableField(value = "cache_miss_tokens")
private Integer cacheMissTokens;
/** 推理 token;null=未上报 */
@TableField(value = "reasoning_tokens")
private Integer reasoningTokens;
/** 本次费用(USD),上报时算好并冻结 */
@TableField(value = "cost_usd")
private BigDecimal costUsd;
/** 计价表版本 */
@TableField(value = "pricing_version")
private String pricingVersion;
/** 是否按峰时价计费 */
@TableField(value = "peak")
private Boolean peak;
/** 本次调用耗时(毫秒) */
@TableField(value = "duration_ms")
private Integer durationMs;
/** 调用结果:200 成功,其余失败 */
@TableField(value = "status")
private Integer status;
/** 失败分类,如 timeout/rate_limited/upstream_error */
@TableField(value = "error_code")
private String errorCode;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
@@ -0,0 +1,50 @@
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;
/**
* 统一标记(标记-01):附加在对象上的一段轻量元信息。
*
* <p>标记不是状态,也不参与聚合口径:会话状态、报告可否修订、导图是否待更新这类流程判断
* 留在各自主体上;内容归属是唯一的结构归属,标记不能用来表达第二归属。</p>
*/
@TableName(value = "markers")
@Data
public class MarkerEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** FRAGMENT | TASK,取值见 {@code MarkerObjectTypeEnum} */
@TableField(value = "object_type")
private String objectType;
/** 对象标识:碎片 id 或 任务编号 */
@TableField(value = "object_num")
private String objectNum;
/** SYSTEM | USER,取值见 {@code MarkerKindEnum} */
@TableField(value = "kind")
private String kind;
/** 标记名:系统标记来自固定词表;用户标签自由输入 */
@TableField(value = "marker_name")
private String markerName;
/** 标记值:系统标记成对使用;用户标签留空(标签名本身就是全部信息) */
@TableField(value = "marker_value")
private String markerValue;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
public boolean isSystemMarker() {
return com.guo.learningprogresstracker.enums.MarkerKindEnum.SYSTEM.name().equals(kind);
}
}
@@ -0,0 +1,69 @@
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 com.guo.learningprogresstracker.utils.GenerateNumTool;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 学习引导会话(复习-06):一次复习行为。
*
* <p>它有两重身份:产出的知识碎片以它作为**记录上下文**(复习行为),
* 复习耗时也记在它身上(与回忆对比同一口径,见复习-07)。</p>
*/
@TableName(value = "review_guidance_conversations")
@Data
public class ReviewGuidanceConversationEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 对外标识,也是产出碎片的记录上下文编号 */
@TableField(value = "guidance_num")
private String guidanceNum;
/** 被引导概念所属的学习任务,也是产出碎片的默认内容归属 */
@TableField(value = "task_num")
private String taskNum;
/** 被引导的概念(来自 Feed 卡片或导图节点) */
@TableField(value = "concept")
private String concept;
/** 对话轮次 JSON:[{role,content}] */
@TableField(value = "turns_payload")
private String turnsPayload;
/** 本次复习耗时(秒),已按 5 分钟空闲截断 */
@TableField(value = "review_duration_seconds")
private Integer reviewDurationSeconds;
@TableField(value = "finished")
private Boolean finished;
@TableField(value = "started_time")
private LocalDateTime startedTime;
@TableField(value = "finished_time")
private LocalDateTime finishedTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
public static ReviewGuidanceConversationEntity initNewConversation(String taskNum, String concept) {
ReviewGuidanceConversationEntity conversation = new ReviewGuidanceConversationEntity();
conversation.setGuidanceNum(GenerateNumTool.generateNum("GUIDANCE"));
conversation.setTaskNum(taskNum);
conversation.setConcept(concept);
conversation.setTurnsPayload("[]");
conversation.setReviewDurationSeconds(0);
conversation.setFinished(false);
conversation.setStartedTime(LocalDateTime.now());
return conversation;
}
}
@@ -18,14 +18,32 @@ 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 表示任务维度复习
* 复习起点节点路径(以 / 分隔),null 表示整棵树
*/
@TableField(value = "focus_path")
private String focusPath;
@@ -57,6 +75,12 @@ public class ReviewRecallRecordEntity extends BaseEntity implements Serializable
@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;
}
@@ -58,6 +58,15 @@ public class ReviewStandardMindMapEntity extends BaseEntity implements Serializa
@TableField(value = "generated_time")
private LocalDateTime generatedTime;
/**
* 内容归属发生变化后置为 true,表示这张导图需要重建;重建由用户手动触发(归属-01)
*/
@TableField(value = "needs_update")
private Boolean needsUpdate;
@TableField(value = "needs_update_time")
private LocalDateTime needsUpdateTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
@@ -0,0 +1,74 @@
package com.guo.learningprogresstracker.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 标签思维导图(闭环-04):以一个「标签集合 + 取数模式」为范围的导图,与任务导图并存。
*
* <p>范围键 {@code scopeKey} 是标签集合(归一化、排序后拼接)与取数模式的稳定哈希:
* 集合相同且模式相同即同一张导图,因此同一用户下范围键唯一。素材是带这些标签的知识碎片,
* 与任务导图共用「碎片 → 缩进大纲」的生成链路与内置规则降级路径。</p>
*/
@TableName(value = "review_tag_mind_maps")
@Data
public class ReviewTagMindMapEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 范围键,见 {@code utils.TagScopeTool#scopeKey} */
@TableField(value = "scope_key")
private String scopeKey;
/** 取数模式:UNION=并集 / INTERSECT=交集,取值见 {@code TagCombineModeEnum} */
@TableField(value = "combine_mode")
private String combineMode;
/** 范围的标签集合(JSON 数组,展示保留输入原样,按归一化名排序) */
@TableField(value = "tag_names")
private String tagNames;
@TableField(value = "title")
private String title;
/** 统一树结构 JSON(根节点:{title, notes, children}) */
@TableField(value = "content")
private String content;
/** 缩进大纲文本,供前端展示与用户编辑 */
@TableField(value = "outline")
private String outline;
@TableField(value = "summary")
private String summary;
/** 生成来源:BUILTIN/AI/USER/USER_MERGE */
@TableField(value = "generator")
private String generator;
@TableField(value = "generator_version")
private String generatorVersion;
@TableField(value = "source_fragment_count")
private Integer sourceFragmentCount;
@TableField(value = "generated_time")
private LocalDateTime generatedTime;
/** 该范围下的素材(碎片标签)发生变化后置为 true,表示这张导图需要重建;重建由用户手动触发 */
@TableField(value = "needs_update")
private Boolean needsUpdate;
@TableField(value = "needs_update_time")
private LocalDateTime needsUpdateTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
@@ -4,36 +4,79 @@ 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 java.io.Serializable;
import com.guo.learningprogresstracker.enums.FragmentContextTypeEnum;
import lombok.Data;
import java.io.Serializable;
/**
* 记录学习过程中的学习内容报告残片
* @TableName study_report_fragments
* 记录学习过程中的学习内容报告残片(知识碎片)。
*
* <p>归属-01 后本实体承载两个互相独立的维度:</p>
* <ul>
* <li><b>记录上下文</b>({@code contextType} + {@code contextNum}):产生于哪次学习会话或复习行为,
* 由系统确定、不可变、不可为空,用于时间统计与报告归属。</li>
* <li><b>内容归属</b>({@code ownerTaskNum}):内容在知识结构上属于哪个任务,由用户确定、可变、可为空
* (为空即「待归类」),用于导图取材与按任务聚合。</li>
* </ul>
*/
@TableName(value ="study_report_fragments")
@TableName(value = "study_report_fragments")
@Data
public class StudyReportFragmentsEntity extends BaseEntity implements Serializable {
/**
*
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
*
* 记录上下文编号:学习会话编号或复习行为编号
*/
@TableField(value = "session_num")
private String sessionNum;
@TableField(value = "context_num")
private String contextNum;
/**
* 学习内容的描述
* 记录上下文类型:SESSION / REVIEW
*/
@TableField(value = "context_type")
private String contextType;
/**
* 内容归属的学习任务编号;null 表示待归类
*/
@TableField(value = "owner_task_num")
private String ownerTaskNum;
/**
* 用户标记「已掌握」:降低出现概率但不归零(复习-02)。
* <p>刻意不进标记表——文档明确「标记不是状态」,流程性判断留在主体上。</p>
*/
@TableField(value = "mastered")
private Boolean mastered;
/**
* 用户标记「稍后再看」:提高出现概率(复习-02)
*/
@TableField(value = "revisit")
private Boolean revisit;
/**
* 最近一次接触时间(展开查看 / 进入回忆对比时刷新),智能排序的第三个信号(复习-02)
*/
@TableField(value = "last_reviewed_time")
private java.time.LocalDateTime lastReviewedTime;
@TableField(value = "content")
private String content;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
/** 是否来自学习会话(记录上下文为 SESSION) */
public boolean fromSession() {
return FragmentContextTypeEnum.SESSION.name().equals(contextType);
}
/** 是否待归类(没有内容归属) */
public boolean isPendingOwnership() {
return ownerTaskNum == null || ownerTaskNum.isBlank();
}
}
@@ -4,37 +4,47 @@ 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 java.io.Serializable;
import lombok.Data;
import java.io.Serializable;
/**
* 存储每次学习结束时的完整学习报告
* @TableName study_reports
* 存储每次学习结束时的完整学习报告。
*
* <p>报告按会话生成,是「这次学习产出了什么」的事实记录,三部分为文本:
* 会话摘要、预期达成判断、自由总结。报告的第四部分「按归属分组的碎片」不落库,
* 查看时按碎片的当前内容归属实时聚合(见 lpt-docs「内容归属」实现级结论 4)。</p>
*/
@TableName(value ="study_reports")
@TableName(value = "study_reports")
@Data
public class StudyReportsEntity extends BaseEntity implements Serializable {
/**
*
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 会话编码
*/
@TableField(value = "session_num")
private String sessionNum;
/**
* 完整的学习报告内容
* 会话摘要:这次实际学了什么
*/
@TableField(value = "content")
private String content;
@TableField(value = "session_summary")
private String sessionSummary;
/**
* 对应学习会话的预期目标(非数据库字段,查询时填充)
* 预期达成判断:对照学习预期得出的结论
*/
@TableField(value = "expectation_verdict")
private String expectationVerdict;
/**
* 自由总结:用户对本次学习的叙述
*/
@TableField(value = "free_summary")
private String freeSummary;
/**
* 会话对应的学习预期,仅用于返回,不落库
*/
@TableField(exist = false)
private String sessionExpectation;
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
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;
@@ -15,8 +16,6 @@ import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;
import static com.guo.learningprogresstracker.service.impl.StudySessionsServiceImpl.WORK_DURATION;
/**
* 记录每次学习会话的具体数据
* @TableName study_sessions
@@ -77,6 +76,13 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
@TableField(value = "session_state")
private String sessionState;
/**
* 是否由服务端自动收敛(会话-04):为 true 表示这段学习疑似忘记点暂停/结束,
* 由惰性收敛或定时扫描强制结算,前端据此给出提示。
*/
@TableField(value = "auto_converged")
private Boolean autoConverged;
/**
* 计时器指针位置,时间戳形式存储(毫秒)
@@ -88,28 +94,42 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 初始化新会话
* @return
* 初始化新会话(使用默认时间口径)
*/
public static StudySessionsEntity initNewSession(){
return initNewSession(StudyTimePolicy.DEFAULT);
}
/**
* 初始化新会话
*/
public static StudySessionsEntity initNewSession(StudyTimePolicy policy){
StudySessionsEntity studySessionsEntity = new StudySessionsEntity();
studySessionsEntity.setSessionNum(GenerateNumTool.generateNum("SESSION"));
studySessionsEntity.setStartTime(LocalDateTime.now());
studySessionsEntity.setLastStartTime(LocalDateTime.now());
studySessionsEntity.setPointerPosition(WORK_DURATION * 60 * 1000L);
studySessionsEntity.setPointerPosition(policy.workDurationMillis());
studySessionsEntity.setLastModifiedTime(LocalDateTime.now());
studySessionsEntity.setSessionState(StudySessionStateEnum.ONGOING.name());
studySessionsEntity.setAutoConverged(false);
return studySessionsEntity;
}
/**
* 继续会话(使用默认时间口径)
*/
public void continueStudySession() throws ServiceException {
continueStudySession(StudyTimePolicy.DEFAULT);
}
/**
* 继续会话
*/
public void continueStudySession() throws ServiceException {
public void continueStudySession(StudyTimePolicy policy) throws ServiceException {
if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())){
this.setSessionState(StudySessionStateEnum.ONGOING.name());
this.setLastStartTime(LocalDateTime.now());
this.calculatePointerPosition();
this.calculatePointerPosition(policy);
} else if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) {
log.info("进行中的学习会话({})被重新开始",this.getSessionNum());
} else{
@@ -118,13 +138,21 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
/**
* 暂停会话
* 暂停会话(使用默认时间口径)
*/
public void pausedStudySession(LocalDateTime endTime){
pausedStudySession(endTime, StudyTimePolicy.DEFAULT);
}
/**
* 暂停会话
*/
public void pausedStudySession(LocalDateTime endTime, StudyTimePolicy policy){
if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())) {
log.warn("不应出现的情况:暂停了一个状态为【{}】的学习会话({})", this.getSessionState(), this.getSessionNum());
} else {
this.setEndTime(ObjectUtils.isEmpty(endTime) ? LocalDateTime.now() : endTime);
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.setEffectivenessRatio(this.effectiveTime / this.actualTime);
@@ -133,22 +161,53 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
/**
* 有效学习时间的最小阈值(秒),低于此值不计入总学习时间
* 计算本次学习分段的结算时间(使用默认时间口径)。
*/
private static final double MIN_EFFECTIVE_TIME_SECONDS = 10 * 60;
public LocalDateTime resolveSettlementTime(LocalDateTime candidateEndTime) {
return resolveSettlementTime(candidateEndTime, StudyTimePolicy.DEFAULT);
}
/**
* 计算本次学习分段的结算时间:暂停、结束与超时收敛都必须走这里,避免同一行为产生两种统计结果。
*
* <p>{@code lastStartTime} 到候选结束时间超过遗忘判定阈值
* ({@link StudyTimePolicy#getForgetThresholdMinutes()})时,按「忘了点暂停/结束」处理,
* 只结算一个番茄钟({@link StudyTimePolicy#getWorkDurationMinutes()} 分钟);否则按候选结束时间结算。</p>
*/
public LocalDateTime resolveSettlementTime(LocalDateTime candidateEndTime, StudyTimePolicy policy) {
LocalDateTime end = ObjectUtils.isEmpty(candidateEndTime) ? LocalDateTime.now() : candidateEndTime;
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return end;
}
long minutes = Duration.between(this.lastStartTime, end).toMinutes();
if (minutes >= policy.getForgetThresholdMinutes()) {
log.info("会话[{}]本段学习已超过{}分钟无操作,按{}分钟结算",
this.getSessionNum(), policy.getForgetThresholdMinutes(), policy.getWorkDurationMinutes());
return this.lastStartTime.plusMinutes(policy.getWorkDurationMinutes());
}
return end;
}
/**
* 结束会话(使用默认时间口径)
*/
public void endedStudySession() {
endedStudySession(StudyTimePolicy.DEFAULT);
}
/**
* 结束会话
*/
public void endedStudySession() {
if (this.getSessionState().equals(StudySessionStateEnum.ENDED.name())){
public void endedStudySession(StudyTimePolicy policy) {
if (this.isEnded()){
log.warn("不应出现的情况:结束了一个状态为【{}】的学习会话",this.getSessionState());
}else {
if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) {
this.pausedStudySession(LocalDateTime.now());
this.pausedStudySession(LocalDateTime.now(), policy);
}
if (this.getEffectiveTime() < MIN_EFFECTIVE_TIME_SECONDS) {
log.info("会话[{}]有效学习时间({}秒)不足10分钟,不计入总学习时间", this.getSessionNum(), this.getEffectiveTime());
if (this.getEffectiveTime() < policy.getMinEffectiveTimeSeconds()) {
log.info("会话[{}]有效学习时间({}秒)不足{}分钟,不计入总学习时间",
this.getSessionNum(), this.getEffectiveTime(), policy.getMinEffectiveTimeSeconds() / 60);
this.setEffectiveTime(0);
this.setEffectivenessRatio(0);
}
@@ -156,6 +215,36 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
}
/**
* 服务端强制收敛悬挂会话(会话-04):进行中且超过硬兜底阈值时,
* 按遗忘规则结算为暂停并打上「自动收敛」标记,供前端提示「本次学习疑似忘记结束」。
*
* @return 是否发生了收敛(未满足条件时返回 false,便于调用方幂等处理)
*/
public boolean forceConverge(LocalDateTime now, StudyTimePolicy policy) {
if (!isForcePausable(now, policy)) {
return false;
}
log.warn("会话[{}]已悬挂超过{}分钟,服务端强制收敛为暂停", this.getSessionNum(), policy.getForcePauseMinutes());
this.setAutoConverged(true);
this.pausedStudySession(now, policy);
this.setLastModifiedTime(LocalDateTime.now());
return true;
}
/**
* 是否属于「长时间无人操作」的进行中会话:只有进行中且本段开始时间早于硬兜底阈值才成立。
*/
public boolean isForcePausable(LocalDateTime now, StudyTimePolicy policy) {
if (!StudySessionStateEnum.ONGOING.name().equals(this.sessionState)) {
return false;
}
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return false;
}
return Duration.between(this.lastStartTime, now).toMinutes() >= policy.getForcePauseMinutes();
}
/**
* 第一次运行
* @return
@@ -165,20 +254,27 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
/**
* 计算当前倒计时指针的位置(使用默认时间口径)
*/
public void calculatePointerPosition() throws ServiceException {
calculatePointerPosition(StudyTimePolicy.DEFAULT);
}
/**
* 计算当前倒计时指针的位置(单位:毫秒)
*
* 规则说明:
* - 如果是第一次运行(lastStartTime为null),则倒计时从25分钟开始
* - 如果是第一次运行(lastStartTime为null),则倒计时从番茄钟长度开始
* - 如果是暂停状态,返回上次保存的pointerPosition
* - 如果是进行中状态,返回 pointerPosition -(当前时间 - lastStartTime)
* 即从上次开始后经历的时间,从之前保存的pointerPosition中扣除
*
* @return 指针当前位置,单位为毫秒
*/
public void calculatePointerPosition() throws ServiceException {
public void calculatePointerPosition(StudyTimePolicy policy) throws ServiceException {
if (isFirstRun()) {
this.pointerPosition = WORK_DURATION * 60 * 1000L; // 毫秒
this.pointerPosition = policy.workDurationMillis();
return;
}
@@ -193,12 +289,12 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
case ONGOING:
long elapsedMillis = Duration.between(lastStartTime, LocalDateTime.now()).toMillis();
long basePointerPosition = ObjectUtils.isEmpty(pointerPosition)
? WORK_DURATION * 60 * 1000L
? policy.workDurationMillis()
: pointerPosition;
long newPointerPosition = basePointerPosition - elapsedMillis;
if (newPointerPosition <= 0) {
// 如果循环已经结束,则需要重置指针位置
this.pointerPosition = WORK_DURATION * 60 * 1000L;
this.pointerPosition = policy.workDurationMillis();
} else {
this.pointerPosition = newPointerPosition;
}
@@ -218,9 +314,40 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
public boolean isOverTime() {
LocalDateTime now = LocalDateTime.now();
long minutes = Duration.between(ObjectUtils.isEmpty(lastStartTime) ? LocalDateTime.now() : lastStartTime, now).toMinutes();
return minutes >= WORK_DURATION * 2;
/**
* 学习会话是否已经结束。
*/
public boolean isEnded() {
return StudySessionStateEnum.ENDED.name().equals(this.sessionState);
}
/**
* 本段学习是否已判定为「忘了点暂停/结束」(使用默认时间口径)。
*/
public boolean isForgotten() {
return isForgotten(LocalDateTime.now(), StudyTimePolicy.DEFAULT);
}
public boolean isForgotten(LocalDateTime now) {
return isForgotten(now, StudyTimePolicy.DEFAULT);
}
/**
* 本段学习是否已判定为「忘了点暂停/结束」,即需要按遗忘规则截断。
*
* <p>只有进行中的会话才成立:暂停与已结束的会话,其时间已在结算时入账,再次截断会重复扣减。
* 同时要求本段尚未结算过({@code end_time} 不早于 {@code last_start_time} 时视为已结算)。</p>
*/
public boolean isForgotten(LocalDateTime now, StudyTimePolicy policy) {
if (!StudySessionStateEnum.ONGOING.name().equals(this.sessionState)) {
return false;
}
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return false;
}
if (!ObjectUtils.isEmpty(this.endTime) && !this.endTime.isBefore(this.lastStartTime)) {
return false;
}
return Duration.between(this.lastStartTime, now).toMinutes() >= policy.getForgetThresholdMinutes();
}
}
@@ -1,5 +1,6 @@
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;
@@ -16,7 +17,7 @@ import java.io.Serializable;
@Data
public class TaskEntity extends BaseEntity implements Serializable {
@TableId
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
@@ -1,69 +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 java.io.Serializable;
import lombok.Data;
/**
* 测试表
* @author Guo
* @TableName test_table
*/
@TableName(value ="test_table")
@Data
public class TestTableEntity implements Serializable {
/**
* 测试主键
*/
@TableId(type = IdType.AUTO)
private Integer id;
/**
* id名字
*/
private String idName;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
TestTableEntity other = (TestTableEntity) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getIdName() == null ? other.getIdName() == null : this.getIdName().equals(other.getIdName()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getIdName() == null) ? 0 : getIdName().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", idName=").append(idName);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
@@ -0,0 +1,27 @@
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;
/**
* 复习排序偏好(复习-01):每个用户一条,保存三档预设之一。
*/
@TableName(value = "user_review_preferences")
@Data
public class UserReviewPreferencesEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 取值见 {@code ReviewSortPresetEnum} */
@TableField(value = "sort_preset")
private String sortPreset;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
@@ -0,0 +1,35 @@
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;
/**
* 标签字典项(闭环-03)。
*
* <p>字典只是打标签的候选项来源,与「对象上的标记」是两份数据:缺了对象的标签不是标记,
* 所以不在 markers 里为「空标签」造没有对象的行。字典的改名与删除只影响候选,
* 不改动任何对象上已经打好的标记。</p>
*/
@TableName(value = "user_tags")
@Data
public class UserTagEntity extends BaseEntity implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 标签名:展示保留用户输入的原样 */
@TableField(value = "tag_name")
private String tagName;
/** 归一化标签名:去首尾空白 + 小写;同一用户下唯一 */
@TableField(value = "normalized_name")
private String normalizedName;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
@@ -0,0 +1,36 @@
package com.guo.learningprogresstracker.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.EnumSet;
import java.util.Set;
/**
* AI 任务状态(AI-02)。
*/
@Getter
@AllArgsConstructor
public enum AiTaskStatusEnum {
/** 已提交,等待执行 */
PENDING("正在准备"),
/** 执行中 */
RUNNING("正在生成"),
/** 已完成,结果可重复获取 */
SUCCEEDED("已完成"),
/** 已失败,允许用户重新提交 */
FAILED("失败了");
private final String description;
/** 进行中的状态集合:用于「生成中」判定与防重复提交 */
public static final Set<AiTaskStatusEnum> ACTIVE = EnumSet.of(PENDING, RUNNING);
public static Set<String> activeNames() {
return ACTIVE.stream().map(Enum::name).collect(java.util.stream.Collectors.toSet());
}
}
@@ -0,0 +1,44 @@
package com.guo.learningprogresstracker.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* AI 任务类型(AI-02)。
*/
@Getter
@AllArgsConstructor
public enum AiTaskTypeEnum {
/** 回忆对比:把用户回忆大纲与标准导图对比 */
RECALL_COMPARE("回忆对比"),
/** 标准思维导图生成:全量、增量或按需生成 */
MIND_MAP("思维导图生成"),
/** 标签思维导图生成:按「标签集合 + 取数模式」生成或重建(闭环-04) */
TAG_MIND_MAP("标签思维导图生成"),
/** 标签范围回忆对比:把用户回忆大纲与标签导图对比(闭环-04) */
TAG_RECALL_COMPARE("标签回忆对比"),
/** 学习报告草稿聚合 */
REPORT_DRAFT("学习报告草稿"),
/** 学习引导:开放式问题引导与概念边界纠正(复习-06) */
GUIDANCE("学习引导");
private final String description;
/** 宽松解析:默认大小写不敏感,并用该类型的默认用户可见名称兜底 */
public static AiTaskTypeEnum parse(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return valueOf(value.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
}
@@ -0,0 +1,23 @@
package com.guo.learningprogresstracker.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 知识碎片的记录上下文类型(归属-01)。
*
* <p>记录上下文回答「这条碎片是在哪次学习行为里产生的」,不可变、不可为空。
* 它是时间轴上的归因,与「内容归属」(内容属于哪个任务)是两件事。</p>
*/
@Getter
@AllArgsConstructor
public enum FragmentContextTypeEnum {
/** 产生于某次学习会话 */
SESSION("学习会话"),
/** 产生于某次复习行为(回忆对比、学习引导) */
REVIEW("复习行为");
private final String description;
}
@@ -0,0 +1,20 @@
package com.guo.learningprogresstracker.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 标记种类(标记-01)。
*
* <p>两类彻底分开:系统标记由系统按固定词表写入、用户只读;用户标签由用户自由增删改。
* 分开的理由是「找出所有来自 X 的内容」这类检索的可靠性依赖于系统标记没被改过。</p>
*/
@Getter
@AllArgsConstructor
public enum MarkerKindEnum {
SYSTEM("系统标记"),
USER("用户标签");
private final String description;
}
@@ -0,0 +1,31 @@
package com.guo.learningprogresstracker.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 标记可挂的对象类型(标记-01)。
*
* <p>只允许知识碎片与学习任务:报告是会话的派生结果(且自身已有「按归属分组」这一维度,
* 再挂标记会出现两套分组语义),会话是时间轴对象(其流程性信息按边界要求留在主体上)。</p>
*/
@Getter
@AllArgsConstructor
public enum MarkerObjectTypeEnum {
FRAGMENT("知识碎片"),
TASK("学习任务");
private final String description;
public static MarkerObjectTypeEnum parse(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return valueOf(value.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
}

Some files were not shown because too many files have changed in this diff Show More