diff --git a/.env.example b/.env.example index a80ddad..7c4fd10 100644 --- a/.env.example +++ b/.env.example @@ -28,6 +28,12 @@ LLM_FALLBACK_ENABLED=true LLM_FALLBACK_RETRY_COUNT=2 LLM_FALLBACK_TIMEOUT_MS=30000 +# ==================== 异步任务队列(整页多题识别) ==================== +# Redis + BullMQ 队列(docker-compose 默认 redis://redis:6379)。 +# 留空时自动降级为进程内队列:接口行为一致(立即返回 taskId + 轮询), +# 但任务不跨进程重启保留,仅建议单实例自托管场景。 +REDIS_URL=redis://redis:6379 + # ==================== 服务器配置 ==================== SERVER_PORT=3000 SERVER_HOST=0.0.0.0 diff --git a/.github/workflows/auto-review.yml b/.github/workflows/auto-review.yml index 2672c2b..466ed79 100644 --- a/.github/workflows/auto-review.yml +++ b/.github/workflows/auto-review.yml @@ -23,9 +23,11 @@ jobs: node-version: '18' - name: Install dependencies - run: | - npm ci --prefix backend - npm ci --prefix frontend + run: npm ci + # 注:本仓库为 npm workspaces monorepo,唯一权威 lockfile 是根 package-lock.json + # (与 ci.yml 保持一致)。backend/frontend 下的子 lockfile 在 workspaces 模式下 + # 不会被 npm 维护( bullmq/vitest 等新依赖只写入根 lockfile),用 npm ci --prefix + # 安装会因不同步而失败,故统一走根安装。 - name: Run code analysis id: analysis diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md index 598d4b8..1ad8b0b 100644 --- a/API_DOCUMENTATION.md +++ b/API_DOCUMENTATION.md @@ -435,6 +435,36 @@ Authorization: Bearer } ``` +### PUT /api/questions/:id/error-tags + +更新错题的错因标签(多维度错因体系)。标签白名单:`审题不清` / `计算粗心` / `公式遗忘` / `方法缺失` / `其他`;去重后最多 10 个,非法值被过滤。 + +**请求头**: +``` +Authorization: Bearer +``` + +**请求体**: +```json +{ + "tags": ["审题不清", "计算粗心"], + "mode": "merge" +} +``` + +- `mode: "replace"` 全量替换;默认/`"merge"` 与现有标签取并集(重做流程追加标注场景)。 + +**响应**: +```json +{ + "status": "success", + "data": { + "id": "uuid", + "errorTags": ["审题不清", "计算粗心"] + } +} +``` + ### DELETE /api/questions/:id 删除错题 @@ -1092,6 +1122,33 @@ Authorization: Bearer } ``` +### GET /api/reports/error-profile/:studentId + +错因多维度标签画像(评审 C1 后 `studentId` 同时接受登录用户 id(users.id)与学生档案 id(students.id)):返回错因标签分布 + 按错误次数加权的薄弱知识点,供学生端与家长端「薄弱点画像」页使用。 + +**请求头**: +``` +Authorization: Bearer +``` + +**响应**: +```json +{ + "status": "success", + "data": { + "totalQuestions": 50, + "taggedQuestions": 32, + "errorTagDistribution": [ + { "tag": "审题不清", "count": 12 }, + { "tag": "计算粗心", "count": 8 } + ], + "weakKnowledgePoints": [ + { "point": "二次函数", "questionCount": 14, "incorrectCount": 9, "totalQuestions": 20 } + ] + } +} +``` + ### GET /api/reports/student/:studentId/daily 获取日报 @@ -1126,7 +1183,7 @@ Authorization: Bearer ### GET /api/llm/usage/summary ### POST /api/questions/identify-multi -大模型多题切分识别接口,支持上传整页图片,自动定位并识别页面中的多道错题。 +大模型多题切分识别接口(同步兼容接口,建议改用异步接口,避免长请求触发 Nginx 504)。 #### 请求 - Header: `Content-Type: multipart/form-data` @@ -1136,11 +1193,49 @@ Authorization: Bearer ```json { "status": "success", - "data": [ - { "title": "...", "content": "...", "answer": "...", "bbox": [0,0,100,100] } - ] + "data": { + "items": [ + { "tempId": "...", "title": "...", "content": "...", "subject": "math", "type": "choice", "answer": "...", "explanation": "...", "isDuplicate": false } + ] + } +} +``` + +### POST /api/questions/identify-multi/async +整页多题识别异步任务提交(推荐):立即返回 taskId,前端轮询进度与结果,消除 15-30s 同步挂起的 504 风险(见 docs/adr/0004)。 + +#### 请求 +- Header: `Content-Type: multipart/form-data` +- Body: `file` (Buffer/Stream)、`subject`(可选,默认 math) + +#### 响应(202) +```json +{ + "status": "success", + "data": { + "taskId": "", + "statusUrl": "/api/questions/identify-multi/tasks/" + } +} +``` + +### GET /api/questions/identify-multi/tasks/:taskId +查询异步识别任务状态(轮询入口,建议 2 秒间隔,超时 10 分钟)。 + +#### 响应 +```json +{ + "status": "success", + "data": { + "taskId": "", + "state": "queued | processing | completed | failed", + "progress": 55, + "result": { "items": [ ... 同同步接口 items 结构 ... ] }, + "error": "失败原因(仅 failed)" + } } ``` +任务不存在或已过期(完成后 1 小时清理)返回 404。 获取LLM用量汇总 **请求头**: diff --git a/README.md b/README.md index 29b93a0..b32ca47 100644 --- a/README.md +++ b/README.md @@ -7,14 +7,16 @@ ## 功能特性 ### 学生端 -- 拍照/手动录入错题,支持整页多题 LLM 切分识别 +- 拍照/手动录入错题,支持整页多题 LLM 切分识别(v1.3.0 起异步化:立即返回 taskId + 进度轮询,不再阻塞触发 504) - 在线作答/拍照手写重做 -- 掌握状态跟踪(连续 3 次做对,间隔 1/7/30 天) -- 今日任务推荐、相似题练习 +- 掌握状态跟踪(v1.3.0 起采用艾宾浩斯间隔调度:第 1/2/4/7/15 天动态复习,走完 5 轮间隔复习即掌握) +- 今日待复习直达、错因标签标注(审题不清/计算粗心/公式遗忘/方法缺失等)、相似题练习 +- 错题本 A4 排版导出:纯题卷 / 题卷+详细解析两种模式,一键打印或另存为 PDF,线下重做 ### 家长端 - 完全透明查看学生学习情况 - 周报查看(每周一)、站内红点提醒 +- 薄弱点画像(v1.3.0):错因占比 + 薄弱知识点可视化统计,移动端友好 ### 管理员端 - LLM 用量监控与告警 @@ -114,6 +116,13 @@ npm run dev:frontend # 前端开发服务器 http://localhost:3001 npm run migrate ``` +v1.3.0 新增 `questions.errorTags` 列(迁移 `1750000000000-AddErrorTagsToQuestions`,幂等可重复执行)。 + +### Redis(可选) + +v1.3.0 起整页多题识别默认使用 Redis + BullMQ 异步队列(docker-compose 已内置 `redis` 服务并注入 `REDIS_URL`)。 +若自托管场景不想引入 Redis,可将 `REDIS_URL` 置空:系统自动降级为进程内队列,接口行为一致(立即返回 taskId + 轮询),但任务不跨进程重启保留,仅建议单实例部署(见 `docs/adr/0004`)。 + ## 配置 ### LLM 配置 diff --git a/backend/package-lock.json b/backend/package-lock.json index f5dfd77..aaa0179 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "error-management-backend", - "version": "1.2.1", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "error-management-backend", - "version": "1.2.1", + "version": "1.3.0", "dependencies": { "bcryptjs": "^2.4.3", "cors": "^2.8.5", diff --git a/backend/package.json b/backend/package.json index 26f437e..3f50fc2 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "error-management-backend", - "version": "1.2.1", + "version": "1.3.0", "description": "错题管理系统后端 - Node.js + Express + TypeScript", "main": "dist/index.js", "scripts": { @@ -17,11 +17,13 @@ }, "dependencies": { "bcryptjs": "^2.4.3", + "bullmq": "^5.81.5", "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", "express-rate-limit": "^7.2.0", "helmet": "^7.1.0", + "ioredis": "^5.11.1", "jsonwebtoken": "^9.0.2", "morgan": "^1.10.0", "multer": "^1.4.5-lts.1", diff --git a/backend/src/__tests__/controllers/MasteryController.test.ts b/backend/src/__tests__/controllers/MasteryController.test.ts index 051a3f6..32456cf 100644 --- a/backend/src/__tests__/controllers/MasteryController.test.ts +++ b/backend/src/__tests__/controllers/MasteryController.test.ts @@ -49,6 +49,8 @@ describe('MasteryController', () => { select: jest.fn().mockReturnThis(), addSelect: jest.fn().mockReturnThis(), where: jest.fn().mockReturnThis(), + andWhere: jest.fn().mockReturnThis(), + getCount: jest.fn().mockResolvedValue(0), getMany: jest.fn().mockResolvedValue([ { status: 'mastered', correctCount: 5, incorrectCount: 0 }, { status: 'learning', correctCount: 2, incorrectCount: 3 }, diff --git a/backend/src/__tests__/controllers/QuestionAsyncTask.test.ts b/backend/src/__tests__/controllers/QuestionAsyncTask.test.ts new file mode 100644 index 0000000..971a983 --- /dev/null +++ b/backend/src/__tests__/controllers/QuestionAsyncTask.test.ts @@ -0,0 +1,93 @@ +jest.mock('../../config/database', () => ({ + AppDataSource: { getRepository: jest.fn(() => null) }, +})) +jest.mock('../../services/tasks/IdentificationTaskManager', () => ({ + identificationTaskManager: { + submit: jest.fn(), + getStatus: jest.fn(), + init: jest.fn(), + close: jest.fn(), + }, +})) + +import { QuestionController } from '../../controllers/QuestionController' +import { identificationTaskManager } from '../../services/tasks/IdentificationTaskManager' + +const submitMock = identificationTaskManager.submit as jest.Mock +const getStatusMock = identificationTaskManager.getStatus as jest.Mock + +const mockReq = (body: any = {}, params: any = {}, file: any = null): any => ({ + body, params, file, + user: { id: 'student1', role: 'student' }, + headers: {}, +}) +const mockRes = () => { + const res: any = {} + res.status = jest.fn().mockReturnValue(res) + res.json = jest.fn().mockReturnValue(res) + return res +} +const mockNext = jest.fn() + +describe('QuestionController 异步整页识别端点', () => { + let controller: QuestionController + + beforeEach(() => { + jest.clearAllMocks() + controller = new QuestionController() + }) + + describe('submitIdentifyMultiTask', () => { + it('缺少文件返回 400', async () => { + const res = mockRes() + await controller.submitIdentifyMultiTask(mockReq(), res, mockNext) + expect(res.status).toHaveBeenCalledWith(400) + }) + + it('提交成功返回 202 + taskId + statusUrl', async () => { + submitMock.mockResolvedValue('task-123') + const res = mockRes() + await controller.submitIdentifyMultiTask( + mockReq({ subject: 'math' }, {}, { path: '/uploads/img.jpg' }), + res, + mockNext + ) + expect(res.status).toHaveBeenCalledWith(202) + expect(res.json).toHaveBeenCalledWith({ + status: 'success', + data: { + taskId: 'task-123', + statusUrl: '/api/questions/identify-multi/tasks/task-123', + }, + }) + expect(submitMock).toHaveBeenCalledWith({ + imagePath: '/uploads/img.jpg', + userId: 'student1', + subject: 'math', + }) + }) + }) + + describe('getIdentifyMultiTaskStatus', () => { + it('任务不存在返回 404', async () => { + getStatusMock.mockResolvedValue(null) + const res = mockRes() + await controller.getIdentifyMultiTaskStatus(mockReq({}, { taskId: 'gone' }), res, mockNext) + expect(res.status).toHaveBeenCalledWith(404) + }) + + it('返回任务状态数据', async () => { + getStatusMock.mockResolvedValue({ + taskId: 't1', + state: 'processing', + progress: 55, + }) + const res = mockRes() + await controller.getIdentifyMultiTaskStatus(mockReq({}, { taskId: 't1' }), res, mockNext) + expect(res.json).toHaveBeenCalledWith({ + status: 'success', + data: { taskId: 't1', state: 'processing', progress: 55 }, + }) + }) + }) +}) diff --git a/backend/src/__tests__/controllers/QuestionController.test.ts b/backend/src/__tests__/controllers/QuestionController.test.ts index 229431a..c67c838 100644 --- a/backend/src/__tests__/controllers/QuestionController.test.ts +++ b/backend/src/__tests__/controllers/QuestionController.test.ts @@ -126,6 +126,43 @@ describe('QuestionController', () => { const savedData = mockRepo.create.mock.calls[0][0] expect(savedData.imageUrl).toBe('/uploads/img-123.jpg') }) + + it('multipart 场景 errorTags 为 JSON 字符串时应还原数组而非按逗号切分(评审 B2)', async () => { + mockRepo.find.mockResolvedValue([]) + mockRepo.create.mockImplementation((data: any) => data) + mockRepo.save.mockImplementation(async (data: any) => data) + const res = mockRes() + // 与前端 FormData.append(key, JSON.stringify(value)) 完全一致的载荷形状 + const req = mockReq({ + title: '带错因题目', + content: '计算 2+3', + subject: 'math', + type: 'choice', + difficulty: '1', + errorTags: '["审题不清","计算粗心"]', + }) + await controller.createQuestion(req, res, mockNext) + const savedData = mockRepo.create.mock.calls[0][0] + expect(savedData.errorTags).toEqual(['审题不清', '计算粗心']) + }) + + it('errorTags 携带非白名单值时被过滤', async () => { + mockRepo.find.mockResolvedValue([]) + mockRepo.create.mockImplementation((data: any) => data) + mockRepo.save.mockImplementation(async (data: any) => data) + const res = mockRes() + const req = mockReq({ + title: 'T', + content: 'C', + subject: 'math', + type: 'choice', + difficulty: '1', + errorTags: ['胡写的标签', '公式遗忘'], + }) + await controller.createQuestion(req, res, mockNext) + const savedData = mockRepo.create.mock.calls[0][0] + expect(savedData.errorTags).toEqual(['公式遗忘']) + }) }) describe('deleteQuestion', () => { diff --git a/backend/src/__tests__/services/ErrorProfileService.test.ts b/backend/src/__tests__/services/ErrorProfileService.test.ts new file mode 100644 index 0000000..d6c0f6b --- /dev/null +++ b/backend/src/__tests__/services/ErrorProfileService.test.ts @@ -0,0 +1,116 @@ +import { ErrorProfileService } from '../../services/ErrorProfileService' +import { ERROR_TAG_PRESETS, normalizeErrorTags, mergeErrorTags } from '../../constants/errorTags' + +const mockQuestionRepo = { find: jest.fn() } +const mockMasteryRepo = { find: jest.fn() } + +jest.mock('../../config/database', () => ({ + AppDataSource: { + getRepository: jest.fn(), + }, +})) + +const resetRepos = () => { + mockQuestionRepo.find.mockReset().mockResolvedValue([]) + mockMasteryRepo.find.mockReset().mockResolvedValue([]) + const { AppDataSource } = require('../../config/database') + ;(AppDataSource.getRepository as jest.Mock).mockReset() + // 构造顺序:先 Question 后 Mastery + ;(AppDataSource.getRepository as jest.Mock) + .mockImplementationOnce(() => mockQuestionRepo) + .mockImplementationOnce(() => mockMasteryRepo) +} + +describe('errorTags 常量(错因标签白名单)', () => { + it('预设包含四个核心错因与「其他」', () => { + expect(ERROR_TAG_PRESETS).toEqual(['审题不清', '计算粗心', '公式遗忘', '方法缺失', '其他']) + }) + + it('normalizeErrorTags 过滤非白名单值并去重', () => { + expect(normalizeErrorTags(['审题不清', '乱写的', '审题不清', ' 计算粗心 '])).toEqual([ + '审题不清', + '计算粗心', + ]) + }) + + it('normalizeErrorTags 支持逗号分隔字符串', () => { + expect(normalizeErrorTags('公式遗忘,方法缺失')).toEqual(['公式遗忘', '方法缺失']) + }) + + it('normalizeErrorTags 忽略非字符串/空输入', () => { + expect(normalizeErrorTags(null)).toEqual([]) + expect(normalizeErrorTags(undefined)).toEqual([]) + expect(normalizeErrorTags(123)).toEqual([]) + }) + + it('mergeErrorTags 取并集去重', () => { + expect(mergeErrorTags(['审题不清'], ['审题不清', '计算粗心'])).toEqual([ + '审题不清', + '计算粗心', + ]) + }) +}) + +describe('ErrorProfileService(薄弱点画像聚合)', () => { + beforeEach(() => { + resetRepos() + }) + + it('空数据返回空画像', async () => { + const service = new ErrorProfileService() + const result = await service.getErrorProfile('s1') + expect(result).toEqual({ + totalQuestions: 0, + taggedQuestions: 0, + errorTagDistribution: [], + weakKnowledgePoints: [], + }) + }) + + it('聚合错因占比(按次数降序)与标注题数', async () => { + mockQuestionRepo.find.mockResolvedValue([ + { errorTags: ['审题不清', '计算粗心'] }, + { errorTags: ['审题不清'] }, + { errorTags: [] }, + ]) + mockMasteryRepo.find.mockResolvedValue([]) + + const result = await new ErrorProfileService().getErrorProfile('s1') + expect(result.totalQuestions).toBe(3) + expect(result.taggedQuestions).toBe(2) + expect(result.errorTagDistribution).toEqual([ + { tag: '审题不清', count: 2 }, + { tag: '计算粗心', count: 1 }, + ]) + }) + + it('聚合薄弱知识点(有错误记录的题目,按错误次数降序,含题目总数)', async () => { + mockQuestionRepo.find.mockResolvedValue([ + { knowledgePoints: ['一元二次方程', '因式分解'] }, + ]) + mockMasteryRepo.find.mockResolvedValue([ + { + incorrectCount: 3, + question: { knowledgePoints: ['一元二次方程', '因式分解'] }, + }, + { + incorrectCount: 1, + question: { knowledgePoints: ['一元二次方程'] }, + }, + ]) + + const result = await new ErrorProfileService().getErrorProfile('s1') + expect(result.weakKnowledgePoints).toEqual([ + { point: '一元二次方程', questionCount: 2, incorrectCount: 4, totalQuestions: 1 }, + { point: '因式分解', questionCount: 1, incorrectCount: 3, totalQuestions: 1 }, + ]) + }) + + it('无错误记录的知识点不出现在画像中', async () => { + mockQuestionRepo.find.mockResolvedValue([{ knowledgePoints: ['化学平衡'] }]) + mockMasteryRepo.find.mockResolvedValue([{ incorrectCount: 0, question: { knowledgePoints: ['化学平衡'] } }]) + + const result = await new ErrorProfileService().getErrorProfile('s1') + expect(result.weakKnowledgePoints).toEqual([]) + }) +}) diff --git a/backend/src/__tests__/services/ReviewScheduler.test.ts b/backend/src/__tests__/services/ReviewScheduler.test.ts new file mode 100644 index 0000000..dd04079 --- /dev/null +++ b/backend/src/__tests__/services/ReviewScheduler.test.ts @@ -0,0 +1,142 @@ +import { + EBBINGHAUS_INTERVALS, + EBBINGHAUS_TOTAL_RUNGS, + EBBINGHAUS_MASTERY_LEVEL, + applyReviewResult, + isReviewDue, + addDays, + startOfToday, + endOfToday, +} from '../../services/ReviewScheduler' +import { Mastery, MasteryStatus } from '../../models/Mastery' + +const createMastery = (overrides: Partial = {}): Mastery => { + const m = new Mastery() + m.status = MasteryStatus.NEW + m.correctCount = 0 + m.incorrectCount = 0 + m.intervalLevel = 0 + return Object.assign(m, overrides) +} + +// 固定基准时间,避免测试受「当天」影响 +const BASE = new Date('2026-01-10T10:00:00.000Z') + +describe('ReviewScheduler(艾宾浩斯间隔调度)', () => { + it('间隔表应为 1/2/4/7/15 天,共 5 轮,掌握阈值 6', () => { + expect(EBBINGHAUS_INTERVALS).toEqual([1, 2, 4, 7, 15]) + expect(EBBINGHAUS_TOTAL_RUNGS).toBe(5) + expect(EBBINGHAUS_MASTERY_LEVEL).toBe(6) + }) + + describe('applyReviewResult', () => { + it('第 1 次做对 → 1 天后复习,进入 learning', () => { + const m = createMastery() + applyReviewResult(m, true, BASE) + expect(m.status).toBe(MasteryStatus.LEARNING) + expect(m.intervalLevel).toBe(1) + expect(m.correctCount).toBe(1) + expect(m.nextReviewDate!.getTime()).toBe(addDays(BASE, 1).getTime()) + }) + + it('连续做对逐轮顺延:+1 → +2 → +4 → +7 → +15 天', () => { + const m = createMastery() + const expected = [1, 2, 4, 7, 15] + for (let i = 0; i < expected.length; i++) { + applyReviewResult(m, true, BASE) + expect(m.intervalLevel).toBe(i + 1) + expect(m.nextReviewDate!.getTime()).toBe(addDays(BASE, expected[i]).getTime()) + } + expect(m.status).toBe(MasteryStatus.LEARNING) + }) + + it('第 6 次做对(完成第 5 轮 15 天间隔复习)→ 已掌握,不再安排复习', () => { + const m = createMastery() + for (let i = 0; i < 5; i++) applyReviewResult(m, true, BASE) + expect(m.status).toBe(MasteryStatus.LEARNING) + applyReviewResult(m, true, BASE) + expect(m.intervalLevel).toBe(6) + expect(m.status).toBe(MasteryStatus.MASTERED) + expect(m.nextReviewDate).toBeNull() + }) + + it('复习做错 → 轮次归零,1 天后重新开始', () => { + const m = createMastery() + applyReviewResult(m, true, BASE) + applyReviewResult(m, true, BASE) + expect(m.intervalLevel).toBe(2) + applyReviewResult(m, false, BASE) + expect(m.status).toBe(MasteryStatus.LEARNING) + expect(m.intervalLevel).toBe(0) + expect(m.correctCount).toBe(0) + expect(m.incorrectCount).toBe(1) + expect(m.nextReviewDate!.getTime()).toBe(addDays(BASE, 1).getTime()) + }) + + it('每次复习都更新 lastReviewDate / lastCorrectDate / lastIncorrectDate', () => { + const m = createMastery() + applyReviewResult(m, true, BASE) + expect(m.lastReviewDate!.getTime()).toBe(BASE.getTime()) + expect(m.lastCorrectDate!.getTime()).toBe(BASE.getTime()) + const t2 = new Date(BASE.getTime() + 3600_000) + applyReviewResult(m, false, t2) + expect(m.lastIncorrectDate!.getTime()).toBe(t2.getTime()) + expect(m.lastReviewDate!.getTime()).toBe(t2.getTime()) + }) + }) + + describe('isReviewDue', () => { + it('已掌握的记录永不到期', () => { + const m = createMastery({ + status: MasteryStatus.MASTERED, + nextReviewDate: new Date('2020-01-01'), + }) + expect(isReviewDue(m, BASE)).toBe(false) + }) + + it('nextReviewDate 在今天结束前 → 到期', () => { + const m = createMastery({ + status: MasteryStatus.LEARNING, + nextReviewDate: new Date('2026-01-09T08:00:00.000Z'), + }) + expect(isReviewDue(m, BASE)).toBe(true) + }) + + it('nextReviewDate 在明天 → 未到期', () => { + const m = createMastery({ + status: MasteryStatus.LEARNING, + nextReviewDate: addDays(startOfToday(BASE), 1), + }) + expect(isReviewDue(m, BASE)).toBe(false) + }) + + it('无 nextReviewDate 且创建于今天 → 未到期(留在新错题队列)', () => { + const m = createMastery({ + status: MasteryStatus.NEW, + nextReviewDate: null, + // 创建时间取本地时区的今天零点,保证任意时区下都等于 startOfToday + createdAt: startOfToday(BASE), + }) + expect(isReviewDue(m, BASE)).toBe(false) + }) + + it('无 nextReviewDate 且创建于昨天之前 → 到期(历史遗留)', () => { + const m = createMastery({ + status: MasteryStatus.NEW, + nextReviewDate: null, + createdAt: addDays(startOfToday(BASE), -1), + }) + expect(isReviewDue(m, BASE)).toBe(true) + }) + }) + + describe('时间工具', () => { + it('startOfToday / endOfToday 覆盖整天', () => { + const s = startOfToday(BASE) + const e = endOfToday(BASE) + expect(s.getHours()).toBe(0) + expect(e.getHours()).toBe(23) + expect(e.getTime() - s.getTime()).toBe(24 * 3600 * 1000 - 1) + }) + }) +}) diff --git a/backend/src/__tests__/services/tasks/IdentificationTaskManager.test.ts b/backend/src/__tests__/services/tasks/IdentificationTaskManager.test.ts new file mode 100644 index 0000000..5fae577 --- /dev/null +++ b/backend/src/__tests__/services/tasks/IdentificationTaskManager.test.ts @@ -0,0 +1,200 @@ +jest.mock('../../../config/database', () => ({ + AppDataSource: { getRepository: jest.fn(() => null) }, +})) +jest.mock('../../../config/redis', () => ({ + isRedisEnabled: jest.fn(() => !!process.env.REDIS_URL), + getRedisConnection: jest.fn(() => (process.env.REDIS_URL ? { fake: 'conn' } : null)), + closeRedisConnection: jest.fn(async () => {}), +})) +jest.mock('bullmq', () => { + const fakeJobStore = new Map() + class FakeJob { + id: string + data: any + state: string + progressValue: number + returnvalue: any + failedReason?: string + constructor(id: string, data: any) { + this.id = id + this.data = data + this.state = 'waiting' + this.progressValue = 0 + fakeJobStore.set(id, this) + } + get progress() { + return this.progressValue + } + async getState() { + return this.state + } + } + class FakeQueue { + name: string + opts: any + added: any[] = [] + constructor(name: string, opts: any) { + this.name = name + this.opts = opts + } + async add(_name: string, data: any) { + const id = `job-${this.added.length + 1}` + const job = new FakeJob(id, data) + this.added.push(job) + return job + } + async getJob(id: string) { + return fakeJobStore.get(id) || null + } + async close() {} + } + class FakeWorker { + name: string + processor: any + opts: any + constructor(name: string, processor: any, opts: any) { + this.name = name + this.processor = processor + this.opts = opts + } + on() {} + async close() {} + } + return { + Queue: FakeQueue, + Worker: FakeWorker, + __fakeJobStore: fakeJobStore, + } +}) +jest.mock('../../../services/tasks/identifyMultiPipeline', () => ({ + processIdentifyMulti: jest.fn(), +})) + +import { identificationTaskManager } from '../../../services/tasks/IdentificationTaskManager' +import { processIdentifyMulti } from '../../../services/tasks/identifyMultiPipeline' + +const processMock = processIdentifyMulti as jest.Mock + +beforeEach(async () => { + jest.clearAllMocks() + delete process.env.REDIS_URL + processMock.mockReset() + // 复位单例初始化状态,避免前一用例的队列后端残留 + await identificationTaskManager.close() +}) + +describe('IdentificationTaskManager(进程内队列降级模式)', () => { + it('submit 立即返回 taskId 并异步执行到 completed', async () => { + processMock.mockResolvedValue({ items: [{ tempId: 't1', title: '题1' }] }) + + const taskId = await identificationTaskManager.submit({ + imagePath: '/uploads/x.jpg', + userId: 'u1', + subject: 'math', + }) + expect(taskId).toBeTruthy() + expect(identificationTaskManager.isRedisBacked()).toBe(false) + + // 链式异步执行,稍等后应 completed 且带结果 + await new Promise((r) => setTimeout(r, 30)) + const status = await identificationTaskManager.getStatus(taskId) + expect(status).toMatchObject({ + taskId, + state: 'completed', + progress: 100, + }) + expect(status!.result!.items).toEqual([{ tempId: 't1', title: '题1' }]) + expect(processMock).toHaveBeenCalledWith( + { imagePath: '/uploads/x.jpg', userId: 'u1', subject: 'math' }, + expect.any(Function) + ) + }) + + it('执行失败 → failed 状态 + 错误信息', async () => { + processMock.mockRejectedValue(new Error('boom')) + + const taskId = await identificationTaskManager.submit({ imagePath: '/x.jpg', userId: 'u1' }) + await new Promise((r) => setTimeout(r, 30)) + const status = await identificationTaskManager.getStatus(taskId) + expect(status).toMatchObject({ state: 'failed', error: 'boom' }) + }) + + it('未知 taskId 返回 null', async () => { + expect(await identificationTaskManager.getStatus('no-such-task')).toBeNull() + }) + + it('归属校验(评审 S1):非本人 taskId 返回 null,本人可读', async () => { + processMock.mockResolvedValue({ items: [{ tempId: 't1' }] }) + const taskId = await identificationTaskManager.submit({ + imagePath: '/mine.jpg', + userId: 'user-a', + }) + await new Promise((r) => setTimeout(r, 30)) + expect(await identificationTaskManager.getStatus(taskId, 'user-a')).toMatchObject({ taskId }) + expect(await identificationTaskManager.getStatus(taskId, 'user-b')).toBeNull() + // 不传 viewer 时保持兼容(历史行为) + expect(await identificationTaskManager.getStatus(taskId)).toMatchObject({ taskId }) + }) + + it('任务串行执行(并发 1)', async () => { + const order: string[] = [] + processMock.mockImplementation(async (_data: any, onProgress: any) => { + order.push('start') + await new Promise((r) => setTimeout(r, 20)) + order.push('end') + return { items: [] } + }) + + const t1 = await identificationTaskManager.submit({ imagePath: '/1.jpg', userId: 'u1' }) + const t2 = await identificationTaskManager.submit({ imagePath: '/2.jpg', userId: 'u1' }) + await new Promise((r) => setTimeout(r, 80)) + + expect(order).toEqual(['start', 'end', 'start', 'end']) + expect((await identificationTaskManager.getStatus(t1))!.state).toBe('completed') + expect((await identificationTaskManager.getStatus(t2))!.state).toBe('completed') + }) +}) + +describe('IdentificationTaskManager(Redis + BullMQ 模式)', () => { + it('REDIS_URL 配置时走 BullMQ:submit 返回 jobId,getStatus 映射状态与结果', async () => { + process.env.REDIS_URL = 'redis://localhost:6379' + const bullmq = require('bullmq') + + const taskId = await identificationTaskManager.submit({ + imagePath: '/uploads/y.jpg', + userId: 'u1', + subject: 'physics', + }) + expect(identificationTaskManager.isRedisBacked()).toBe(true) + + let status = await identificationTaskManager.getStatus(taskId) + expect(status).toMatchObject({ taskId, state: 'queued', progress: 0 }) + + // 模拟任务处理中/完成 + const job = bullmq.__fakeJobStore.get(taskId) + job.state = 'active' + job.progressValue = 55 + status = await identificationTaskManager.getStatus(taskId) + expect(status).toMatchObject({ state: 'processing', progress: 55 }) + + job.state = 'completed' + job.returnvalue = { items: [{ tempId: 'r1' }] } + status = await identificationTaskManager.getStatus(taskId) + expect(status).toMatchObject({ state: 'completed', progress: 100 }) + expect(status!.result!.items).toEqual([{ tempId: 'r1' }]) + + job.state = 'failed' + job.failedReason = 'LLM timeout' + status = await identificationTaskManager.getStatus(taskId) + expect(status).toMatchObject({ state: 'failed', error: 'LLM timeout' }) + }) + + it('close() 释放队列并复位初始化状态', async () => { + process.env.REDIS_URL = 'redis://localhost:6379' + await identificationTaskManager.submit({ imagePath: '/z.jpg', userId: 'u1' }) + expect(identificationTaskManager.isRedisBacked()).toBe(true) + await identificationTaskManager.close() + expect(identificationTaskManager.isRedisBacked()).toBe(false) + delete process.env.REDIS_URL + }) +}) diff --git a/backend/src/__tests__/services/tasks/identifyMultiPipeline.test.ts b/backend/src/__tests__/services/tasks/identifyMultiPipeline.test.ts new file mode 100644 index 0000000..6f0c154 --- /dev/null +++ b/backend/src/__tests__/services/tasks/identifyMultiPipeline.test.ts @@ -0,0 +1,79 @@ +jest.mock('../../../config/database', () => { + const mockQuestionRepo = { + find: jest.fn().mockResolvedValue([]), + } + return { + AppDataSource: { + getRepository: jest.fn(() => mockQuestionRepo), + __mockQuestionRepo: mockQuestionRepo, + }, + } +}) +jest.mock('../../../services/LLMService', () => { + const state = { impl: jest.fn() } + return { + LLMService: jest.fn(() => ({ identifyMultiQuestions: state.impl })), + __llmState: state, + } +}) + +import { processIdentifyMulti, textFingerprint } from '../../../services/tasks/identifyMultiPipeline' + +const { AppDataSource } = require('../../../config/database') +const { __llmState } = require('../../../services/LLMService') + +beforeEach(() => { + jest.clearAllMocks() + __llmState.impl.mockReset() + AppDataSource.__mockQuestionRepo.find.mockReset().mockResolvedValue([]) +}) + +describe('identifyMultiPipeline(整页识别任务管道)', () => { + it('LLM 识别成功:条目归一化(tempId/默认值)', async () => { + __llmState.impl.mockResolvedValue([ + { title: '题目A', content: '求解 x', subject: 'physics', type: 'fill', answer: 'x=1', explanation: '移项' }, + { title: '题目B', content: '计算 2+3' }, + ]) + + const { items } = await processIdentifyMulti({ imagePath: '/p.jpg', userId: 'u1' }) + expect(items).toHaveLength(2) + expect(items[0]).toMatchObject({ title: '题目A', subject: 'physics', type: 'fill', isDuplicate: false }) + expect(items[1]).toMatchObject({ title: '题目B', subject: 'math', type: 'choice', isDuplicate: false }) + expect(items.every((i: any) => typeof i.tempId === 'string' && i.tempId)).toBe(true) + }) + + it('LLM 失败/返回空:回退内置 mock 条目', async () => { + __llmState.impl.mockResolvedValue(null) + const { items } = await processIdentifyMulti({ imagePath: '/p.jpg', userId: 'u1', subject: 'chemistry' }) + expect(items).toHaveLength(2) + expect(items[0].title).toBe('识别题目 1') + expect(items[0].subject).toBe('chemistry') + }) + + it('文本指纹与已有错题重复 → isDuplicate 标记 + existingQuestionId', async () => { + __llmState.impl.mockResolvedValue([ + { title: '求解方程', content: 'x^2-4=0 的解' }, + ]) + AppDataSource.__mockQuestionRepo.find.mockResolvedValue([ + { id: 'q-existing', title: '求解方程', content: 'x^2-4=0 的解' }, + ]) + + const { items } = await processIdentifyMulti({ imagePath: '/p.jpg', userId: 'u1' }) + expect(items[0].isDuplicate).toBe(true) + expect(items[0].existingQuestionId).toBe('q-existing') + }) + + it('防重查询异常时整体失败(任务进入 failed)', async () => { + __llmState.impl.mockResolvedValue([{ title: 'T', content: 'C' }]) + AppDataSource.__mockQuestionRepo.find.mockRejectedValue(new Error('db down')) + + await expect( + processIdentifyMulti({ imagePath: '/p.jpg', userId: 'u1' }) + ).rejects.toThrow('db down') + }) + + it('textFingerprint 去除空白与标点', () => { + expect(textFingerprint('Hello, world!', ' x = 1 ')).toBe('Helloworldx1') + expect(textFingerprint('已知:a=1', '求 b?')).toBe('已知a1求b') + }) +}) diff --git a/backend/src/__tests__/utils/resolveStudentUserId.test.ts b/backend/src/__tests__/utils/resolveStudentUserId.test.ts new file mode 100644 index 0000000..a29924c --- /dev/null +++ b/backend/src/__tests__/utils/resolveStudentUserId.test.ts @@ -0,0 +1,52 @@ +jest.mock('../../config/database', () => { + const mockStudentRepo = { + findOne: jest.fn().mockResolvedValue(null), + } + return { + AppDataSource: { + getRepository: jest.fn(() => mockStudentRepo), + __mockStudentRepo: mockStudentRepo, + }, + } +}) + +import { resolveStudentUserId } from '../../utils/resolveStudentUserId' + +const { AppDataSource } = require('../../config/database') + +const studentRepo = AppDataSource.__mockStudentRepo + +beforeEach(() => { + jest.clearAllMocks() + studentRepo.findOne.mockReset().mockResolvedValue(null) +}) + +describe('resolveStudentUserId(studentId 口径归一,评审 C1)', () => { + it('入参是学生档案 id(students.id)→ 解析为其登录用户 id(users.id)', async () => { + studentRepo.findOne.mockResolvedValue({ + id: 'student-row-id', + user: { id: 'user-login-id' }, + }) + + expect(await resolveStudentUserId('student-row-id')).toBe('user-login-id') + expect(studentRepo.findOne).toHaveBeenCalledWith({ + where: { id: 'student-row-id' }, + relations: ['user'], + }) + }) + + it('入参不是学生档案 id(未命中 students 表)→ 原样返回(视为 users.id)', async () => { + expect(await resolveStudentUserId('user-login-id')).toBe('user-login-id') + }) + + it('学生档案存在但缺 user 关联 → 原样返回,不抛错', async () => { + studentRepo.findOne.mockResolvedValue({ id: 'student-row-id', user: null }) + expect(await resolveStudentUserId('student-row-id')).toBe('student-row-id') + }) + + it('空值原样返回', async () => { + expect(await resolveStudentUserId('')).toBe('') + expect(await resolveStudentUserId(null as any)).toBeNull() + expect(studentRepo.findOne).not.toHaveBeenCalled() + }) +}) diff --git a/backend/src/config/redis.ts b/backend/src/config/redis.ts new file mode 100644 index 0000000..266f00f --- /dev/null +++ b/backend/src/config/redis.ts @@ -0,0 +1,34 @@ +/** + * Redis 连接(可选) + * + * REDIS_URL 存在时返回共享 ioredis 连接(供 BullMQ 队列/Worker 使用); + * 未配置时返回 null —— 异步识别任务自动降级为进程内队列,消除同步 HTTP 挂起的 504 风险。 + */ + +import Redis from 'ioredis' + +let connection: Redis | null = null + +export function isRedisEnabled(): boolean { + return !!process.env.REDIS_URL +} + +export function getRedisConnection(): Redis | null { + if (!isRedisEnabled()) return null + if (!connection) { + // maxRetriesPerRequest: null 为 BullMQ 官方要求(避免连接抖动导致任务请求报错) + connection = new Redis(process.env.REDIS_URL as string, { + maxRetriesPerRequest: null, + enableReadyCheck: true, + }) + } + return connection +} + +export async function closeRedisConnection(): Promise { + if (connection) { + const conn = connection + connection = null + await conn.quit().catch(() => conn.disconnect()) + } +} diff --git a/backend/src/constants/errorTags.ts b/backend/src/constants/errorTags.ts new file mode 100644 index 0000000..817c484 --- /dev/null +++ b/backend/src/constants/errorTags.ts @@ -0,0 +1,41 @@ +/** + * 错因标签体系(多维度错因标注) + * + * 预设错因标签:录入与重做流程中可标注,家长端/学生端按此统计错因占比。 + * 为保证画像统计口径一致,后端只接受预设白名单内的标签。 + */ + +export const ERROR_TAG_PRESETS = [ + '审题不清', + '计算粗心', + '公式遗忘', + '方法缺失', + '其他', +] as const + +export type ErrorTag = (typeof ERROR_TAG_PRESETS)[number] + +/** + * 将任意输入(数组或逗号分隔字符串)归一化为合法错因标签数组: + * 去重、去空白、过滤非白名单值,最多保留 10 个。 + */ +export function normalizeErrorTags(input: unknown): string[] { + let raw: string[] = [] + if (Array.isArray(input)) { + raw = input + } else if (typeof input === 'string') { + raw = input.split(',') + } + const cleaned = raw + .filter((t): t is string => typeof t === 'string') + .map((t) => t.trim()) + .filter(Boolean) + return [...new Set(cleaned.filter((t) => (ERROR_TAG_PRESETS as readonly string[]).includes(t)))].slice(0, 10) +} + +/** + * 合并两组错因标签(重做流程追加标注场景):并集、去重、白名单过滤。 + */ +export function mergeErrorTags(existing: unknown, incoming: unknown): string[] { + return normalizeErrorTags([...normalizeErrorTags(existing), ...normalizeErrorTags(incoming)]) +} diff --git a/backend/src/controllers/AuthController.ts b/backend/src/controllers/AuthController.ts index 6be58b0..30b562c 100644 --- a/backend/src/controllers/AuthController.ts +++ b/backend/src/controllers/AuthController.ts @@ -252,9 +252,29 @@ export class AuthController { }) } + // 家长账号:补充绑定学生的档案 id(students.id),供前端以 + // `user?.studentId || user?.id` 统一取值查孩子数据(评审 C1); + // 数据端点均已按 utils/resolveStudentUserId 归一两种 id 口径。 + let studentId = user.studentId + if (user.role === UserRole.PARENT && user.parentId) { + const parent = await this.parentRepository.findOne({ + where: { id: user.parentId }, + relations: ['student'], + }) + if (parent?.student) { + studentId = parent.student.id + } + } + res.json({ status: 'success', - data: user, + data: { + id: user.id, + username: user.username, + role: user.role, + studentId, + parentId: user.parentId, + }, }) } catch (error) { next(error) diff --git a/backend/src/controllers/MasteryController.ts b/backend/src/controllers/MasteryController.ts index 5380d49..2283331 100644 --- a/backend/src/controllers/MasteryController.ts +++ b/backend/src/controllers/MasteryController.ts @@ -15,6 +15,8 @@ import { Request, Response, NextFunction } from 'express' import { AppDataSource } from '../config/database' import { Mastery, MasteryStatus } from '../models/Mastery' +import { resolveStudentUserId } from '../utils/resolveStudentUserId' +import { applyReviewResult, startOfToday, endOfToday } from '../services/ReviewScheduler' /** * 掌握状态控制器类 @@ -154,35 +156,9 @@ export class MasteryController { }) } - // Update mastery based on review result - if (isCorrect) { - mastery.correctCount += 1 - mastery.lastCorrectDate = new Date() - - // Check if mastery condition is met (3 correct in a row with intervals) - if (mastery.correctCount >= 3) { - mastery.status = MasteryStatus.MASTERED - } else { - mastery.status = MasteryStatus.LEARNING - mastery.intervalLevel = Math.min(mastery.correctCount, 3) - } - } else { - mastery.incorrectCount += 1 - mastery.lastIncorrectDate = new Date() - mastery.status = MasteryStatus.LEARNING - mastery.correctCount = 0 - mastery.intervalLevel = 0 - } - - // Calculate next review date based on interval level - const intervals = [1, 7, 30] // days - if (mastery.intervalLevel > 0 && mastery.intervalLevel <= intervals.length) { - const daysToAdd = intervals[mastery.intervalLevel - 1] - mastery.nextReviewDate = new Date() - mastery.nextReviewDate.setDate(mastery.nextReviewDate.getDate() + daysToAdd) - } + // Update mastery based on review result (艾宾浩斯间隔调度:第 1/2/4/7/15 天) + applyReviewResult(mastery, isCorrect) - mastery.lastReviewDate = new Date() await this.masteryRepository.save(mastery) res.json({ @@ -201,9 +177,11 @@ export class MasteryController { ) => { try { const { studentId } = req.params + // 口径归一:接受 students.id 或 users.id(评审 C1) + const resolvedStudentId = await resolveStudentUserId(studentId) const masteryRecords = await this.masteryRepository.find({ - where: { studentId }, + where: { studentId: resolvedStudentId }, relations: ['question'], order: { updatedAt: 'DESC' }, }) @@ -224,18 +202,19 @@ export class MasteryController { ) => { try { const { studentId } = req.params - - const today = new Date() - today.setHours(0, 0, 0, 0) + const resolvedStudentId = await resolveStudentUserId(studentId) const masteryRecords = await this.masteryRepository .createQueryBuilder('mastery') .leftJoinAndSelect('mastery.question', 'question') - .where('mastery.studentId = :studentId', { studentId }) + .where('mastery.studentId = :studentId', { studentId: resolvedStudentId }) .andWhere('mastery.status != :status', { status: MasteryStatus.MASTERED }) .andWhere( - '(mastery.nextReviewDate IS NULL OR mastery.nextReviewDate <= :today)', - { today } + '((mastery.nextReviewDate IS NOT NULL AND mastery.nextReviewDate <= :endOfToday) OR (mastery.nextReviewDate IS NULL AND mastery.createdAt < :startOfToday))', + { + endOfToday: endOfToday(), + startOfToday: startOfToday(), + } ) .orderBy('mastery.nextReviewDate', 'ASC') .getMany() @@ -256,32 +235,47 @@ export class MasteryController { ) => { try { const { studentId } = req.params + const resolvedStudentId = await resolveStudentUserId(studentId) const totalQuestions = await this.masteryRepository.count({ - where: { studentId }, + where: { studentId: resolvedStudentId }, }) const masteredQuestions = await this.masteryRepository.count({ where: { - studentId, + studentId: resolvedStudentId, status: MasteryStatus.MASTERED, }, }) const learningQuestions = await this.masteryRepository.count({ where: { - studentId, + studentId: resolvedStudentId, status: MasteryStatus.LEARNING, }, }) const newQuestions = await this.masteryRepository.count({ where: { - studentId, + studentId: resolvedStudentId, status: MasteryStatus.NEW, }, }) + // 今日待复习:按艾宾浩斯间隔到期的复习数 + const todayDueQuestions = await this.masteryRepository + .createQueryBuilder('mastery') + .where('mastery.studentId = :studentId', { studentId: resolvedStudentId }) + .andWhere('mastery.status != :status', { status: MasteryStatus.MASTERED }) + .andWhere( + '((mastery.nextReviewDate IS NOT NULL AND mastery.nextReviewDate <= :endOfToday) OR (mastery.nextReviewDate IS NULL AND mastery.createdAt < :startOfToday))', + { + endOfToday: endOfToday(), + startOfToday: startOfToday(), + } + ) + .getCount() + res.json({ status: 'success', data: { @@ -289,6 +283,7 @@ export class MasteryController { masteredQuestions, learningQuestions, newQuestions, + todayDueQuestions, masteryRate: totalQuestions > 0 ? Math.round((masteredQuestions / totalQuestions) * 100) diff --git a/backend/src/controllers/QuestionController.ts b/backend/src/controllers/QuestionController.ts index f1b0607..b9760d8 100644 --- a/backend/src/controllers/QuestionController.ts +++ b/backend/src/controllers/QuestionController.ts @@ -18,6 +18,10 @@ import { AppDataSource } from '../config/database' import { Question, Subject, QuestionType } from '../models/Question' import { Mastery, MasteryStatus } from '../models/Mastery' import { LLMService } from '../services/LLMService' +import { normalizeErrorTags, mergeErrorTags } from '../constants/errorTags' +import { processIdentifyMulti } from '../services/tasks/identifyMultiPipeline' +import { identificationTaskManager } from '../services/tasks/IdentificationTaskManager' +import { resolveStudentUserId } from '../utils/resolveStudentUserId' import { v4 as uuidv4 } from 'uuid' /** @@ -122,6 +126,19 @@ export class QuestionController { } } + // 错因标签(多维度错因体系,白名单校验) + // multipart 场景下数组被序列化为 JSON 字符串(如 '["审题不清"]'), + // 先还原再归一,避免被按逗号切分后白名单全滤掉(评审 B2) + let rawErrorTags: unknown = req.body.errorTags + if (typeof rawErrorTags === 'string') { + try { + rawErrorTags = JSON.parse(rawErrorTags) + } catch { + // 非 JSON 字符串:保留原样,normalizeErrorTags 会按逗号切分 + } + } + const errorTags = normalizeErrorTags(rawErrorTags) + // 错题防重排查:根据 studentId + subject + title/content 校验 const cleanContent = (content || title || '').replace(/[^一-龥a-zA-Z0-9]/g, ''); @@ -150,12 +167,13 @@ export class QuestionController { type, difficulty: parseInt(difficulty) || 1, knowledgePoints: parsedKnowledgePoints, + errorTags, imageUrl, answer, explanation, studentId: userId, isIdentified: false, - }) + } as any) await this.questionRepository.save(question) await this.ensureMasteryRecord((question as any).id, userId) @@ -185,6 +203,11 @@ export class QuestionController { }) } + // 错因标签单独校验(白名单),避免任意字段直写 + if ('errorTags' in updateData) { + updateData.errorTags = normalizeErrorTags(updateData.errorTags) + } + // Update question Object.assign(question, updateData) await this.questionRepository.save(question) @@ -198,6 +221,45 @@ export class QuestionController { } } + /** + * 设置错题的错因标签(录入确认/重做后标注错因) + * mode=replace:整组替换;mode=merge:在现有标签上追加(重做流程标注) + */ + setQuestionErrorTags = async ( + req: Request, + res: Response, + next: NextFunction + ) => { + try { + const { id } = req.params + const { tags, mode } = req.body + + const question = await this.questionRepository.findOne({ + where: { id }, + }) + + if (!question) { + return res.status(404).json({ + status: 'error', + message: 'Question not found', + }) + } + + question.errorTags = mode === 'replace' + ? normalizeErrorTags(tags) + : mergeErrorTags(question.errorTags, tags) + + await this.questionRepository.save(question) + + res.json({ + status: 'success', + data: question, + }) + } catch (error) { + next(error) + } + } + deleteQuestion = async (req: Request, res: Response, next: NextFunction) => { try { const { id } = req.params @@ -305,9 +367,11 @@ export class QuestionController { ) => { try { const { studentId } = req.params + // 口径归一:接受 students.id 或 users.id(评审 C1,详见 utils/resolveStudentUserId) + const resolvedStudentId = await resolveStudentUserId(studentId) const questions = await this.questionRepository.find({ - where: { studentId }, + where: { studentId: resolvedStudentId }, order: { createdAt: 'DESC' }, }) @@ -327,7 +391,10 @@ export class QuestionController { const queryBuilder = this.questionRepository.createQueryBuilder('question') if (studentId) { - queryBuilder.where('question.studentId = :studentId', { studentId }) + // 口径归一:接受 students.id 或 users.id(评审 C1) + queryBuilder.where('question.studentId = :studentId', { + studentId: await resolveStudentUserId(studentId as string), + }) } if (subject) { @@ -364,16 +431,18 @@ export class QuestionController { getQuestionStats = async (req: Request, res: Response, next: NextFunction) => { try { const { studentId } = req.params + // 口径归一:接受 students.id 或 users.id(评审 C1) + const resolvedStudentId = await resolveStudentUserId(studentId) const total = await this.questionRepository.count({ - where: { studentId }, + where: { studentId: resolvedStudentId }, }) const bySubject = await this.questionRepository .createQueryBuilder('question') .select('question.subject', 'subject') .addSelect('COUNT(*)', 'count') - .where('question.studentId = :studentId', { studentId }) + .where('question.studentId = :studentId', { studentId: resolvedStudentId }) .groupBy('question.subject') .getRawMany() @@ -381,7 +450,7 @@ export class QuestionController { .createQueryBuilder('question') .select('question.difficulty', 'difficulty') .addSelect('COUNT(*)', 'count') - .where('question.studentId = :studentId', { studentId }) + .where('question.studentId = :studentId', { studentId: resolvedStudentId }) .groupBy('question.difficulty') .getRawMany() @@ -414,68 +483,54 @@ export class QuestionController { const userId = (req as any).user?.id const subject = req.body.subject || Subject.MATH - let llmItems: any[] = [] - try { - const llmResult = await this.llmService.identifyMultiQuestions(req.file.path, userId) - if (Array.isArray(llmResult) && llmResult.length > 0) { - llmItems = llmResult.map((item: any, idx: number) => ({ - tempId: uuidv4(), - title: item.title || `识别题目 ${idx + 1}`, - content: item.content || '', - subject: item.subject || subject, - type: item.type || QuestionType.CHOICE, - answer: item.answer || '', - explanation: item.explanation || '', - isDuplicate: false, - })) - } - } catch (err) { - console.error('LLM identifyMultiQuestions error:', err) - } + // 与异步任务共用同一管道(LLM 识别 → 归一化 → 指纹防重 → 失败兑底 mock) + const { items } = await processIdentifyMulti( + { imagePath: req.file.path, userId, subject }, + () => {} + ) - const mockItems = llmItems.length > 0 ? llmItems : [ - { - tempId: uuidv4(), - title: '识别题目 1', - content: '计算:2 + 3 = ?', - subject: subject, - type: QuestionType.CHOICE, - answer: '5', - explanation: '基础加法运算', - isDuplicate: false, + res.json({ + status: 'success', + data: { + items, }, - { - tempId: uuidv4(), - title: '识别题目 2', - content: '求解方程:x^2 - 4 = 0', - subject: subject, - type: QuestionType.ANSWER, - answer: 'x = ±2', - explanation: '因式分解求解', - isDuplicate: false, - } - ] - - // 计算文本指纹防重逻辑 - for (const item of mockItems) { - const fp = (item.title + item.content).replace(/\s+/g, '').replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '') - if (userId && fp) { - const existingList = await this.questionRepository.find({ where: { studentId: userId, subject: subject as any } }) - const dup = existingList.find(q => { - const qfp = (q.title + q.content).replace(/\s+/g, '').replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '') - return qfp === fp - }) - if (dup) { - item.isDuplicate = true - ;(item as any).existingQuestionId = dup.id - } - } + }) + } catch (error) { + next(error) + } + } + + /** + * 异步提交整页多题识别任务:立即返回 taskId,前端轮询获取进度与结果。 + * 解决整页 Vision 识别同步挂起 15-30s+ 触发 Nginx 504 的问题(见 docs/adr/0004)。 + */ + submitIdentifyMultiTask = async ( + req: Request, + res: Response, + next: NextFunction + ) => { + try { + if (!req.file) { + return res.status(400).json({ + status: 'error', + message: 'Please upload an image', + }) } - res.json({ + const userId = (req as any).user?.id + const subject = req.body.subject || Subject.MATH + + const taskId = await identificationTaskManager.submit({ + imagePath: req.file.path, + userId, + subject, + }) + + res.status(202).json({ status: 'success', data: { - items: mockItems, + taskId, + statusUrl: `/api/questions/identify-multi/tasks/${taskId}`, }, }) } catch (error) { @@ -483,6 +538,38 @@ export class QuestionController { } } + /** + * 查询整页多题识别任务状态/进度/结果(前端轮询入口)。 + */ + getIdentifyMultiTaskStatus = async ( + req: Request, + res: Response, + next: NextFunction + ) => { + try { + const { taskId } = req.params + + // 归属校验(评审建议 S1):非本人提交的任务与不存在同样返回 404 + const task = await identificationTaskManager.getStatus( + taskId, + (req as any).user?.id + ) + if (!task) { + return res.status(404).json({ + status: 'error', + message: 'Task not found or expired', + }) + } + + res.json({ + status: 'success', + data: task, + }) + } catch (error) { + next(error) + } + } + createBatchQuestions = async ( req: Request, res: Response, diff --git a/backend/src/controllers/RedoController.ts b/backend/src/controllers/RedoController.ts index b798573..a796031 100644 --- a/backend/src/controllers/RedoController.ts +++ b/backend/src/controllers/RedoController.ts @@ -16,6 +16,7 @@ import { Request, Response, NextFunction } from 'express' import { AppDataSource } from '../config/database' import { RedoRecord, RedoType } from '../models/RedoRecord' import { LLMService } from '../services/LLMService' +import { applyReviewResult } from '../services/ReviewScheduler' /** * 重做控制器类 @@ -109,7 +110,6 @@ export class RedoController { let isCorrect = false let feedback: string | undefined = undefined let gradeResult: any = undefined - let modelUsed: string | undefined = undefined if (question) { if (question.type === 'answer' || !question.answer) { @@ -146,39 +146,16 @@ export class RedoController { isCorrect, feedback, gradeResult, - modelUsed, }) - // 联动更新 Mastery 状态 + // 联动更新 Mastery 状态(艾宾浩斯间隔调度:第 1/2/4/7/15 天) if (question) { const masteryRepository = AppDataSource.getRepository('Mastery') const mastery = await masteryRepository.findOne({ where: { questionId: question.id, studentId: userId } }) if (mastery) { - if (isCorrect) { - mastery.correctCount += 1 - mastery.lastCorrectDate = new Date() - if (mastery.correctCount >= 3) { - mastery.status = 'mastered' as any - } else { - mastery.status = 'learning' as any - mastery.intervalLevel = Math.min(mastery.correctCount, 3) - } - } else { - mastery.incorrectCount += 1 - mastery.lastIncorrectDate = new Date() - mastery.status = 'learning' as any - mastery.correctCount = 0 - mastery.intervalLevel = 0 - } - const intervals = [1, 7, 30] - if (mastery.intervalLevel > 0 && mastery.intervalLevel <= intervals.length) { - const daysToAdd = intervals[mastery.intervalLevel - 1] - mastery.nextReviewDate = new Date() - mastery.nextReviewDate.setDate(mastery.nextReviewDate.getDate() + daysToAdd) - } - mastery.lastReviewDate = new Date() + applyReviewResult(mastery as any, isCorrect) await masteryRepository.save(mastery) } } diff --git a/backend/src/controllers/ReportController.ts b/backend/src/controllers/ReportController.ts index 21bfd69..d6888c5 100644 --- a/backend/src/controllers/ReportController.ts +++ b/backend/src/controllers/ReportController.ts @@ -18,7 +18,9 @@ import { WeeklyReport } from '../models/WeeklyReport' import { Question } from '../models/Question' import { RedoRecord } from '../models/RedoRecord' import { Mastery, MasteryStatus } from '../models/Mastery' +import { resolveStudentUserId } from '../utils/resolveStudentUserId' import { SimilarQuestion } from '../models/SimilarQuestion' +import { ErrorProfileService } from '../services/ErrorProfileService' /** * 报告控制器类 @@ -133,6 +135,30 @@ export class ReportController { } } + /** + * 薄弱点画像:错因占比 + 薄弱知识点(学生/家长共用) + */ + getErrorProfile = async ( + req: Request, + res: Response, + next: NextFunction + ) => { + try { + const { studentId } = req.params + // 口径归一:接受 students.id 或 users.id(评审 C1) + const resolvedStudentId = await resolveStudentUserId(studentId) + + const profile = await new ErrorProfileService().getErrorProfile(resolvedStudentId) + + res.json({ + status: 'success', + data: profile, + }) + } catch (error) { + next(error) + } + } + getDailyReport = async ( req: Request, res: Response, @@ -140,6 +166,7 @@ export class ReportController { ) => { try { const { studentId } = req.params + const resolvedStudentId = await resolveStudentUserId(studentId) const today = new Date() today.setHours(0, 0, 0, 0) @@ -150,7 +177,7 @@ export class ReportController { // Get today's questions const questions = await this.questionRepository.find({ where: { - studentId, + studentId: resolvedStudentId, createdAt: { $gte: today, $lt: tomorrow, @@ -161,7 +188,7 @@ export class ReportController { // Get today's redos const redos = await this.redoRepository.find({ where: { - studentId, + studentId: resolvedStudentId, createdAt: { $gte: today, $lt: tomorrow, @@ -172,7 +199,7 @@ export class ReportController { // Get mastery stats const masteryStats = await this.masteryRepository .createQueryBuilder('mastery') - .where('mastery.studentId = :studentId', { studentId }) + .where('mastery.studentId = :studentId', { studentId: resolvedStudentId }) .getMany() const masteredCount = masteryStats.filter( diff --git a/backend/src/index.ts b/backend/src/index.ts index ba25b56..bdd4494 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -8,6 +8,7 @@ import dotenv from 'dotenv' import { connectDatabase } from './config/database' import { errorHandler } from './middleware/errorHandler' import { notFound } from './middleware/notFound' +import { identificationTaskManager } from './services/tasks/IdentificationTaskManager' // Routes import authRoutes from './routes/auth' @@ -76,6 +77,8 @@ app.use(errorHandler) const startServer = async () => { try { await connectDatabase() + // 启动整页多题识别异步任务队列(REDIS_URL 未配置时自动降级为进程内队列) + identificationTaskManager.init() app.listen(PORT, () => { console.log(`Server running on port ${PORT}`) console.log(`Environment: ${process.env.NODE_ENV || 'development'}`) @@ -86,6 +89,19 @@ const startServer = async () => { } } +// 优雅关闭:等待识别队列中的任务收尾 +const shutdown = async (signal: string) => { + console.log(`Received ${signal}, shutting down...`) + try { + await identificationTaskManager.close() + } catch (e) { + console.error('Error during task manager shutdown:', e) + } + process.exit(0) +} +process.on('SIGTERM', () => shutdown('SIGTERM')) +process.on('SIGINT', () => shutdown('SIGINT')) + startServer() export default app \ No newline at end of file diff --git a/database/migrations/1720000000000-InitMasteryRecords.ts b/backend/src/migrations/1720000000000-InitMasteryRecords.ts similarity index 100% rename from database/migrations/1720000000000-InitMasteryRecords.ts rename to backend/src/migrations/1720000000000-InitMasteryRecords.ts diff --git a/database/migrations/1730000000000-AddMultiRecognitionScene.ts b/backend/src/migrations/1730000000000-AddMultiRecognitionScene.ts similarity index 100% rename from database/migrations/1730000000000-AddMultiRecognitionScene.ts rename to backend/src/migrations/1730000000000-AddMultiRecognitionScene.ts diff --git a/backend/src/migrations/1740000000000-AddDiagramUrlsToQuestions.ts b/backend/src/migrations/1740000000000-AddDiagramUrlsToQuestions.ts new file mode 100644 index 0000000..f3d51d3 --- /dev/null +++ b/backend/src/migrations/1740000000000-AddDiagramUrlsToQuestions.ts @@ -0,0 +1,23 @@ +import { MigrationInterface, QueryRunner } from 'typeorm' + +/** + * questions 增加裁剪插图列 diagramUrls(ADR 0003:干净的题目插图,不含手写答案)。 + * + * 说明:ADD COLUMN IF NOT EXISTS(MariaDB 10.2+)保证幂等——生产库当年该列系 + * 迁移链外手工外加,收敛进正式迁移链后首次执行不会撞 duplicate column。 + */ +export class AddDiagramUrlsToQuestions1740000000000 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE questions + ADD COLUMN IF NOT EXISTS diagramUrls JSON NULL AFTER imageUrl; + `) + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE questions + DROP COLUMN IF EXISTS diagramUrls; + `) + } +} diff --git a/backend/src/migrations/1750000000000-AddErrorTagsToQuestions.ts b/backend/src/migrations/1750000000000-AddErrorTagsToQuestions.ts new file mode 100644 index 0000000..2e8a85c --- /dev/null +++ b/backend/src/migrations/1750000000000-AddErrorTagsToQuestions.ts @@ -0,0 +1,27 @@ +import { MigrationInterface, QueryRunner } from 'typeorm' + +/** + * 错题增加错因标签列(多维度错因体系)。 + * + * 说明:MariaDB 10.2+ 支持 ADD COLUMN IF NOT EXISTS,保证幂等—— + * 无论是通过 `npm run migrate`(TypeORM 迁移表记录)还是手工执行, + * 重复应用都不会报 duplicate column 错误。不指定 AFTER:列位置纯装饰, + * 且避免依赖迁移链中未必存在的列(评审 B1)。 + */ +export class AddErrorTagsToQuestions1750000000000 implements MigrationInterface { + name = 'AddErrorTagsToQuestions1750000000000' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE questions + ADD COLUMN IF NOT EXISTS errorTags JSON NULL; + `) + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE questions + DROP COLUMN IF EXISTS errorTags; + `) + } +} diff --git a/backend/src/models/Question.ts b/backend/src/models/Question.ts index 0d87758..9085f95 100644 --- a/backend/src/models/Question.ts +++ b/backend/src/models/Question.ts @@ -60,6 +60,9 @@ export class Question { @Column('json', { nullable: true }) diagramUrls: string[] + @Column('json', { nullable: true }) + errorTags: string[] + @Column({ nullable: true }) originalImageUrl: string diff --git a/backend/src/routes/questions.ts b/backend/src/routes/questions.ts index 098de8d..5d04851 100644 --- a/backend/src/routes/questions.ts +++ b/backend/src/routes/questions.ts @@ -53,8 +53,22 @@ router.post( questionController.identifyMultiQuestions ) +// 异步整页识别:立即返回 taskId,前端轮询 /identify-multi/tasks/:taskId +router.post( + '/identify-multi/async', + upload.single('image'), + questionController.submitIdentifyMultiTask +) +router.get( + '/identify-multi/tasks/:taskId', + questionController.getIdentifyMultiTaskStatus +) + router.post('/batch', questionController.createBatchQuestions) +// 错因标签标注(录入确认/重做后追加) +router.put('/:id/error-tags', questionController.setQuestionErrorTags) + // Student-specific routes router.get( '/student/:studentId', diff --git a/backend/src/routes/reports.ts b/backend/src/routes/reports.ts index 49f97a9..2cdd683 100644 --- a/backend/src/routes/reports.ts +++ b/backend/src/routes/reports.ts @@ -13,6 +13,9 @@ router.get('/weekly/:userId', reportController.getWeeklyReportByUser) router.get('/stats', reportController.getStats) router.get('/stats/:userId', reportController.getStatsByUser) +// 薄弱点画像(错因占比 + 薄弱知识点,学生/家长共用) +router.get('/error-profile/:studentId', reportController.getErrorProfile) + // Student-specific routes router.get('/student/:studentId/daily', reportController.getDailyReport) router.get('/student/:studentId/weekly', reportController.getWeeklyReportByStudent) diff --git a/backend/src/services/ErrorProfileService.ts b/backend/src/services/ErrorProfileService.ts new file mode 100644 index 0000000..b4fd83f --- /dev/null +++ b/backend/src/services/ErrorProfileService.ts @@ -0,0 +1,106 @@ +/** + * 薄弱点画像服务 + * + * 聚合两类可视化数据(学生端/家长端共用,移动端友好): + * - 错因占比:错题的 errorTags(错因标签)分布; + * - 薄弱知识点画像:错题知识点 × 掌握记录错误次数的加权分布。 + */ + +import { AppDataSource } from '../config/database' +import { Question } from '../models/Question' +import { Mastery } from '../models/Mastery' + +export interface ErrorTagSlice { + tag: string + count: number +} + +export interface WeakKnowledgePoint { + point: string + /** 涉及的错题数(该知识点下有错误记录的题目数) */ + questionCount: number + /** 累计做错次数 */ + incorrectCount: number + /** 该知识点下题目总数 */ + totalQuestions: number +} + +export interface ErrorProfile { + totalQuestions: number + /** 已标注错因的题目数 */ + taggedQuestions: number + errorTagDistribution: ErrorTagSlice[] + weakKnowledgePoints: WeakKnowledgePoint[] +} + +export class ErrorProfileService { + private questionRepository = AppDataSource.getRepository(Question) + private masteryRepository = AppDataSource.getRepository(Mastery) + + async getErrorProfile(studentId: string): Promise { + const [questions, masteries] = await Promise.all([ + this.questionRepository.find({ where: { studentId } }), + this.masteryRepository.find({ + where: { studentId }, + relations: ['question'], + }), + ]) + + // ---- 错因占比 ---- + const tagCount = new Map() + let taggedQuestions = 0 + for (const q of questions) { + const tags = Array.isArray(q.errorTags) ? q.errorTags : [] + if (tags.length > 0) taggedQuestions += 1 + for (const t of tags) { + tagCount.set(t, (tagCount.get(t) || 0) + 1) + } + } + const errorTagDistribution: ErrorTagSlice[] = [...tagCount.entries()] + .map(([tag, count]) => ({ tag, count })) + .sort((a, b) => b.count - a.count) + + // ---- 薄弱知识点画像(有错误记录的题目按知识点聚合) ---- + const kpAgg = new Map() + for (const m of masteries) { + if (!(m.incorrectCount > 0)) continue + const kps = Array.isArray(m.question?.knowledgePoints) + ? (m.question!.knowledgePoints as string[]) + : [] + for (const kp of kps) { + const entry = kpAgg.get(kp) || { + point: kp, + questionCount: 0, + incorrectCount: 0, + totalQuestions: 0, + } + entry.questionCount += 1 + entry.incorrectCount += m.incorrectCount + kpAgg.set(kp, entry) + } + } + + // 每个知识点下的题目总数(含未出错的),用于画像比率 + for (const q of questions) { + const kps = Array.isArray(q.knowledgePoints) ? q.knowledgePoints : [] + for (const kp of kps) { + const entry = kpAgg.get(kp) + if (entry) entry.totalQuestions += 1 + } + } + + const weakKnowledgePoints: WeakKnowledgePoint[] = [...kpAgg.values()] + .sort( + (a, b) => + b.incorrectCount - a.incorrectCount || b.questionCount - a.questionCount + ) + .slice(0, 20) + + return { + totalQuestions: questions.length, + taggedQuestions, + errorTagDistribution, + weakKnowledgePoints, + } + } +} diff --git a/backend/src/services/LearningService.ts b/backend/src/services/LearningService.ts index 5b04bc2..2d8f599 100644 --- a/backend/src/services/LearningService.ts +++ b/backend/src/services/LearningService.ts @@ -3,6 +3,7 @@ import { Question } from '../models/Question' import { Mastery, MasteryStatus } from '../models/Mastery' import { RedoRecord } from '../models/RedoRecord' import { SimilarQuestion } from '../models/SimilarQuestion' +import { startOfToday, endOfToday } from './ReviewScheduler' export class LearningService { private questionRepository = AppDataSource.getRepository(Question) @@ -27,13 +28,20 @@ export class LearningService { .andWhere('mastery.createdAt < :tomorrow', { tomorrow }) .getMany() - // Get questions that need review (due for review) + // Get questions that need review (due for review,艾宾浩斯间隔到期) + // 排除当天新录入(仍在 newQuestions 中);历史遗留的未安排记录(nextReviewDate 为空且非今日创建)也算到期 const reviewQuestions = await this.masteryRepository .createQueryBuilder('mastery') .leftJoinAndSelect('mastery.question', 'question') .where('mastery.studentId = :studentId', { studentId }) .andWhere('mastery.status != :status', { status: MasteryStatus.MASTERED }) - .andWhere('(mastery.nextReviewDate IS NULL OR mastery.nextReviewDate <= :today)', { today }) + .andWhere( + '((mastery.nextReviewDate IS NOT NULL AND mastery.nextReviewDate <= :endOfToday) OR (mastery.nextReviewDate IS NULL AND mastery.createdAt < :startOfToday))', + { + endOfToday: endOfToday(today), + startOfToday: startOfToday(today), + } + ) .orderBy('mastery.nextReviewDate', 'ASC') .getMany() diff --git a/backend/src/services/ReviewScheduler.ts b/backend/src/services/ReviewScheduler.ts new file mode 100644 index 0000000..82f4f13 --- /dev/null +++ b/backend/src/services/ReviewScheduler.ts @@ -0,0 +1,106 @@ +/** + * 艾宾浩斯间隔复习调度器 + * + * 用动态间隔(第 1/2/4/7/15 天)替代旧的固定间隔(1/7/30 天)与固定重做次数逻辑: + * - 每次复习做对,复习轮次(intervalLevel)前进一格,下次复习日期按艾宾浩斯间隔表顺延; + * - 走完 5 个间隔(共 5 次间隔复习全部做对)即判定「已掌握」; + * - 任一次复习做错,轮次归零,1 天后重新开始; + * - 新错题录入后 nextReviewDate 为空,进入「新错题」队列,可当天重做; + * 首次做对后进入间隔复习调度。 + * + * 该模块是纯逻辑(不触库),供 MasteryController(独立复习打卡)与 + * RedoController(重做联动)共用,保证两处调度行为一致。 + */ + +import { Mastery, MasteryStatus } from '../models/Mastery' + +/** 艾宾浩斯复习间隔(天):第 1/2/4/7/15 天 */ +export const EBBINGHAUS_INTERVALS = [1, 2, 4, 7, 15] + +/** 走完全部间隔所需的复习轮次(完成第 5 轮即 15 天间隔复习) */ +export const EBBINGHAUS_TOTAL_RUNGS = EBBINGHAUS_INTERVALS.length + +/** 掌握阈值:intervalLevel 达到「轮次数 + 1」表示第 5 轮(15 天间隔)复习已做对 */ +export const EBBINGHAUS_MASTERY_LEVEL = EBBINGHAUS_TOTAL_RUNGS + 1 + +export function addDays(base: Date, days: number): Date { + const d = new Date(base.getTime()) + d.setDate(d.getDate() + days) + return d +} + +/** 当天 00:00:00.000 */ +export function startOfToday(now: Date = new Date()): Date { + return new Date(now.getFullYear(), now.getMonth(), now.getDate()) +} + +/** 当天 23:59:59.999 */ +export function endOfToday(now: Date = new Date()): Date { + const d = startOfToday(now) + d.setDate(d.getDate() + 1) + return new Date(d.getTime() - 1) +} + +/** + * 判定一条掌握记录的复习是否到期(今日待复习)。 + * - 有 nextReviewDate:到期日 <= 今天结束(23:59:59.999)即到期; + * - 无 nextReviewDate 的历史遗留记录(录入后从未安排):创建日早于今天即到期, + * 当天新录入的仍留在「新错题」队列。 + */ +export function isReviewDue(mastery: { + status: MasteryStatus + nextReviewDate?: Date | null + createdAt?: Date | null +}, now: Date = new Date()): boolean { + if (mastery.status === MasteryStatus.MASTERED) return false + if (mastery.nextReviewDate) { + return new Date(mastery.nextReviewDate).getTime() <= endOfToday(now).getTime() + } + return !!mastery.createdAt && new Date(mastery.createdAt).getTime() < startOfToday(now).getTime() +} + +/** + * 将一次复习结果应用到掌握记录上(原地修改),并返回该记录。 + * + * 调度语义(与需求书掌握状态机同构,间隔替换为艾宾浩斯 1/2/4/7/15 天): + * - intervalLevel 表示「即将到来的间隔复习轮次」:录入后首次做对 → 1(1 天后第 1 轮); + * 第 k 轮复习做对 → k+1(再隔 intervals[k] 天进入第 k+1 轮); + * - 第 5 轮(15 天间隔)复习做对 → intervalLevel = 6 → 已掌握; + * - 任一次复习做错 → 轮次归零,1 天后重新开始。 + * + * @param mastery 掌握记录实体 + * @param isCorrect 本次复习/重做是否做对 + * @param now 复习发生时间(默认当前时间) + */ +export function applyReviewResult( + mastery: Mastery, + isCorrect: boolean, + now: Date = new Date() +): Mastery { + mastery.lastReviewDate = now + + if (isCorrect) { + mastery.correctCount += 1 + mastery.lastCorrectDate = now + mastery.intervalLevel = Math.min((mastery.intervalLevel || 0) + 1, EBBINGHAUS_MASTERY_LEVEL) + + if (mastery.intervalLevel >= EBBINGHAUS_MASTERY_LEVEL) { + // 走完第 5 轮(15 天间隔)复习并做对 → 已掌握 + mastery.status = MasteryStatus.MASTERED + mastery.nextReviewDate = null + } else { + mastery.status = MasteryStatus.LEARNING + mastery.nextReviewDate = addDays(now, EBBINGHAUS_INTERVALS[mastery.intervalLevel - 1]) + } + } else { + mastery.incorrectCount += 1 + mastery.lastIncorrectDate = now + mastery.status = MasteryStatus.LEARNING + mastery.correctCount = 0 + mastery.intervalLevel = 0 + // 做错后 1 天后重新开始间隔复习 + mastery.nextReviewDate = addDays(now, EBBINGHAUS_INTERVALS[0]) + } + + return mastery +} diff --git a/backend/src/services/tasks/IdentificationTaskManager.ts b/backend/src/services/tasks/IdentificationTaskManager.ts new file mode 100644 index 0000000..b19e8a4 --- /dev/null +++ b/backend/src/services/tasks/IdentificationTaskManager.ts @@ -0,0 +1,190 @@ +/** + * 整页多题识别任务管理器 + * + * 双后端设计(默认 Redis + BullMQ,见 docs/adr/0004): + * - REDIS_URL 已配置:BullMQ 队列 + 进程内 Worker(并发 1),任务状态/进度/结果存 Redis, + * 重启不丢任务,removeOnComplete 保留 1 小时供轮询; + * - REDIS_URL 未配置:自动降级为进程内队列(内存 Map + 串行异步执行), + * 接口行为完全一致,同样立即返回 taskId,消除同步 HTTP 挂起的 504 风险; + * 局限:任务不跨进程重启保留(自托管单实例场景可接受,PR/ADR 已注明)。 + */ + +import { Queue, Worker, type Job } from 'bullmq' +import { v4 as uuidv4 } from 'uuid' +import { getRedisConnection, closeRedisConnection } from '../../config/redis' +import { + processIdentifyMulti, + type IdentifyMultiJobData, + type MultiRecognizeItem, +} from './identifyMultiPipeline' + +export type TaskState = 'queued' | 'processing' | 'completed' | 'failed' + +export interface TaskStatus { + taskId: string + state: TaskState + progress: number + result?: { items: MultiRecognizeItem[] } + error?: string +} + +interface MemoryTask extends TaskStatus { + createdAt: number + /** 提交者 users.id,用于归属校验(评审建议 S1) */ + userId?: string +} + +/** 完成任务保留时长(供前端轮询),之后清理 */ +const TASK_RETENTION_MS = 60 * 60 * 1000 + +const QUEUE_NAME = 'identify-multi' + +class IdentificationTaskManager { + private queue: Queue | null = null + private worker: Worker | null = null + private memoryTasks = new Map() + private memoryChain: Promise = Promise.resolve() + private initialized = false + + /** 初始化队列后端(幂等;进程启动或首次 submit 时调用) */ + init(): void { + if (this.initialized) return + this.initialized = true + + const connection = getRedisConnection() + if (!connection) { + console.log( + '[IdentificationTaskManager] REDIS_URL 未配置,使用进程内队列(单实例,重启不保留任务)' + ) + return + } + + console.log('[IdentificationTaskManager] 使用 Redis + BullMQ 队列') + this.queue = new Queue(QUEUE_NAME, { connection }) + this.worker = new Worker( + QUEUE_NAME, + async (job: Job) => + processIdentifyMulti(job.data, (p) => job.updateProgress(p)), + { connection, concurrency: 1 } + ) + this.worker.on('failed', (job, err) => { + console.error(`[IdentificationTaskManager] 任务 ${job?.id} 失败:`, err?.message) + }) + } + + /** 提交识别任务,立即返回 taskId(不等待 LLM 完成) */ + async submit(data: IdentifyMultiJobData): Promise { + this.init() + + if (this.queue) { + const job = await this.queue.add(QUEUE_NAME, data, { + attempts: 1, + removeOnComplete: { age: TASK_RETENTION_MS, count: 500 }, + removeOnFail: { age: TASK_RETENTION_MS, count: 500 }, + }) + return job.id as string + } + + // 进程内队列:串行执行,避免并发 Vision 调用打爆上游配额 + const taskId = uuidv4() + this.memoryTasks.set(taskId, { + taskId, + state: 'queued', + progress: 0, + createdAt: Date.now(), + userId: data.userId, + }) + this.memoryChain = this.memoryChain + .then(() => this.runMemoryTask(taskId, data)) + .catch(() => {}) + return taskId + } + + private async runMemoryTask(taskId: string, data: IdentifyMultiJobData): Promise { + const task = this.memoryTasks.get(taskId) + if (!task) return + task.state = 'processing' + task.progress = 5 + try { + const result = await processIdentifyMulti(data, (p) => { + task.progress = Math.max(task.progress, p) + }) + task.state = 'completed' + task.progress = 100 + task.result = result + } catch (err: any) { + task.state = 'failed' + task.error = err?.message || '识别任务执行失败' + } finally { + setTimeout(() => this.memoryTasks.delete(taskId), TASK_RETENTION_MS).unref?.() + } + } + + /** + * 查询任务状态;不存在(或已过期清理)返回 null。 + * 传入 viewerUserId 时校验归属:非本人提交的任务同样返回 null(评审建议 S1, + * 避免已登录用户枚举他人 taskId 读取识别内容)。 + */ + async getStatus(taskId: string, viewerUserId?: string): Promise { + this.init() + + if (this.queue) { + const job = await this.queue.getJob(taskId) + if (!job) return null + if (viewerUserId && job.data?.userId && job.data.userId !== viewerUserId) { + return null + } + const bullState = await job.getState() + const stateMap: Record = { + waiting: 'queued', + delayed: 'queued', + active: 'processing', + completed: 'completed', + failed: 'failed', + } + const state = stateMap[bullState] || 'queued' + const progress = typeof job.progress === 'number' ? job.progress : 0 + return { + taskId, + state, + progress: state === 'completed' ? 100 : progress, + result: state === 'completed' ? (job.returnvalue as any) : undefined, + error: state === 'failed' ? job.failedReason : undefined, + } + } + + const task = this.memoryTasks.get(taskId) + if (!task) return null + if (viewerUserId && task.userId && task.userId !== viewerUserId) { + return null + } + return { + taskId: task.taskId, + state: task.state, + progress: task.progress, + result: task.result, + error: task.error, + } + } + + /** 当前是否为 Redis 后端(测试/诊断用) */ + isRedisBacked(): boolean { + return this.queue !== null + } + + /** 优雅关闭(SIGTERM/SIGINT) */ + async close(): Promise { + if (this.worker) { + await this.worker.close().catch(() => {}) + this.worker = null + } + if (this.queue) { + await this.queue.close().catch(() => {}) + this.queue = null + } + this.initialized = false + await closeRedisConnection() + } +} + +export const identificationTaskManager = new IdentificationTaskManager() diff --git a/backend/src/services/tasks/identifyMultiPipeline.ts b/backend/src/services/tasks/identifyMultiPipeline.ts new file mode 100644 index 0000000..1d16566 --- /dev/null +++ b/backend/src/services/tasks/identifyMultiPipeline.ts @@ -0,0 +1,131 @@ +/** + * 整页多题识别任务管道(异步化核心逻辑) + * + * 从 QuestionController.identifyMultiQuestions 提取,供以下两条路径共用: + * - 异步任务(BullMQ Worker / 进程内队列 Worker); + * - 同步 HTTP 接口(兼容保留)。 + * + * 处理步骤:Vision LLM 切题识别 → 结果归一化 → 文本指纹防重标记 → 失败兜底 mock 题。 + */ + +import { AppDataSource } from '../../config/database' +import { Question, Subject, QuestionType } from '../../models/Question' +import { LLMService } from '../LLMService' +import { v4 as uuidv4 } from 'uuid' + +export interface IdentifyMultiJobData { + imagePath: string + userId: string + subject?: string +} + +export interface MultiRecognizeItem { + tempId: string + title: string + content: string + subject: string + type: string + answer: string + explanation: string + isDuplicate: boolean + existingQuestionId?: string +} + +export type ProgressFn = (progress: number) => void | Promise + +const MOCK_ITEMS = (subject: string): Omit[] => [ + { + title: '识别题目 1', + content: '计算:2 + 3 = ?', + subject, + type: QuestionType.CHOICE, + answer: '5', + explanation: '基础加法运算', + isDuplicate: false, + }, + { + title: '识别题目 2', + content: '求解方程:x^2 - 4 = 0', + subject, + type: QuestionType.ANSWER, + answer: 'x = ±2', + explanation: '因式分解求解', + isDuplicate: false, + }, +] + +/** 文本指纹:去除空白与标点,仅保留中英文数字 */ +export function textFingerprint(title: string, content: string): string { + return (title + content) + .replace(/\s+/g, '') + .replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '') +} + +/** + * 执行整页多题识别:调用 Vision LLM,归一化条目,并按文本指纹标记重复。 + * LLM 不可用/失败时回退到内置 mock 条目(与原同步接口行为一致)。 + */ +export async function processIdentifyMulti( + data: IdentifyMultiJobData, + onProgress: ProgressFn = () => {} +): Promise<{ items: MultiRecognizeItem[] }> { + const subject = data.subject || Subject.MATH + const userId = data.userId + + let llmItems: any[] = [] + try { + await onProgress(10) + const llmService = new LLMService() + const llmResult = await llmService.identifyMultiQuestions(data.imagePath, userId) + if (Array.isArray(llmResult) && llmResult.length > 0) { + llmItems = llmResult.map((item: any, idx: number) => ({ + tempId: uuidv4(), + title: item.title || `识别题目 ${idx + 1}`, + content: item.content || '', + subject: item.subject || subject, + type: item.type || QuestionType.CHOICE, + answer: item.answer || '', + explanation: item.explanation || '', + isDuplicate: false, + })) + } + } catch (err) { + console.error('LLM identifyMultiQuestions error:', err) + } + + const rawItems = llmItems.length > 0 + ? llmItems + : MOCK_ITEMS(subject).map((item) => ({ ...item, tempId: uuidv4() })) + + await onProgress(55) + + // 文本指纹防重标记 + try { + const questionRepository = AppDataSource.getRepository(Question) + const existingList = userId + ? await questionRepository.find({ + where: { studentId: userId, subject: subject as any }, + }) + : [] + const existingFps = existingList.map((q) => textFingerprint(q.title || '', q.content || '')) + + for (const item of rawItems) { + const fp = textFingerprint(item.title, item.content) + if (userId && fp) { + // 与原同步接口一致的精确指纹匹配 + const dupIndex = existingFps.findIndex((qfp) => qfp === fp) + if (dupIndex !== -1) { + item.isDuplicate = true + item.existingQuestionId = existingList[dupIndex].id + } + } + } + } catch (err) { + console.error('Duplicate fingerprint check error:', err) + throw err + } + + await onProgress(90) + + return { items: rawItems } +} diff --git a/backend/src/utils/resolveStudentUserId.ts b/backend/src/utils/resolveStudentUserId.ts new file mode 100644 index 0000000..f2ac55a --- /dev/null +++ b/backend/src/utils/resolveStudentUserId.ts @@ -0,0 +1,24 @@ +import { AppDataSource } from '../config/database' +import { Student } from '../models/Student' + +/** + * studentId 口径统一工具(评审 C1)。 + * + * 背景:数据行(questions / mastery / redo_records.studentId)写入的是登录用户 id + * (users.id,录入时取 req.user.id),而 users.studentId 字段与家长绑定关系暴露的 + * 是学生档案 id(students.id)。前端统一以 `user?.studentId || user?.id` 取值: + * 登录后刷新(fetchUser 返回 students.id)或家长视角(绑定学生的 students.id)时, + * 直查会导致恒为空。 + * + * 归一策略:入参若命中 students.id 则解析为其登录用户 id(users.id);否则视为 + * 已是 users.id 原样返回。两种口径从此等价,调用方无需区分。 + */ +export async function resolveStudentUserId(rawId: string | undefined | null): Promise { + if (!rawId) return rawId as string + + const student = await AppDataSource.getRepository(Student).findOne({ + where: { id: rawId }, + relations: ['user'], + }) + return student?.user?.id || rawId +} diff --git a/database/migrations/1710000000000-InitialSchema.ts b/database/migrations/1710000000000-InitialSchema.ts deleted file mode 100644 index 569b317..0000000 --- a/database/migrations/1710000000000-InitialSchema.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { MigrationInterface, QueryRunner } from 'typeorm' - -export class InitialSchema1710000000000 implements MigrationInterface { - name = 'InitialSchema1710000000000' - - public async up(queryRunner: QueryRunner): Promise { - // Create users table - await queryRunner.query(` - CREATE TABLE users ( - id VARCHAR(36) PRIMARY KEY, - username VARCHAR(255) UNIQUE NOT NULL, - password VARCHAR(255) NOT NULL, - role ENUM('student', 'parent', 'admin') DEFAULT 'student', - studentId VARCHAR(36), - parentId VARCHAR(36), - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP - ) - `) - - // Create students table - await queryRunner.query(` - CREATE TABLE students ( - id VARCHAR(36) PRIMARY KEY, - name VARCHAR(255) NOT NULL, - grade VARCHAR(50), - school VARCHAR(255), - userId VARCHAR(36), - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - FOREIGN KEY (userId) REFERENCES users(id) ON DELETE SET NULL - ) - `) - - // Create parents table - await queryRunner.query(` - CREATE TABLE parents ( - id VARCHAR(36) PRIMARY KEY, - name VARCHAR(255) NOT NULL, - phone VARCHAR(20), - email VARCHAR(255), - userId VARCHAR(36), - studentId VARCHAR(36), - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - FOREIGN KEY (userId) REFERENCES users(id) ON DELETE SET NULL, - FOREIGN KEY (studentId) REFERENCES students(id) ON DELETE SET NULL - ) - `) - - // Create questions table - await queryRunner.query(` - CREATE TABLE questions ( - id VARCHAR(36) PRIMARY KEY, - title VARCHAR(255) NOT NULL, - content TEXT NOT NULL, - subject ENUM('math', 'physics', 'chemistry') NOT NULL, - type ENUM('choice', 'fill', 'answer') NOT NULL, - difficulty INT DEFAULT 1, - knowledgePoints JSON, - imageUrl VARCHAR(500), - originalImageUrl VARCHAR(500), - answer TEXT, - explanation TEXT, - isIdentified BOOLEAN DEFAULT FALSE, - confidence DECIMAL(3,2), - studentId VARCHAR(36) NOT NULL, - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - FOREIGN KEY (studentId) REFERENCES users(id) ON DELETE CASCADE - ) - `) - - // Create redo_records table - await queryRunner.query(` - CREATE TABLE redo_records ( - id VARCHAR(36) PRIMARY KEY, - type ENUM('online', 'photo') NOT NULL, - answer TEXT NOT NULL, - isCorrect BOOLEAN DEFAULT FALSE, - gradeResult TEXT, - modelUsed VARCHAR(100), - feedback TEXT, - questionId VARCHAR(36) NOT NULL, - studentId VARCHAR(36) NOT NULL, - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (questionId) REFERENCES questions(id) ON DELETE CASCADE, - FOREIGN KEY (studentId) REFERENCES users(id) ON DELETE CASCADE - ) - `) - - // Create mastery table - await queryRunner.query(` - CREATE TABLE mastery ( - id VARCHAR(36) PRIMARY KEY, - status ENUM('new', 'learning', 'mastered') DEFAULT 'new', - correctCount INT DEFAULT 0, - incorrectCount INT DEFAULT 0, - lastCorrectDate TIMESTAMP NULL, - lastIncorrectDate TIMESTAMP NULL, - nextReviewDate TIMESTAMP NULL, - intervalLevel INT DEFAULT 0, - lastReviewDate TIMESTAMP NULL, - questionId VARCHAR(36) NOT NULL, - studentId VARCHAR(36) NOT NULL, - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - FOREIGN KEY (questionId) REFERENCES questions(id) ON DELETE CASCADE, - FOREIGN KEY (studentId) REFERENCES users(id) ON DELETE CASCADE, - UNIQUE KEY unique_question_student (questionId, studentId) - ) - `) - - // Create similar_questions table - await queryRunner.query(` - CREATE TABLE similar_questions ( - id VARCHAR(36) PRIMARY KEY, - content TEXT NOT NULL, - isApplicable BOOLEAN DEFAULT TRUE, - reason TEXT, - originalQuestionId VARCHAR(36) NOT NULL, - generatedBy VARCHAR(100), - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (originalQuestionId) REFERENCES questions(id) ON DELETE CASCADE - ) - `) - - // Create llm_usage table - await queryRunner.query(` - CREATE TABLE llm_usage ( - id VARCHAR(36) PRIMARY KEY, - scene ENUM('recognition', 'grading', 'guidance', 'similar', 'other') NOT NULL, - provider VARCHAR(50) NOT NULL, - model VARCHAR(100) NOT NULL, - isFallback BOOLEAN DEFAULT FALSE, - tokensInput INT DEFAULT 0, - tokensOutput INT DEFAULT 0, - tokensTotal INT DEFAULT 0, - cost DECIMAL(10,6) DEFAULT 0, - latencyMs INT DEFAULT 0, - success BOOLEAN DEFAULT TRUE, - error TEXT, - businessId VARCHAR(36), - userId VARCHAR(36) NOT NULL, - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE - ) - `) - - // Create notifications table - await queryRunner.query(` - CREATE TABLE notifications ( - id VARCHAR(36) PRIMARY KEY, - type ENUM('weekly_report', 'similar_question', 'system') NOT NULL, - title VARCHAR(255) NOT NULL, - content TEXT NOT NULL, - isRead BOOLEAN DEFAULT FALSE, - userId VARCHAR(36) NOT NULL, - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE - ) - `) - - // Create weekly_reports table - await queryRunner.query(` - CREATE TABLE weekly_reports ( - id VARCHAR(36) PRIMARY KEY, - weekStart TIMESTAMP NOT NULL, - weekEnd TIMESTAMP NOT NULL, - weakPoints JSON, - totalQuestions INT DEFAULT 0, - masteredQuestions INT DEFAULT 0, - similarQuestionsGenerated INT DEFAULT 0, - totalRedos INT DEFAULT 0, - masteryRate DECIMAL(5,2) DEFAULT 0, - userId VARCHAR(36) NOT NULL, - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE - ) - `) - - // Create sys_config table - await queryRunner.query(` - CREATE TABLE sys_config ( - id VARCHAR(36) PRIMARY KEY, - \`key\` VARCHAR(255) UNIQUE NOT NULL, - value TEXT NOT NULL, - description TEXT, - category VARCHAR(100) DEFAULT 'system', - createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP - ) - `) - - // Create indexes - await queryRunner.query(`CREATE INDEX idx_users_role ON users(role)`) - await queryRunner.query(`CREATE INDEX idx_questions_student ON questions(studentId)`) - await queryRunner.query(`CREATE INDEX idx_questions_subject ON questions(subject)`) - await queryRunner.query(`CREATE INDEX idx_redo_records_question ON redo_records(questionId)`) - await queryRunner.query(`CREATE INDEX idx_redo_records_student ON redo_records(studentId)`) - await queryRunner.query(`CREATE INDEX idx_mastery_student ON mastery(studentId)`) - await queryRunner.query(`CREATE INDEX idx_mastery_status ON mastery(status)`) - await queryRunner.query(`CREATE INDEX idx_mastery_next_review ON mastery(nextReviewDate)`) - await queryRunner.query(`CREATE INDEX idx_similar_questions_original ON similar_questions(originalQuestionId)`) - await queryRunner.query(`CREATE INDEX idx_llm_usage_user ON llm_usage(userId)`) - await queryRunner.query(`CREATE INDEX idx_llm_usage_scene ON llm_usage(scene)`) - await queryRunner.query(`CREATE INDEX idx_llm_usage_created ON llm_usage(createdAt)`) - await queryRunner.query(`CREATE INDEX idx_notifications_user ON notifications(userId)`) - await queryRunner.query(`CREATE INDEX idx_notifications_read ON notifications(isRead)`) - await queryRunner.query(`CREATE INDEX idx_weekly_reports_user ON weekly_reports(userId)`) - await queryRunner.query(`CREATE INDEX idx_weekly_reports_week ON weekly_reports(weekStart, weekEnd)`) - } - - public async down(queryRunner: QueryRunner): Promise { - // Drop tables in reverse order - await queryRunner.query(`DROP TABLE IF EXISTS sys_config`) - await queryRunner.query(`DROP TABLE IF EXISTS weekly_reports`) - await queryRunner.query(`DROP TABLE IF EXISTS notifications`) - await queryRunner.query(`DROP TABLE IF EXISTS llm_usage`) - await queryRunner.query(`DROP TABLE IF EXISTS similar_questions`) - await queryRunner.query(`DROP TABLE IF EXISTS mastery`) - await queryRunner.query(`DROP TABLE IF EXISTS redo_records`) - await queryRunner.query(`DROP TABLE IF EXISTS questions`) - await queryRunner.query(`DROP TABLE IF EXISTS parents`) - await queryRunner.query(`DROP TABLE IF EXISTS students`) - await queryRunner.query(`DROP TABLE IF EXISTS users`) - } -} \ No newline at end of file diff --git a/database/migrations/1740000000000-AddDiagramUrlsToQuestions.ts b/database/migrations/1740000000000-AddDiagramUrlsToQuestions.ts deleted file mode 100644 index 5e8ec82..0000000 --- a/database/migrations/1740000000000-AddDiagramUrlsToQuestions.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MigrationInterface, QueryRunner } from 'typeorm' - -export class AddDiagramUrlsToQuestions1740000000000 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE questions - ADD COLUMN diagramUrls JSON NULL AFTER imageUrl; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE questions - DROP COLUMN diagramUrls; - `) - } -} diff --git a/docker-compose.yml b/docker-compose.yml index 6a9862b..6b5bf7c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,6 +24,8 @@ services: depends_on: mariadb: condition: service_healthy + redis: + condition: service_healthy environment: - NODE_ENV=production - PORT=3000 @@ -47,6 +49,8 @@ services: - LLM_FALLBACK_ENABLED=${LLM_FALLBACK_ENABLED:-true} - LLM_FALLBACK_RETRY_COUNT=${LLM_FALLBACK_RETRY_COUNT:-2} - LLM_FALLBACK_TIMEOUT_MS=${LLM_FALLBACK_TIMEOUT_MS:-30000} + # 异步任务队列(整页多题识别);REDIS_URL 留空则自动降级为进程内队列 + - REDIS_URL=${REDIS_URL:-redis://redis:6379} volumes: - uploads:/app/uploads networks: @@ -54,6 +58,22 @@ services: - backend-net restart: unless-stopped + # Redis:整页多题识别异步队列(BullMQ) + redis: + image: redis:7-alpine + command: ["redis-server", "--appendonly", "yes", "--maxmemory-policy", "noeviction"] + volumes: + - redis-data:/data + networks: + - backend-net + restart: unless-stopped + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + # MariaDB database mariadb: image: mariadb:10.11 @@ -97,6 +117,7 @@ services: volumes: mariadb-data: uploads: + redis-data: networks: frontend-net: diff --git a/docs/adr/0004-async-multi-question-recognition-pipeline.md b/docs/adr/0004-async-multi-question-recognition-pipeline.md new file mode 100644 index 0000000..3a82499 --- /dev/null +++ b/docs/adr/0004-async-multi-question-recognition-pipeline.md @@ -0,0 +1,33 @@ +# ADR 0004: 整页多题 Vision 识别异步化架构(任务队列 + 轮询) + +## 状态 +已通过 (Accepted) + +## 上下文 (Context) +整页多题切分识别(`POST /api/questions/identify-multi`)原为同步 HTTP 挂起调用:整页大图的 Vision 模型调用通常耗时 15-30 秒,叠加降级重试可达 1 分钟以上。Nginx 反向代理在长请求上容易触发 504 Gateway Timeout,导致识别失败且无法恢复,也不可观测进度。 + +## 决策 (Decisions) + +1. **接口立即返回 taskId(异步任务模式)**: + - `POST /api/questions/identify-multi/async` 上传图片后立即返回 `202 { taskId, statusUrl }`; + - 前端轮询 `GET /api/questions/identify-multi/tasks/:taskId`(2 秒间隔)获取 `state`(queued/processing/completed/failed)、`progress`(0-100)与识别结果 `items`; + - 选择轮询而非 SSE:轮询对 Nginx/代理无附加要求(无需缓冲关闭配置),实现简单、断线可恢复,移动端 H5 兼容性最好。 + +2. **默认队列方案:Redis + BullMQ**: + - docker-compose 增加 `redis:7-alpine` 服务(AOF 持久化 + `maxmemory-policy noeviction`,BullMQ 官方要求),backend 注入 `REDIS_URL`; + - BullMQ Queue + 进程内 Worker(并发 1,避免并发 Vision 调用打爆上游配额),任务状态/进度/结果存 Redis; + - 任务完成后结果保留 1 小时(`removeOnComplete: { age: 1h, count: 500 }`)供轮询,之后自动清理;`attempts: 1` 不自动重试(LLM 识别重试由服务层降级策略负责); + - backend 进程内运行 Worker(单容器自托管场景,无需独立 worker 服务);SIGTERM/SIGINT 优雅关闭等待任务收尾。 + +3. **无 Redis 自动降级:进程内队列**: + - `REDIS_URL` 未配置时,任务管理器自动降级为进程内队列(内存 Map + 串行异步执行),对外接口行为完全一致(同样立即返回 taskId + 轮询); + - 局限:任务不跨进程重启保留、仅适用单实例部署——自托管单容器场景可接受; + - 该设计保证**所有部署形态都不存在同步 HTTP 长挂起路径**,504 风险被消除。 + +4. **同步接口保留(兼容)**: + - 原 `POST /api/questions/identify-multi` 保留为同步兼容接口,内部与异步任务共用同一处理管道(`processIdentifyMulti`:LLM 识别 → 归一化 → 文本指纹防重 → 失败兜底 mock);前端已切换为异步路径。 + +## 后果 (Consequences) +- **正面**:504 风险消除;识别进度可视化(排队/识别中 x%);任务失败有明确错误态可重试;LLM 用量与重复识别可控(任务级幂等提交)。 +- **负面**:部署组件增加 Redis(docker-compose 一键托管,自托管门槛小幅上升);降级模式下任务不跨重启保留;前端需实现轮询生命周期管理(超时 10 分钟、取消、换图重置)。 +- **措辞限定**:应用主链路(前端录入页)不再存在同步长挂起请求;原同步 `/identify-multi` 接口为兼容保留,本身仍是长挂起路径(前端不再调用,第三方直连时需注意)。 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 209d067..f7849a0 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "error-management-frontend", - "version": "1.2.1", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "error-management-frontend", - "version": "1.2.1", + "version": "1.3.0", "dependencies": { "axios": "^1.6.8", "katex": "^0.18.1", diff --git a/frontend/package.json b/frontend/package.json index 8f641ac..0602914 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "error-management-frontend", - "version": "1.2.1", + "version": "1.3.0", "description": "错题管理系统前端 - H5移动优先Web应用", "type": "module", "scripts": { @@ -8,7 +8,8 @@ "build": "vue-tsc && vite build", "preview": "vite preview", "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix", - "format": "prettier --write src/" + "format": "prettier --write src/", + "test": "vitest run" }, "dependencies": { "axios": "^1.6.8", @@ -27,6 +28,7 @@ "prettier": "^3.2.5", "typescript": "~5.4.0", "vite": "^5.2.0", + "vitest": "^1.6.0", "vue-tsc": "^2.0.6" } } diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index ec0cf2a..99ae348 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -42,6 +42,12 @@ const routes: RouteRecordRaw[] = [ component: () => import('@/views/student/QuestionDetail.vue'), meta: { requiresAuth: true }, }, + { + path: '/questions/export', + name: 'QuestionPaperExport', + component: () => import('@/views/student/QuestionPaperExport.vue'), + meta: { requiresAuth: true }, + }, { path: '/redo/add/:questionId', name: 'AddRedo', @@ -147,6 +153,12 @@ const routes: RouteRecordRaw[] = [ component: () => import('@/views/common/Stats.vue'), meta: { requiresAuth: true }, }, + { + path: '/reports/weakness', + name: 'WeaknessProfile', + component: () => import('@/views/common/WeaknessProfile.vue'), + meta: { requiresAuth: true }, + }, { path: '/settings', name: 'Settings', diff --git a/frontend/src/services/mastery.ts b/frontend/src/services/mastery.ts index a75f35d..2458c6a 100644 --- a/frontend/src/services/mastery.ts +++ b/frontend/src/services/mastery.ts @@ -40,6 +40,12 @@ export interface Mastery { questionId: string /** 学生ID */ studentId: string + /** 关联题目(复习队列接口返回) */ + question?: { + id: string + title: string + content: string + } /** 创建时间 */ createdAt: string /** 更新时间 */ diff --git a/frontend/src/services/questions.ts b/frontend/src/services/questions.ts index 6df3e6b..564b908 100644 --- a/frontend/src/services/questions.ts +++ b/frontend/src/services/questions.ts @@ -39,6 +39,8 @@ export interface Question { originalImageUrl?: string /** 独立插图URL列表 */ diagramUrls?: string[] + /** 错因标签(审题不清/计算粗心/公式遗忘/方法缺失/其他) */ + errorTags?: string[] /** 参考答案 */ answer?: string /** 解析说明 */ @@ -76,6 +78,8 @@ export interface CreateQuestionRequest { difficulty: number /** 知识点标签 */ knowledgePoints: string[] + /** 错因标签 */ + errorTags?: string[] /** 参考答案 */ answer?: string /** 解析说明 */ @@ -109,7 +113,7 @@ export const questionService = { const formData = new FormData() Object.entries(data).forEach(([key, value]) => { if (value !== undefined && value !== null) { - if (key === 'knowledgePoints') { + if (key === 'knowledgePoints' || key === 'errorTags') { formData.append(key, JSON.stringify(value)) } else { formData.append(key, String(value)) @@ -149,6 +153,12 @@ export const questionService = { return response.data }, + /** 设置错因标签(mode=replace 整组替换;mode=merge 追加,重做后标注用) */ + async setErrorTags(id: string, tags: string[], mode: 'replace' | 'merge' = 'merge'): Promise { + const response = await api.put(`/questions/${id}/error-tags`, { tags, mode }) + return response.data + }, + async delete(id: string): Promise { await api.delete(`/questions/${id}`) }, @@ -198,6 +208,42 @@ export const questionService = { return result.data || result }, + /** + * 异步提交整页多题识别:立即返回 taskId,避免同步挂起触发 Nginx 504。 + * 配合 getMultiTaskStatus 轮询进度与结果。 + */ + async identifyMultiAsync(image: File, subject?: string): Promise<{ taskId: string; statusUrl: string }> { + const formData = new FormData() + formData.append('image', image) + if (subject) formData.append('subject', subject) + + const token = localStorage.getItem('token') + const response = await fetch('/api/questions/identify-multi/async', { + method: 'POST', + headers: { + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: formData, + }) + const result = await response.json() + if (!response.ok) { + throw new Error(result.message || `HTTP ${response.status}`) + } + return result.data || result + }, + + /** 查询识别任务状态(queued/processing/completed/failed + 进度 + 结果) */ + async getMultiTaskStatus(taskId: string): Promise<{ + taskId: string + state: 'queued' | 'processing' | 'completed' | 'failed' + progress: number + result?: { items: any[] } + error?: string + }> { + const response = await api.get(`/questions/identify-multi/tasks/${taskId}`) + return response.data + }, + async createBatch(items: any[]): Promise { const response = await api.post('/questions/batch', { items }) return response.data diff --git a/frontend/src/services/reports.ts b/frontend/src/services/reports.ts index fe39e2d..5349a54 100644 --- a/frontend/src/services/reports.ts +++ b/frontend/src/services/reports.ts @@ -64,6 +64,28 @@ export interface DailyReport { } } +/** + * 薄弱点画像接口 + */ +export interface ErrorTagSlice { + tag: string + count: number +} + +export interface WeakKnowledgePoint { + point: string + questionCount: number + incorrectCount: number + totalQuestions: number +} + +export interface ErrorProfile { + totalQuestions: number + taggedQuestions: number + errorTagDistribution: ErrorTagSlice[] + weakKnowledgePoints: WeakKnowledgePoint[] +} + /** * 统计接口 */ @@ -117,4 +139,10 @@ export const reportService = { const response = await api.get(`/reports/parent/${parentId}/child`) return response.data }, + + /** 薄弱点画像(错因占比 + 薄弱知识点,学生/家长共用) */ + async getErrorProfile(studentId: string): Promise { + const response = await api.get(`/reports/error-profile/${studentId}`) + return response.data + }, } \ No newline at end of file diff --git a/frontend/src/utils/__tests__/paperBuilder.test.ts b/frontend/src/utils/__tests__/paperBuilder.test.ts new file mode 100644 index 0000000..66c2236 --- /dev/null +++ b/frontend/src/utils/__tests__/paperBuilder.test.ts @@ -0,0 +1,101 @@ +import { describe, it, expect } from 'vitest' +import { buildPaperHtml, escapeHtml, type PaperQuestion } from '../paperBuilder' + +const passthrough = (t: string) => t + +const baseQuestion = (overrides: Partial = {}): PaperQuestion => ({ + title: '一元二次方程求解', + content: '已知方程 $x^2 - 4 = 0$,求所有实数解。', + subject: 'math', + type: 'answer', + difficulty: 3, + diagramUrls: ['/uploads/diagram-1.png'], + answer: '$x = \\pm 2$', + explanation: '因式分解得 $(x-2)(x+2) = 0$。', + ...overrides, +}) + +describe('escapeHtml', () => { + it('转义纯文本中的 HTML 特殊字符', () => { + expect(escapeHtml('')).toBe( + '<img src=x onerror=alert(1)>' + ) + expect(escapeHtml('a & "b" \'c\'')).toBe('a & "b" 'c'') + }) +}) + +describe('buildPaperHtml', () => { + it('纯题卷:包含题干、公式、干净插图,不含答案/解析/原图', () => { + const q = baseQuestion({ + diagramUrls: ['/uploads/diagram-clean.png'], + answer: 'SECRET-ANSWER', + explanation: 'SECRET-EXPLANATION', + }) + const html = buildPaperHtml([q], { mode: 'questions' }, passthrough) + + expect(html).toContain('错题重练卷') + expect(html).toContain('纯题卷 · 不含答案') + expect(html).toContain('已知方程 $x^2 - 4 = 0$') + expect(html).toContain('src="/uploads/diagram-clean.png"') + expect(html).not.toContain('SECRET-ANSWER') + expect(html).not.toContain('SECRET-EXPLANATION') + expect(html).not.toContain('pq-answer-block') + }) + + it('题卷+详细解析:包含答案与解析块', () => { + const html = buildPaperHtml([baseQuestion()], { mode: 'withAnswers' }, passthrough) + + expect(html).toContain('错题重练卷(含解析)') + expect(html).toContain('含参考答案与解析') + expect(html).toContain('pq-answer-block') + expect(html).toContain('参考答案') + expect(html).toContain('因式分解得 $(x-2)(x+2) = 0$') + }) + + it('插图只取 diagramUrls,绝不输出 imageUrl(原图由调用方不传入,构建器也不接受该字段)', () => { + const q = baseQuestion() as any + q.imageUrl = '/uploads/original-with-handwriting.jpg' + const html = buildPaperHtml([q], { mode: 'questions' }, passthrough) + expect(html).toContain('/uploads/diagram-1.png') + expect(html).not.toContain('original-with-handwriting') + }) + + it('多题题号连续,头部统计题数与科目', () => { + const qs = [ + baseQuestion({ subject: 'math' }), + baseQuestion({ subject: 'physics' }), + baseQuestion({ subject: 'chemistry' }), + ] + const html = buildPaperHtml(qs, { mode: 'questions' }, passthrough) + expect(html).toContain('共 3 题') + expect(html).toContain('数学') + expect(html).toContain('物理') + expect(html).toContain('化学') + expect(html).toContain('1.') + expect(html).toContain('3.') + }) + + it('标题与选项等纯文本先转义再进渲染函数(防注入)', () => { + const q = baseQuestion({ title: '求 所有 解 & "验证"' }) + const html = buildPaperHtml([q], { mode: 'questions' }, passthrough) + expect(html).toContain('求 <b>所有</b> 解 & "验证"') + }) + + it('自定义渲染函数被用于题干/答案/解析', () => { + const calls: string[] = [] + const spy = (t: string) => { + calls.push(t) + return `[R:${t}]` + } + const html = buildPaperHtml([baseQuestion()], { mode: 'withAnswers' }, spy) + expect(html).toContain('[R:一元二次方程求解]') + expect(html).toContain('[R:$x = \\pm 2$]') + expect(calls).toContain('已知方程 $x^2 - 4 = 0$,求所有实数解。') + }) + + it('空列表输出空卷提示', () => { + const html = buildPaperHtml([], { mode: 'questions' }, passthrough) + expect(html).toContain('暂无错题可导出') + expect(html).toContain('共 0 题') + }) +}) diff --git a/frontend/src/utils/paperBuilder.ts b/frontend/src/utils/paperBuilder.ts new file mode 100644 index 0000000..3dbe836 --- /dev/null +++ b/frontend/src/utils/paperBuilder.ts @@ -0,0 +1,154 @@ +/** + * A4 排版试卷构建器(纯函数,可单测) + * + * 两种导出模式(对标 wrong-notebook): + * - questions 纯题卷:仅题目文本 + KaTeX 公式 + 干净的 diagramUrls 裁剪插图; + * 不含参考答案、解析与带手写笔记的原始全景图,适合线下重做; + * - withAnswers 题卷 + 详细解析:在纯题卷基础上追加参考答案与解析块。 + * + * 安全约定:题目文本/公式走 renderMath(与应用其余渲染路径一致); + * 纯文本片段(标题、姓名、标签)统一 escapeHtml 后输出。 + */ + +import { renderMath } from './math' + +export type PaperMode = 'questions' | 'withAnswers' + +export interface PaperQuestion { + title: string + content: string + subject: string + type: string + difficulty?: number + /** 干净裁剪插图(不含手写答案的全景图不入卷) */ + diagramUrls?: string[] + answer?: string + explanation?: string +} + +export interface PaperOptions { + mode: PaperMode + paperTitle?: string + studentName?: string + date?: string +} + +const SUBJECT_TEXTS: Record = { + math: '数学', + physics: '物理', + chemistry: '化学', +} + +const TYPE_TEXTS: Record = { + choice: '选择题', + fill: '填空题', + answer: '解答题', +} + +export function escapeHtml(text: string): string { + return String(text) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +const subjectText = (s: string) => SUBJECT_TEXTS[s] || s +const typeText = (t: string) => TYPE_TEXTS[t] || t + +/** + * 构建试卷正文 HTML 片段(不含 外壳与样式表; + * @page/print 样式由承载页面提供,保证该函数在 Node 单测环境可运行)。 + */ +/** 公式渲染函数签名(与 utils/math 的 renderMath 兼容) */ +interface MathRenderer { + // eslint-disable-next-line no-unused-vars -- 函数类型参数名仅作类型标注 + (t: string): string +} + +export function buildPaperHtml( + questions: PaperQuestion[], + options: PaperOptions, + renderMathFn: MathRenderer = renderMath +): string { + // 题干/答案/解析:先转义纯文本再交给渲染函数(防注入),公式渲染与全应用一致 + const safeMath = (text: string) => renderMathFn(escapeHtml(text)) + const mode = options.mode === 'withAnswers' ? 'withAnswers' : 'questions' + const paperTitle = options.paperTitle || (mode === 'withAnswers' ? '错题重练卷(含解析)' : '错题重练卷') + + const header = ` +
+

${escapeHtml(paperTitle)}

+
+ ${escapeHtml(options.studentName ? `学生:${options.studentName}` : '')} + ${escapeHtml(options.date || '')} + 共 ${questions.length} 题 + ${mode === 'withAnswers' ? '含参考答案与解析' : '纯题卷 · 不含答案'} +
+
+ ` + + const body = questions + .map((q, idx) => { + const head = ` +
+ ${idx + 1}. + ${escapeHtml(subjectText(q.subject))} + ${escapeHtml(typeText(q.type))} + ${q.difficulty ? `难度 ${escapeHtml(String(q.difficulty))}` : ''} +
+ ` + const titleHtml = q.title + ? `
${safeMath(q.title)}
` + : '' + const contentHtml = q.content + ? `
${safeMath(q.content)}
` + : '' + + // 仅使用独立裁剪插图 diagramUrls;带手写笔记的原始全景图 imageUrl 一律不入卷 + const diagramItems = (q.diagramUrls || []) + .filter((url) => typeof url === 'string' && url) + .map( + (url, i) => ` +
+ 题图 ${i + 1} +
` + ) + .join('') + const diagramsHtml = diagramItems + ? `
${diagramItems}
` + : '' + + let answerHtml = '' + if (mode === 'withAnswers') { + answerHtml = ` +
+ ${q.answer ? `
参考答案
${renderMathFn(escapeHtml(q.answer))}
` : ''} + ${q.explanation ? `
解析
${renderMathFn(escapeHtml(q.explanation))}
` : ''} +
+ ` + } + + return ` +
+ ${head} + ${titleHtml} + ${contentHtml} + ${diagramsHtml} + ${answerHtml} +
+ ` + }) + .join('\n') + + const empty = questions.length === 0 ? `
暂无错题可导出
` : '' + + return ` +
+ ${header} + ${empty} + ${body} +
+ ` +} diff --git a/frontend/src/views/common/WeaknessProfile.vue b/frontend/src/views/common/WeaknessProfile.vue new file mode 100644 index 0000000..0cccbf9 --- /dev/null +++ b/frontend/src/views/common/WeaknessProfile.vue @@ -0,0 +1,197 @@ + + + + + diff --git a/frontend/src/views/parent/Dashboard.vue b/frontend/src/views/parent/Dashboard.vue index 278497f..75b8cc3 100644 --- a/frontend/src/views/parent/Dashboard.vue +++ b/frontend/src/views/parent/Dashboard.vue @@ -43,6 +43,13 @@ icon="orders-o" @click="$router.push('/parent/questions')" /> + + > + + + + + + +
+ + + + + + + + + + {{ multiTaskFailed ? '重新开始' : '取消等待' }} + +
+
识别结果列表 (勾选需要导入的题目):
@@ -234,7 +278,7 @@ + + + + diff --git a/frontend/src/views/student/Questions.vue b/frontend/src/views/student/Questions.vue index 6c22822..7a6127a 100644 --- a/frontend/src/views/student/Questions.vue +++ b/frontend/src/views/student/Questions.vue @@ -6,6 +6,11 @@ @click-left="$router.back()" >