Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions .github/workflows/auto-review.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
103 changes: 99 additions & 4 deletions API_DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,36 @@ Authorization: Bearer <token>
}
```

### PUT /api/questions/:id/error-tags

更新错题的错因标签(多维度错因体系)。标签白名单:`审题不清` / `计算粗心` / `公式遗忘` / `方法缺失` / `其他`;去重后最多 10 个,非法值被过滤。

**请求头**:
```
Authorization: Bearer <token>
```

**请求体**:
```json
{
"tags": ["审题不清", "计算粗心"],
"mode": "merge"
}
```

- `mode: "replace"` 全量替换;默认/`"merge"` 与现有标签取并集(重做流程追加标注场景)。

**响应**:
```json
{
"status": "success",
"data": {
"id": "uuid",
"errorTags": ["审题不清", "计算粗心"]
}
}
```

### DELETE /api/questions/:id

删除错题
Expand Down Expand Up @@ -1092,6 +1122,33 @@ Authorization: Bearer <token>
}
```

### GET /api/reports/error-profile/:studentId

错因多维度标签画像(评审 C1 后 `studentId` 同时接受登录用户 id(users.id)与学生档案 id(students.id)):返回错因标签分布 + 按错误次数加权的薄弱知识点,供学生端与家长端「薄弱点画像」页使用。

**请求头**:
```
Authorization: Bearer <token>
```

**响应**:
```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

获取日报
Expand Down Expand Up @@ -1126,7 +1183,7 @@ Authorization: Bearer <token>
### GET /api/llm/usage/summary

### POST /api/questions/identify-multi
大模型多题切分识别接口,支持上传整页图片,自动定位并识别页面中的多道错题。
大模型多题切分识别接口(同步兼容接口,建议改用异步接口,避免长请求触发 Nginx 504)。

#### 请求
- Header: `Content-Type: multipart/form-data`
Expand All @@ -1136,11 +1193,49 @@ Authorization: Bearer <token>
```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": "<uuid>",
"statusUrl": "/api/questions/identify-multi/tasks/<uuid>"
}
}
```

### GET /api/questions/identify-multi/tasks/:taskId
查询异步识别任务状态(轮询入口,建议 2 秒间隔,超时 10 分钟)。

#### 响应
```json
{
"status": "success",
"data": {
"taskId": "<uuid>",
"state": "queued | processing | completed | failed",
"progress": 55,
"result": { "items": [ ... 同同步接口 items 结构 ... ] },
"error": "失败原因(仅 failed)"
}
}
```
任务不存在或已过期(完成后 1 小时清理)返回 404。
获取LLM用量汇总

**请求头**:
Expand Down
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 用量监控与告警
Expand Down Expand Up @@ -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 配置
Expand Down
4 changes: 2 additions & 2 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand All @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions backend/src/__tests__/controllers/MasteryController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
93 changes: 93 additions & 0 deletions backend/src/__tests__/controllers/QuestionAsyncTask.test.ts
Original file line number Diff line number Diff line change
@@ -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 },
})
})
})
})
37 changes: 37 additions & 0 deletions backend/src/__tests__/controllers/QuestionController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Loading
Loading