From 441c6ca2f8eaa7eebd1c3e3a20c17fae50d1de61 Mon Sep 17 00:00:00 2001 From: xstudio agent Date: Tue, 29 Sep 2026 16:05:08 +0800 Subject: [PATCH 1/6] =?UTF-8?q?chg=5F0012(T1):=20docs/dth/lms-v2/scenario.?= =?UTF-8?q?md=20=E2=80=94=204=20scene=20=E8=AE=BE=E8=AE=A1=E4=B8=8E=20FRC?= =?UTF-8?q?=20=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 验证 chg_0006 LMS v1 已在 src/backend/src/lms/ 完整存在(CLAUDE.md F-2 路径索引有误) - 实际 schema: lms_course(code,name,instructor) / lms_enrollment(status) - 实际 seed: S20200001/李雷 + CS101/数据安全导论(与 brief 描述不一致;以在盘为准) - 4 类 scene: slide / quiz / simulation / pbl(pbl v2 阶段仅占位 + 501) - 命名取舍: 保留 dth simulation 而非 OpenMAIC interactive(与 chg_0010/0011 术语一致) - MiniMD 5 节点规格: h1/h2/p/ul/li/code;非法节点原样保留 - FRC 6-scene 模板: 严格对位 chg_0010 S1-S6(6 simulation scene + order_index 1-6) - 6 个 v2 endpoint + 6 条关键不变量 + 4 前端组件 + 3 前端视图 Co-Authored-By: Claude --- docs/dth/lms-v2/scenario.md | 165 ++++++++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 docs/dth/lms-v2/scenario.md diff --git a/docs/dth/lms-v2/scenario.md b/docs/dth/lms-v2/scenario.md new file mode 100644 index 0000000..6cb1f22 --- /dev/null +++ b/docs/dth/lms-v2/scenario.md @@ -0,0 +1,165 @@ +# LMS v2 多场景课程平台 — 4 类 Scene 设计 + FRC 模板 + +> chg_0012 · 2026-09-29 · owner: pm@dth · 状态:implemented +> +> 在 chg_0006 LMS v1(学员 / 课程 / 选课)基础上扩展 v2:把每门课程拆成 +> **有序 scene 序列**,scene 4 类(slide / quiz / simulation / pbl)。 +> 同时落地 **FRC 6-scene 模板**,把 chg_0010 的 6 步联合风控流程以 +> "可执行 simulation" 形式嵌入 LMS 课程。 +> +> **0 新算子 / 0 新依赖 / 0 前端框架切换**。所有 scene 复用既有 chg_0008/0009 算子 +> (通过 `embed_url` 引用 `/experiment/runs` 形态)或前端纯组件渲染。 + +## 0. 状态核验(chg_0012 起点) + +CLAUDE.md F-2 索引说 LMS 在 `src/backend/src/dth/lms/`,**实际位置是 +`src/backend/src/lms/`**(自 chg_0006 落地起就在此,未迁移至 `dth/` 子目录)。 +chg_0012 T1 不重建 v1,直接在此基础上扩展 v2。详见下文"实现路径"段。 + +实际字段命名与 brief 略有差异,本设计以**在盘代码为准**: + +| 字段 | 本设计 | brief 描述 | 决策 | +|---|---|---|---| +| `lms_course.code` | `code` | `course_code` | **保持 `code`**(与 chg_0006 一致,e2e 已依赖) | +| `lms_course.name` | `name` | `title` | **保持 `name`**(同上) | +| `lms_course.instructor` | `instructor` | `teacher` | **保持 `instructor`**(同上) | +| `lms_enrollment.status` | `status` | `progress_scene_ids JSON` | **保持 `status`**;v2 进度另开 `lms_course_scene` 表 | + +种子数据也与 brief 不一致: + +| 资源 | 实际 seed | brief 描述 | +|---|---|---| +| 学员 1 | `S20200001` / 李雷 / `lilei@school.edu` | `S2026001` / 张三 | +| 学员 2 | `S20200002` / 韩梅梅 / `hanmeimei@school.edu` | (未指定)| +| 课程 1 | `CS101` / 数据安全导论 / 3 学分 / 王老师 | `C-INTRO` / 数智安全导论 | +| 课程 2 | `CS201` / 隐私计算实战 / 4 学分 / 陈老师 | (未指定)| + +> **Ruling**:v1 schema / seed 不动;chg_0012 在 v1 之上增量加 `lms_course_scene` 表 + v2 endpoints。 +> chg_0006 LMS e2e (`tests/e2e/dth_lms.test.sh`) 不回归。 + +## 1. 业务背景 + +LMS v1 的课程是"扁平"资源——只描述课程元信息(代码 / 学分 / 教师), +不描述课程**怎么上**。v2 引入"场景化教学":每门课 = 一个**有序 scene 序列**, +学员按 order_index 依次完成。 + +4 类 scene 对位教学法(沿用既有 chg_0008/0009 算子命名 + LMS 教学常识): + +| scene_type | 教学法 | 实现 | 何时用 | +|---|---|---|---| +| `slide` | 讲解(教师讲) | 后端 MiniMD → 前端 `dangerouslySetInnerHTML` | 概念导入 / 算子原理讲解 | +| `quiz` | 测验(学员练)| 前端本地判分 + 调用 `POST /scenes/:id/grade` 留痕 | 概念验证 / 选择题 + 简答题 | +| `simulation` | 仿真(学员跑)| `embed_url` 指向既有算子 e2e 页面或 `experiment/runs` 触发页 | 真实算子协同演示(如 FRC 6 步) | +| `pbl` | PBL(项目式学习)| **v2 阶段仅做占位 + 501 NOT_IMPLEMENTED** | 课程占位 / 后续 chg | + +### 与 OpenMAIC 的对位(命名取舍) + +OpenMAIC(multi-agent interactive classroom)的 scene 字典命名是 +`interactive`(默认)/ `video` / `audio` / `quiz` / `simulation`。 +我们**保留 dth 命名 `simulation` 而非 OpenMAIC 的 `interactive`**: + +1. chg_0010 / chg_0011 已落地"6 步 simulation 流程"作为术语, + 改名会导致 e2e / 文档断裂; +3. dth scene 字典保持简洁 4 类(slide/quiz/simulation/pbl),不引入 `video` / `audio` + (实验台是后端工程师学习平台,视频/音频教学形态不属于 v0)。 + +## 2. 数据模型(PGlite 第 4 张表) + +### lms_course_scene(v2 新增) + +```sql +CREATE TABLE IF NOT EXISTS lms_course_scene ( + id TEXT PRIMARY KEY, -- uuid v4 + course_id TEXT NOT NULL, -- FK → lms_course.id + scene_type TEXT NOT NULL, -- enum: slide|quiz|simulation|pbl + payload_json TEXT NOT NULL, -- 不同 scene 不同 schema + order_index INTEGER NOT NULL, -- 1-based + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(course_id, order_index), -- 顺序不冲突 + CHECK(scene_type IN ('slide','quiz','simulation','pbl')) +); +CREATE INDEX IF NOT EXISTS idx_lms_course_scene_course ON lms_course_scene(course_id); +``` + +### 4 类 payload schema(payload_json 内部) + +| scene_type | payload_json 必填字段 | 可选字段 | 备注 | +|---|---|---|---| +| `slide` | `markdown: string`(MiniMD 5 节点) | `title: string` | 后端转换 HTML,前端 `dangerouslySetInnerHTML` | +| `quiz` | `questions: [{id, type: 'choice'/'short', prompt, options?, answer?, keywords?}]` | `pass_score: number` | `answer` + `keywords` 用于判分(参考依据:服务端的黄金答案) | +| `simulation` | `embed_url: string`(必须 http(s):// 前缀)| `height: number`、`sandbox: string` | 前端 iframe `sandbox=allow-same-origin`(默认) | +| `pbl` | (v2 阶段无必填)| `placeholder: string` | 后端 render 返回 501 NOT_IMPLEMENTED | + +### MiniMD 5 节点规格 + +| 节点 | Markdown 语法 | HTML 输出 | 非法节点处理 | +|---|---|---|---| +| `h1` | `# xxx` | `

xxx

` | 原样保留(含 `# xxx` 文本) | +| `h2` | `## xxx` | `

xxx

` | 同上 | +| `p` | 任意行(非标题 / 列表 / 代码) | `

xxx

` | 同上 | +| `ul` / `li` | `- xxx` / ` - xxx` | `` | 同上 | +| `code` | `` ```xxx``` `` 或 ` `xxx` ` | (临时占位)| -- | + +**非法节点策略 = 原样保留**(不抛错、不删字符),确保坏 Markdown 也能渲染(虽然丑)。 +实现路径:正则 5 类匹配 + 全局 fail-open 替换;这是**零新依赖**的关键。 + +## 3. API 设计(v2 endpoints) + +| Method | Path | 鉴权 | 用途 | +|---|---|---|---| +| `POST` | `/api/ssw/dth/lms-v2/courses` | admin | 创建课程(**含 scenes[]**);重复 code → 409 DUPLICATE_COURSE_CODE | +| `GET` | `/api/ssw/dth/lms-v2/courses/:courseId/scenes` | admin / 非 admin | 列出课程全部 scene(按 order_index 升序) | +| `GET` | `/api/ssw/dth/lms-v2/courses/:courseId/scenes/:sceneId/render` | 学员 / admin | scene 渲染(slide → HTML;simulation → 校验 embed_url;pbl → 501) | +| `POST` | `/api/ssw/dth/lms-v2/scenes/:sceneId/grade` | 学员 | quiz 判分 → `{score: 0..1, correct_count, total_count}` | +| `POST` | `/api/ssw/dth/lms-v2/scenes/:sceneId/complete` | 学员 | 标记 scene 完成(**append-only 幂等**,进度 JSON 累积) | +| `POST` | `/api/ssw/dth/lms-v2/courses/from-frc-template` | admin | 生成 FRC 6-scene 模板课程(见 §4) | + +### 关键不变量 + +| 不变量 | 失败码 | 文案 | +|---|---|---| +| 重复 `course_code` | 409 | `DUPLICATE_COURSE_CODE` | +| 重复 enroll(同 student × course)| 409 | `ALREADY_ENROLLED`(与 v1 一致)| +| `progress_scene_ids` append-only | — | 重复 complete 不增 count(测试断言)| +| 非法 `scene_type`(如 `video`)| 422 | `INVALID_SCENE_TYPE`(schema CHECK 兜底)| +| `simulation.embed_url` 非 http(s):// | 400 | `INVALID_EMBED_URL` | +| PBL scene render | 501 | `NOT_IMPLEMENTED`,文案:"PBL 场景 v2 实现,当前仅作课程占位" | + +## 4. FRC 6-scene 模板 + +`POST /api/ssw/dth/lms-v2/courses/from-frc-template` 接受 `{course_code, teacher}`, +创建 1 门含 **6 个 simulation scene** 的课程(order_index 1-6),embed_url +严格对应 chg_0010 S1-S6: + +| order | scene_id (chg_0010 S#) | title | embed_url 描述 | +|---|---|---|---| +| 1 | S1 | DID + TDS 联合身份验证 | `/exp/admin/iframe/s1` | +| 2 | S2 | PSI 求三方交集 | `/exp/admin/iframe/s2` | +| 3 | S3 | Paillier 同态求和 | `/exp/admin/iframe/s3` | +| 4 | S4 | Threshold 2-of-3 签名 | `/exp/admin/iframe/s4` | +| 5 | S5 | ABAC 联合风控策略 | `/exp/admin/iframe/s5` | +| 6 | S6 | 审计链 HMAC 验证 | `/exp/admin/iframe/s6` | + +`embed_url` 在本 chg 是占位 `/experiment/runs/` 的约定形式, +**不是真实可达 URL**——LMS v2 不引入新前端路由;学员点击 scene → iframe 加载 +`embed_url`,后端校验前缀格式即可。 + +## 5. 前端视图(4 组件 + 3 视图) + +``` +src/frontend/src/views/LMS/ + CourseList.tsx # 列出课程列表(GET /courses) + CourseDetail.tsx # 课程详情 + scene 列表(GET /courses/:id/scenes) + SceneRenderer.tsx # 路由 /courses/:courseId/scenes/:sceneId → 4 类 scene 之一 + SlideScene.tsx # dangerouslySetInnerHTML(MiniMD HTML) + QuizScene.tsx # 本地填答案 + 调 /grade + SimScene.tsx # iframe sandbox=allow-same-origin + PBLScene.tsx # 显示 "即将推出" 占位文案(与后端 501 文案一致) +``` + +路由:`/lms`(CourseList)→ `/lms/:courseId`(CourseDetail)→ `/lms/:courseId/:sceneId`(SceneRenderer)。 +挂载在 `App.tsx` 的 `` 下,与 Dashboard / OperatorList 平级。 + +## 6. e2e 覆盖(S1-S10) + +详见 `tests/e2e/dth_lms_v2.test.sh`(chg_0012 T2 输出)。 \ No newline at end of file From c1c1bf650ed540e777bb3d157a76dec61ada8c7a Mon Sep 17 00:00:00 2001 From: xstudio agent Date: Tue, 29 Sep 2026 16:15:28 +0800 Subject: [PATCH 2/6] =?UTF-8?q?chg=5F0012(T2):=20LMS=20v1=20=E9=87=8D?= =?UTF-8?q?=E5=BB=BA=20+=20v2=20=E5=A4=9A=E5=9C=BA=E6=99=AF=20+=204=20scen?= =?UTF-8?q?e=20+=20FRC=20=E6=A8=A1=E6=9D=BF=20+=20e2e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端: - lms_course_scene 表 + lms_enrollment.progress_scene_ids JSONB 列 - lms-v2.service.ts: createCourseWithScenes / renderScene / gradeQuiz / completeScene / createFromFrcTemplate + MiniMD (h1/h2/p/ul/li/code 5 节点 + 非法节点原样保留) - lms-v2.controller.ts: 6 endpoints (含 from-frc-template 生成 6 simulation scene 对位 chg_0010 S1-S6) - lms.module.ts: 注册 v2 controller + service - 6 不变量: 409 DUPLICATE_COURSE_CODE / 422 INVALID_SCENE_TYPE / 400 INVALID_EMBED_URL / 501 PBL 占位 + append-only idempotent / scene 严格 4 类 enum 前端: - api/lms/client.ts: listLmsCourses / listScenesByCourse / renderScene / gradeQuiz / completeScene / createFromFrcTemplate / enrollStudent - views/LMS/: CourseList / CourseDetail / SceneRenderer + Slide/Quiz/Sim/PBL 4 个 scene 组件 - App.tsx: 注册 /lms / /lms/:courseId / /lms/:courseId/:sceneId 3 个 ProtectedRoute - 0 新依赖 e2e: - tests/e2e/dth_lms_v2.test.sh: 10 case (45 sub-assertion) 覆盖 S1-S10 - C1 LMS v1 数据模型 / C2 scene_type enum / C3 多场景 + FRC 模板 / C4 选课 + 进度 append-only - C5 Slide MiniMD / C6 Quiz 判分 / C7 Sim embed_url / C8 FRC 6 scene 对位 chg_0010 S1-S6 - C9 E2E 完整流程 / C10 PBL 501 占位文案一致性 注意: chg_0006 LMS v1 schema/seed 已在盘存在(CLAUDE.md F-2 路径索引有误,应为 src/backend/src/lms/ 非 dth/lms/),未重建;v2 在 v1 之上增量扩展。 Co-Authored-By: Claude --- src/backend/src/common/pglite/init.ts | 24 +- src/backend/src/lms/lms-v2.controller.ts | 92 ++++ src/backend/src/lms/lms-v2.service.ts | 486 +++++++++++++++++++ src/backend/src/lms/lms.module.ts | 6 +- src/frontend/src/App.tsx | 10 + src/frontend/src/api/lms/client.ts | 205 ++++++++ src/frontend/src/views/LMS/CourseDetail.tsx | 60 +++ src/frontend/src/views/LMS/CourseList.tsx | 59 +++ src/frontend/src/views/LMS/PBLScene.tsx | 41 ++ src/frontend/src/views/LMS/QuizScene.tsx | 111 +++++ src/frontend/src/views/LMS/SceneRenderer.tsx | 66 +++ src/frontend/src/views/LMS/SimScene.tsx | 28 ++ src/frontend/src/views/LMS/SlideScene.tsx | 26 + tests/e2e/dth_lms_v2.test.sh | 454 +++++++++++++++++ 14 files changed, 1661 insertions(+), 7 deletions(-) create mode 100644 src/backend/src/lms/lms-v2.controller.ts create mode 100644 src/backend/src/lms/lms-v2.service.ts create mode 100644 src/frontend/src/api/lms/client.ts create mode 100644 src/frontend/src/views/LMS/CourseDetail.tsx create mode 100644 src/frontend/src/views/LMS/CourseList.tsx create mode 100644 src/frontend/src/views/LMS/PBLScene.tsx create mode 100644 src/frontend/src/views/LMS/QuizScene.tsx create mode 100644 src/frontend/src/views/LMS/SceneRenderer.tsx create mode 100644 src/frontend/src/views/LMS/SimScene.tsx create mode 100644 src/frontend/src/views/LMS/SlideScene.tsx create mode 100755 tests/e2e/dth_lms_v2.test.sh diff --git a/src/backend/src/common/pglite/init.ts b/src/backend/src/common/pglite/init.ts index 41d6936..0db46ab 100644 --- a/src/backend/src/common/pglite/init.ts +++ b/src/backend/src/common/pglite/init.ts @@ -55,16 +55,30 @@ export async function initPglite(): Promise { CREATE INDEX IF NOT EXISTS idx_lms_course_code ON lms_course(code); CREATE TABLE IF NOT EXISTS lms_enrollment ( - id TEXT PRIMARY KEY, - student_id TEXT NOT NULL, - course_id TEXT NOT NULL, - enrolled_at TIMESTAMP NOT NULL DEFAULT NOW(), - status TEXT NOT NULL DEFAULT 'active', + id TEXT PRIMARY KEY, + student_id TEXT NOT NULL, + course_id TEXT NOT NULL, + enrolled_at TIMESTAMP NOT NULL DEFAULT NOW(), + status TEXT NOT NULL DEFAULT 'active', + progress_scene_ids JSONB NOT NULL DEFAULT '[]'::jsonb, UNIQUE(student_id, course_id) ); CREATE INDEX IF NOT EXISTS idx_lms_enroll_student ON lms_enrollment(student_id); CREATE INDEX IF NOT EXISTS idx_lms_enroll_course ON lms_enrollment(course_id); + -- chg_0012 LMS v2: per-course ordered scenes (4 types: slide/quiz/simulation/pbl) + CREATE TABLE IF NOT EXISTS lms_course_scene ( + id TEXT PRIMARY KEY, + course_id TEXT NOT NULL, + scene_type TEXT NOT NULL, + payload_json TEXT NOT NULL, + order_index INTEGER NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(course_id, order_index), + CHECK(scene_type IN ('slide','quiz','simulation','pbl')) + ); + CREATE INDEX IF NOT EXISTS idx_lms_scene_course ON lms_course_scene(course_id); + -- chg_0007 lite-demo schema: book_shop_book / book_shop_product -- JNPF f_ 前缀 + f_id varchar(50) + f_delete_mark 软删 CREATE TABLE IF NOT EXISTS book_shop_book ( diff --git a/src/backend/src/lms/lms-v2.controller.ts b/src/backend/src/lms/lms-v2.controller.ts new file mode 100644 index 0000000..e7c3940 --- /dev/null +++ b/src/backend/src/lms/lms-v2.controller.ts @@ -0,0 +1,92 @@ +import { + Body, + Controller, + Get, + Param, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import { JwtAuthGuard, RequireAdmin } from '../auth/jwt.guard'; +import { + CreateCourseWithScenesDto, + LmsV2Service, + SceneType, +} from './lms-v2.service'; + +/** + * LMS v2 controller — multi-scene course endpoints. + * Path prefix: /api/ssw/dth/lms-v2 + * + * 401/600 from JwtAuthGuard; admin-only endpoints tagged via @RequireAdmin(). + */ +@Controller('api/ssw/dth/lms-v2') +@UseGuards(JwtAuthGuard) +export class LmsV2Controller { + constructor(private readonly v2: LmsV2Service) {} + + /** Admin creates a course with optional embedded scenes. */ + @Post('courses') + @RequireAdmin() + async createCourseWithScenes(@Body() dto: CreateCourseWithScenesDto) { + const result = await this.v2.createCourseWithScenes(dto); + return { code: 200, msg: 'ok', data: result }; + } + + /** Admin creates a course pre-populated with FRC's 6 simulation scenes. */ + @Post('courses/from-frc-template') + @RequireAdmin() + async createFromFrcTemplate( + @Body() dto: { course_code: string; teacher: string }, + ) { + const result = await this.v2.createFromFrcTemplate(dto); + return { code: 200, msg: 'ok', data: result }; + } + + /** List scenes for a course (any authenticated user). */ + @Get('courses/:courseId/scenes') + async listScenes(@Param('courseId') courseId: string) { + const scenes = await this.v2.listScenesByCourse(courseId); + return { code: 200, msg: 'ok', data: scenes }; + } + + /** Render a scene (returns payload depending on scene_type). */ + @Get('courses/:courseId/scenes/:sceneId/render') + async renderScene( + @Param('courseId') courseId: string, + @Param('sceneId') sceneId: string, + ) { + const data = await this.v2.renderScene(courseId, sceneId); + return { code: 200, msg: 'ok', data }; + } + + /** Grade a quiz submission. */ + @Post('scenes/:sceneId/grade') + async gradeScene( + @Param('sceneId') sceneId: string, + @Body() dto: { answers: Record }, + ) { + const answers = dto?.answers ?? {}; + const result = await this.v2.gradeQuiz(sceneId, answers); + return { code: 200, msg: 'ok', data: result }; + } + + /** Mark scene complete (idempotent append-only). */ + @Post('scenes/:sceneId/complete') + async completeScene( + @Param('sceneId') sceneId: string, + @Body() dto: { student_id: string; course_id: string }, + ) { + const studentId = dto?.student_id; + const courseId = dto?.course_id; + if (!studentId || !courseId) { + throw new (await import('@nestjs/common')).BadRequestException( + 'student_id / course_id are required', + ); + } + const result = await this.v2.completeScene(studentId, courseId, sceneId); + return { code: 200, msg: 'ok', data: result }; + } +} + +export { SceneType }; \ No newline at end of file diff --git a/src/backend/src/lms/lms-v2.service.ts b/src/backend/src/lms/lms-v2.service.ts new file mode 100644 index 0000000..4a75349 --- /dev/null +++ b/src/backend/src/lms/lms-v2.service.ts @@ -0,0 +1,486 @@ +import { + BadRequestException, + ConflictException, + Injectable, + NotFoundException, + NotImplementedException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { v4 as uuidv4 } from 'uuid'; +import { getDb } from '../common/pglite/init'; +import { CoursesService } from './courses.courses.service'; + +/** + * LMS v2 service — multi-scene courses with 4 scene types + * (slide/quiz/simulation/pbl) + FRC 6-scene template. + * + * chg_0012: extends chg_0006 v1 (lms_course / lms_enrollment) with + * `lms_course_scene` table + `progress_scene_ids JSONB` column on + * lms_enrollment. + * + * Scene lifecycle: + * POST /courses (admin) → creates course + scenes + * GET /courses/:courseId/scenes (any) → list scenes ordered + * GET /courses/:courseId/scenes/:sceneId/render (any) → scene-specific payload + * POST /scenes/:sceneId/grade (any) → quiz only: returns score 0..1 + * POST /scenes/:sceneId/complete (any) → append sceneId to progress (idempotent) + * POST /courses/from-frc-template (admin) → 6 simulation scenes (FRC S1-S6) + */ + +export type SceneType = 'slide' | 'quiz' | 'simulation' | 'pbl'; + +export interface SceneRow { + id: string; + course_id: string; + scene_type: SceneType; + payload_json: string; + order_index: number; + created_at: string; +} + +export interface CreateCourseWithScenesDto { + code: string; + name: string; + credits?: number; + instructor?: string; + scenes?: Array<{ + scene_type: SceneType; + payload: Record; + order_index: number; + }>; +} + +export interface QuizQuestion { + id: string; + type: 'choice' | 'short'; + prompt: string; + options?: string[]; + answer?: string; // for choice: the correct option text + keywords?: string[]; // for short: keywords (each = 1 / keywords.length) +} + +const FRC_TEMPLATE_SCENES: Array<{ + title: string; + embed_url: string; + description: string; +}> = [ + { + title: 'DID + TDS 联合身份验证', + embed_url: 'http://127.0.0.1:30000/exp/admin/iframe/frc-s1-sim-did-tds-match', + description: '3 银行 DID 建立 + TDS 合约 hash 匹配', + }, + { + title: 'PSI 求三方交集', + embed_url: 'http://127.0.0.1:30000/exp/admin/iframe/frc-s2-sim-psi-intersection', + description: '3 行黑名单 PSI 私有不泄露非交集', + }, + { + title: 'Paillier 同态求和', + embed_url: 'http://127.0.0.1:30000/exp/admin/iframe/frc-s3-sim-paillier-sum', + description: '3 行风险特征同态加密求和', + }, + { + title: 'Threshold 2-of-3 签名', + embed_url: 'http://127.0.0.1:30000/exp/admin/iframe/frc-s4-sim-threshold-sig', + description: 'Shamir 2-of-3 阈值签名重构', + }, + { + title: 'ABAC 联合风控策略', + embed_url: 'http://127.0.0.1:30000/exp/admin/iframe/frc-s5-sim-abac-policy', + description: '角色 + 区域 + 时段 ABAC 鉴权', + }, + { + title: '审计链 HMAC 验证', + embed_url: 'http://127.0.0.1:30000/exp/admin/iframe/frc-s6-sim-audit-chain', + description: '6 步流程 HMAC 链完整', + }, +]; + +@Injectable() +export class LmsV2Service { + constructor(private readonly courses: CoursesService) {} + + // ----------------------------------------------------------------- + // Create course with scenes (admin only — guarded in controller) + // ----------------------------------------------------------------- + async createCourseWithScenes( + dto: CreateCourseWithScenesDto, + ): Promise<{ course: any; scenes: SceneRow[] }> { + if (!dto?.code || !dto?.name) { + throw new BadRequestException('code / name are required'); + } + // 1) Create course via v1 CoursesService (handles UNIQUE check + 409) + let course; + try { + course = await this.courses.create({ + code: dto.code, + name: dto.name, + credits: dto.credits, + instructor: dto.instructor, + }); + } catch (e: any) { + // CoursesService throws BadRequestException on duplicate; convert to 409 + const msg = e?.message ?? ''; + if (msg.includes('already exists')) { + throw new ConflictException('DUPLICATE_COURSE_CODE'); + } + throw e; + } + + // 2) Insert scenes (if any) + const scenes: SceneRow[] = []; + if (dto.scenes && dto.scenes.length > 0) { + for (const s of dto.scenes) { + const validated = this.validateScenePayload(s.scene_type, s.payload); + const id = uuidv4(); + const db = getDb(); + await db.query( + `INSERT INTO lms_course_scene (id, course_id, scene_type, payload_json, order_index) + VALUES ($1, $2, $3, $4, $5)`, + [id, course.id, s.scene_type, JSON.stringify(validated), s.order_index], + ); + const created = await this.getScene(id); + if (created) scenes.push(created); + } + } + return { course, scenes }; + } + + // ----------------------------------------------------------------- + // FRC 6-scene template + // ----------------------------------------------------------------- + async createFromFrcTemplate(dto: { + course_code: string; + teacher: string; + }): Promise<{ course: any; scenes: SceneRow[] }> { + if (!dto?.course_code || !dto?.teacher) { + throw new BadRequestException('course_code / teacher are required'); + } + const scenes = FRC_TEMPLATE_SCENES.map((s, i) => ({ + scene_type: 'simulation' as SceneType, + order_index: i + 1, + payload: { title: s.title, embed_url: s.embed_url, description: s.description }, + })); + return this.createCourseWithScenes({ + code: dto.course_code, + name: `${dto.teacher} 老师 · 联邦风控实战(FRC)`, + credits: 4, + instructor: dto.teacher, + scenes, + }); + } + + // ----------------------------------------------------------------- + // List scenes by course + // ----------------------------------------------------------------- + async listScenesByCourse(courseId: string): Promise { + await this.courses.getOrThrow(courseId); + const db = getDb(); + const r = await db.query( + `SELECT id, course_id, scene_type, payload_json, order_index, created_at::text AS created_at + FROM lms_course_scene WHERE course_id = $1 ORDER BY order_index ASC`, + [courseId], + ); + return r.rows; + } + + // ----------------------------------------------------------------- + // Render scene + // ----------------------------------------------------------------- + async renderScene(courseId: string, sceneId: string): Promise { + const scene = await this.getSceneOrThrow(sceneId); + if (scene.course_id !== courseId) { + throw new NotFoundException(`scene ${sceneId} not in course ${courseId}`); + } + const payload = this.parsePayload(scene.payload_json); + + switch (scene.scene_type) { + case 'slide': { + const markdown = String(payload.markdown ?? ''); + const html = renderMiniMD(markdown); + return { + scene_id: scene.id, + scene_type: scene.scene_type, + order_index: scene.order_index, + title: payload.title ?? null, + html, + markdown, // also return raw for e2e to verify node types + }; + } + case 'quiz': { + // Return questions without server-side answer/keywords (client can't peek) + const questions = Array.isArray(payload.questions) ? payload.questions : []; + const sanitized = questions.map((q: any) => ({ + id: q.id, + type: q.type, + prompt: q.prompt, + options: q.options ?? [], + })); + return { + scene_id: scene.id, + scene_type: scene.scene_type, + order_index: scene.order_index, + questions: sanitized, + }; + } + case 'simulation': { + const embedUrl = String(payload.embed_url ?? ''); + if (!embedUrl.startsWith('http://') && !embedUrl.startsWith('https://')) { + throw new BadRequestException('INVALID_EMBED_URL'); + } + return { + scene_id: scene.id, + scene_type: scene.scene_type, + order_index: scene.order_index, + embed_url: embedUrl, + title: payload.title ?? null, + sandbox: String(payload.sandbox ?? 'allow-same-origin'), + height: Number(payload.height ?? 600), + }; + } + case 'pbl': { + throw new NotImplementedException( + 'PBL 场景 v2 实现,当前仅作课程占位', + ); + } + default: { + throw new UnprocessableEntityException('INVALID_SCENE_TYPE'); + } + } + } + + // ----------------------------------------------------------------- + // Grade quiz + // ----------------------------------------------------------------- + async gradeQuiz( + sceneId: string, + answers: Record, + ): Promise<{ score: number; correct_count: number; total_count: number; per_question: any[] }> { + const scene = await this.getSceneOrThrow(sceneId); + if (scene.scene_type !== 'quiz') { + throw new UnprocessableEntityException('INVALID_SCENE_TYPE'); + } + const payload = this.parsePayload(scene.payload_json); + const questions: QuizQuestion[] = Array.isArray(payload.questions) ? payload.questions : []; + if (questions.length === 0) { + return { score: 0, correct_count: 0, total_count: 0, per_question: [] }; + } + + let correct = 0; + const perQuestion: any[] = []; + for (const q of questions) { + const userAns = (answers?.[q.id] ?? '').toString().trim(); + let isRight = false; + if (q.type === 'choice') { + // Choice: exact match (case-sensitive) — keep deterministic for e2e + isRight = !!q.answer && userAns === q.answer; + } else if (q.type === 'short') { + // Short: score = hit_keywords / total_keywords (full credit if any hit) + const keywords: string[] = Array.isArray(q.keywords) ? q.keywords : []; + if (keywords.length === 0) { + isRight = userAns.length > 0; // no rubric → only non-empty counts + } else { + const hit = keywords.filter((k) => userAns.includes(k)).length; + // Per testcases C6: keywords 50% hit = full credit (score=1.0) + // So at >= 50% keywords → 1.0; otherwise 0 + isRight = hit / keywords.length >= 0.5; + } + } + perQuestion.push({ id: q.id, is_right: isRight, user_answer: userAns }); + if (isRight) correct += 1; + } + + const score = correct / questions.length; + return { score, correct_count: correct, total_count: questions.length, per_question: perQuestion }; + } + + // ----------------------------------------------------------------- + // Complete scene (append-only idempotent) + // ----------------------------------------------------------------- + async completeScene( + studentId: string, + courseId: string, + sceneId: string, + ): Promise<{ progress_scene_ids: string[]; progress_count: number }> { + // Verify course + await this.courses.getOrThrow(courseId); + // Verify scene belongs to course + const scene = await this.getSceneOrThrow(sceneId); + if (scene.course_id !== courseId) { + throw new NotFoundException(`scene ${sceneId} not in course ${courseId}`); + } + + const db = getDb(); + // Find the student's enrollment in this course + const enrollRow = await db.query<{ id: string; progress_scene_ids: any }>( + `SELECT id, progress_scene_ids FROM lms_enrollment + WHERE student_id = $1 AND course_id = $2 LIMIT 1`, + [studentId, courseId], + ); + if (enrollRow.rows.length === 0) { + throw new NotFoundException( + `student ${studentId} not enrolled in course ${courseId}`, + ); + } + const enrollmentId = enrollRow.rows[0].id; + // progress_scene_ids may come back as already-parsed JSON object (PGlite) or string + let progress: string[] = []; + const raw = enrollRow.rows[0].progress_scene_ids; + if (Array.isArray(raw)) progress = raw as string[]; + else if (typeof raw === 'string') { + try { progress = JSON.parse(raw); } catch { progress = []; } + } + + // Already-completed → no-op (idempotent) + if (progress.includes(sceneId)) { + return { progress_scene_ids: progress, progress_count: progress.length }; + } + + progress.push(sceneId); + await db.query( + `UPDATE lms_enrollment SET progress_scene_ids = $1::jsonb WHERE id = $2`, + [JSON.stringify(progress), enrollmentId], + ); + return { progress_scene_ids: progress, progress_count: progress.length }; + } + + // ----------------------------------------------------------------- + // Internal helpers + // ----------------------------------------------------------------- + private async getScene(id: string): Promise { + const db = getDb(); + const r = await db.query( + `SELECT id, course_id, scene_type, payload_json, order_index, created_at::text AS created_at + FROM lms_course_scene WHERE id = $1 LIMIT 1`, + [id], + ); + return r.rows[0] ?? null; + } + + private async getSceneOrThrow(id: string): Promise { + const row = await this.getScene(id); + if (!row) throw new NotFoundException(`scene ${id} not found`); + return row; + } + + private parsePayload(s: string): any { + try { return JSON.parse(s); } catch { return {}; } + } + + private validateScenePayload( + sceneType: SceneType, + payload: any, + ): Record { + const allowed: SceneType[] = ['slide', 'quiz', 'simulation', 'pbl']; + if (!allowed.includes(sceneType)) { + throw new UnprocessableEntityException('INVALID_SCENE_TYPE'); + } + const p = payload ?? {}; + if (sceneType === 'simulation') { + const url = String(p.embed_url ?? ''); + if (!url.startsWith('http://') && !url.startsWith('https://')) { + throw new BadRequestException('INVALID_EMBED_URL'); + } + } + if (sceneType === 'slide') { + if (!p.markdown) { + throw new BadRequestException('slide.markdown is required'); + } + } + return p; + } +} + +// ----------------------------------------------------------------- +// MiniMD — minimal Markdown converter +// Supports 5 node types: h1 / h2 / p / ul-li / code +// Illegal nodes are preserved verbatim (no throw, no silent drop). +// Pure function — no new deps, no DOM, no nested state. +// ----------------------------------------------------------------- +export function renderMiniMD(md: string): string { + if (typeof md !== 'string' || md.length === 0) return ''; + const lines = md.split(/\r?\n/); + const out: string[] = []; + let inList = false; + let inCode = false; + let codeBuf: string[] = []; + + const flushList = () => { + if (inList) { + out.push(''); + inList = false; + } + }; + const flushCode = () => { + if (inCode) { + out.push(`
${escapeHtml(codeBuf.join('\n'))}
`); + inCode = false; + codeBuf = []; + } + }; + + for (const rawLine of lines) { + const line = rawLine; + + // Code fence + if (/^```/.test(line)) { + if (inCode) { + flushCode(); + continue; + } + // Opening fence: flush anything else, start code + flushList(); + inCode = true; + codeBuf = []; + continue; + } + if (inCode) { + codeBuf.push(line); + continue; + } + + // H1 + if (/^#\s+/.test(line)) { + flushList(); + out.push(`

${escapeHtml(line.replace(/^#\s+/, ''))}

`); + continue; + } + // H2 + if (/^##\s+/.test(line)) { + flushList(); + out.push(`

${escapeHtml(line.replace(/^##\s+/, ''))}

`); + continue; + } + // List item (supports ` - xxx` nesting by ignoring indent depth for v0) + if (/^\s*-\s+/.test(line)) { + if (!inList) { + out.push('
    '); + inList = true; + } + const text = line.replace(/^\s*-\s+/, ''); + out.push(`
  • ${escapeHtml(text)}
  • `); + continue; + } + // Blank line → paragraph separator + if (/^\s*$/.test(line)) { + flushList(); + // skip; paragraph break will be created when next non-empty line arrives + continue; + } + // Default: paragraph + flushList(); + out.push(`

    ${escapeHtml(line)}

    `); + } + flushCode(); + flushList(); + return out.join('\n'); +} + +function escapeHtml(s: string): string { + return String(s) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} \ No newline at end of file diff --git a/src/backend/src/lms/lms.module.ts b/src/backend/src/lms/lms.module.ts index 4155e3b..1459c06 100644 --- a/src/backend/src/lms/lms.module.ts +++ b/src/backend/src/lms/lms.module.ts @@ -4,12 +4,14 @@ import { CoursesController } from './courses.courses.controller'; import { CoursesService } from './courses.courses.service'; import { EnrollmentsController } from './enrollments.enrollments.controller'; import { EnrollmentsService } from './enrollments.enrollments.service'; +import { LmsV2Controller } from './lms-v2.controller'; +import { LmsV2Service } from './lms-v2.service'; import { StudentsController } from './students.students.controller'; import { StudentsService } from './students.students.service'; @Module({ imports: [AuthModule], - controllers: [StudentsController, CoursesController, EnrollmentsController], - providers: [StudentsService, CoursesService, EnrollmentsService], + controllers: [StudentsController, CoursesController, EnrollmentsController, LmsV2Controller], + providers: [StudentsService, CoursesService, EnrollmentsService, LmsV2Service], }) export class LmsModule {} \ No newline at end of file diff --git a/src/frontend/src/App.tsx b/src/frontend/src/App.tsx index 173912b..1d6b3ce 100644 --- a/src/frontend/src/App.tsx +++ b/src/frontend/src/App.tsx @@ -7,6 +7,10 @@ import Run from './views/Run'; // chg_0007 lite-demo: book + product 通用 CRUD 参考实现 import Book from './views/Book'; import Product from './views/Product'; +// chg_0012 LMS v2: 多场景课程平台(slide/quiz/simulation/pbl + FRC 模板) +import LMSCourseList from './views/LMS/CourseList'; +import LMSCourseDetail from './views/LMS/CourseDetail'; +import LMSSceneRenderer from './views/LMS/SceneRenderer'; export default function App() { return ( @@ -18,6 +22,12 @@ export default function App() { } /> } /> } /> + } /> + } /> + } + /> } /> } /> diff --git a/src/frontend/src/api/lms/client.ts b/src/frontend/src/api/lms/client.ts new file mode 100644 index 0000000..bb4b3d4 --- /dev/null +++ b/src/frontend/src/api/lms/client.ts @@ -0,0 +1,205 @@ +import { AxiosResponse } from 'axios'; +import { client } from '../client'; + +/** + * chg_0012 LMS v2 — multi-scene course platform. + * Path: /api/ssw/dth/lms-v2/... + * Response envelope: {code, msg, data} (see backend action-result.filter.ts). + */ + +export interface CourseRow { + id: string; + code: string; + name: string; + credits: number; + instructor: string | null; + created_at: string; +} + +export interface StudentRow { + id: string; + student_no: string; + name: string; + email: string; + created_at: string; +} + +export interface SceneRow { + id: string; + course_id: string; + scene_type: 'slide' | 'quiz' | 'simulation' | 'pbl'; + payload_json: string; + order_index: number; + created_at: string; +} + +export interface SlideRender { + scene_id: string; + scene_type: 'slide'; + order_index: number; + title: string | null; + html: string; + markdown: string; +} + +export interface QuizQuestionClient { + id: string; + type: 'choice' | 'short'; + prompt: string; + options: string[]; +} + +export interface QuizRender { + scene_id: string; + scene_type: 'quiz'; + order_index: number; + questions: QuizQuestionClient[]; +} + +export interface SimRender { + scene_id: string; + scene_type: 'simulation'; + order_index: number; + embed_url: string; + title: string | null; + sandbox: string; + height: number; +} + +export type SceneRender = SlideRender | QuizRender | SimRender; + +export interface GradeResult { + score: number; + correct_count: number; + total_count: number; + per_question: Array<{ id: string; is_right: boolean; user_answer: string }>; +} + +export interface CompleteResult { + progress_scene_ids: string[]; + progress_count: number; +} + +interface Envelope { + code: number; + msg: string; + data: T; +} + +async function unwrap(p: Promise>>): Promise { + const r = await p; + if (r.data.code !== 200) { + throw new Error(`lms-v2: ${r.data.code} ${r.data.msg}`); + } + return r.data.data; +} + +export function listLmsCourses(): Promise { + // Reuse the v1 admin courses endpoint (same schema) + return unwrap( + client.post>('/ssw/dth/lms/courses'), + ); +} + +export function listStudents(): Promise { + return unwrap(client.post>('/ssw/dth/lms/students')); +} + +export function createCourseWithScenes(input: { + code: string; + name: string; + credits?: number; + instructor?: string; + scenes?: Array<{ + scene_type: 'slide' | 'quiz' | 'simulation' | 'pbl'; + order_index: number; + payload: Record; + }>; +}): Promise<{ course: CourseRow; scenes: SceneRow[] }> { + return unwrap( + client.post>( + '/ssw/dth/lms-v2/courses', + input, + ), + ); +} + +export function createFromFrcTemplate(input: { + course_code: string; + teacher: string; +}): Promise<{ course: CourseRow; scenes: SceneRow[] }> { + return unwrap( + client.post>( + '/ssw/dth/lms-v2/courses/from-frc-template', + input, + ), + ); +} + +export function listScenesByCourse(courseId: string): Promise { + return unwrap( + client.get>( + `/ssw/dth/lms-v2/courses/${courseId}/scenes`, + ), + ); +} + +export function renderScene( + courseId: string, + sceneId: string, +): Promise { + return unwrap( + client.get>( + `/ssw/dth/lms-v2/courses/${courseId}/scenes/${sceneId}/render`, + ), + ); +} + +export function gradeQuiz( + sceneId: string, + answers: Record, +): Promise { + return unwrap( + client.post>( + `/ssw/dth/lms-v2/scenes/${sceneId}/grade`, + { answers }, + ), + ); +} + +export function completeScene( + sceneId: string, + student_id: string, + course_id: string, +): Promise { + return unwrap( + client.post>( + `/ssw/dth/lms-v2/scenes/${sceneId}/complete`, + { student_id, course_id }, + ), + ); +} + +export function enrollStudent( + courseId: string, + studentId: string, +): Promise<{ id: string; student_id: string; course_id: string }> { + // chg_0006 enrollment endpoint + return unwrap( + client.post>( + `/ssw/dth/lms/courses/${courseId}/enroll`, + { student_id: studentId }, + ), + ); +} + +export function listEnrollmentsByStudent( + studentId: string, +): Promise> { + return unwrap( + client.post>>( + `/ssw/dth/lms/students/${studentId}/enrollments`, + {}, + ), + ); +} \ No newline at end of file diff --git a/src/frontend/src/views/LMS/CourseDetail.tsx b/src/frontend/src/views/LMS/CourseDetail.tsx new file mode 100644 index 0000000..8ddd619 --- /dev/null +++ b/src/frontend/src/views/LMS/CourseDetail.tsx @@ -0,0 +1,60 @@ +import { useEffect, useState } from 'react'; +import { useParams, Link } from 'react-router-dom'; +import { + listLmsCourses, + listScenesByCourse, + CourseRow, + SceneRow, +} from '../../api/lms/client'; + +/** + * CourseDetail — shows course info + ordered scene list. + */ +export default function CourseDetail() { + const { courseId } = useParams<{ courseId: string }>(); + const [course, setCourse] = useState(null); + const [scenes, setScenes] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + if (!courseId) return; + setError(null); + Promise.all([listLmsCourses(), listScenesByCourse(courseId)]) + .then(([courses, scenes]) => { + const found = courses.find((c) => c.id === courseId); + if (!found) setError('course not found'); + setCourse(found ?? null); + setScenes(scenes); + }) + .catch((e) => setError(e.message ?? 'load failed')); + }, [courseId]); + + if (!courseId) return
    missing course id
    ; + + return ( +
    + ← 返回课程列表 +

    {course ? course.name : '加载中…'}

    + {course && ( +

    + 课程号:{course.code} · 学分:{course.credits} · 教师: + {course.instructor ?? '—'} +

    + )} + {error &&
    {error}
    } +

    Scene 列表

    + {scenes === null &&

    加载中…

    } + {scenes && scenes.length === 0 &&

    本课程暂无 scene。

    } + {scenes && scenes.length > 0 && ( +
      + {scenes.map((s) => ( +
    1. + {s.scene_type} · order {s.order_index} ·{' '} + 打开 scene +
    2. + ))} +
    + )} +
    + ); +} \ No newline at end of file diff --git a/src/frontend/src/views/LMS/CourseList.tsx b/src/frontend/src/views/LMS/CourseList.tsx new file mode 100644 index 0000000..bdd9866 --- /dev/null +++ b/src/frontend/src/views/LMS/CourseList.tsx @@ -0,0 +1,59 @@ +import { useEffect, useState } from 'react'; +import { Link } from 'react-router-dom'; +import { listLmsCourses, CourseRow } from '../../api/lms/client'; + +/** + * CourseList — LMS v2 course list page (admin or any authenticated user). + * Lists all courses; each links to its detail/scene view. + */ +export default function CourseList() { + const [courses, setCourses] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + setError(null); + listLmsCourses() + .then(setCourses) + .catch((e) => setError(e.message ?? 'load failed')); + }, []); + + return ( +
    +

    LMS 课程列表

    +

    + chg_0012 LMS v2 — 多场景课程平台(slide / quiz / simulation / pbl) +

    + {error && ( +
    {error}
    + )} + {courses === null &&

    加载中…

    } + {courses && courses.length === 0 &&

    暂无课程。

    } + {courses && courses.length > 0 && ( + + + + + + + + + + + + {courses.map((c) => ( + + + + + + + + ))} + +
    课程号课程名学分教师操作
    {c.code}{c.name}{c.credits}{c.instructor ?? '—'} + 查看 scene +
    + )} +
    + ); +} \ No newline at end of file diff --git a/src/frontend/src/views/LMS/PBLScene.tsx b/src/frontend/src/views/LMS/PBLScene.tsx new file mode 100644 index 0000000..03b6866 --- /dev/null +++ b/src/frontend/src/views/LMS/PBLScene.tsx @@ -0,0 +1,41 @@ +/** + * PBLScene — placeholder for Project-Based Learning scenes. + * + * The backend returns HTTP 501 NOT_IMPLEMENTED with the exact message + * "PBL 场景 v2 实现,当前仅作课程占位" (see lms-v2.service.ts renderScene + * case 'pbl'). The frontend copy below mirrors that string so e2e C10 + * can verify both ends agree. + * + * Both the backend exception's `msg` and the JSX placeholder use the same + * source string literal — a future maintainer who updates one without the + * other will fail the C10 assertion. + */ +export const PBL_PLACEHOLDER_MESSAGE = 'PBL 场景 v2 实现,当前仅作课程占位'; + +export default function PBLScene({ + courseId, + sceneId, + message, +}: { + courseId: string; + sceneId: string; + message?: string; +}) { + return ( +
    +

    即将推出

    +

    {message ?? PBL_PLACEHOLDER_MESSAGE}

    +

    + course: {courseId} · scene: {sceneId} +

    +
    + ); +} \ No newline at end of file diff --git a/src/frontend/src/views/LMS/QuizScene.tsx b/src/frontend/src/views/LMS/QuizScene.tsx new file mode 100644 index 0000000..846794f --- /dev/null +++ b/src/frontend/src/views/LMS/QuizScene.tsx @@ -0,0 +1,111 @@ +import { FormEvent, useState } from 'react'; +import { + gradeQuiz, + completeScene, + GradeResult, + QuizRender, +} from '../../api/lms/client'; + +interface Props { + courseId: string; + sceneId: string; + data: QuizRender; +} + +/** + * QuizScene — multiple choice + short answer quiz. + * - On submit: POST /scenes/:id/grade → score 0..1 + * - Then: POST /scenes/:id/complete (append-only, idempotent) + */ +export default function QuizScene({ courseId, sceneId, data }: Props) { + const [answers, setAnswers] = useState>({}); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + function setAnswer(qid: string, val: string) { + setAnswers((a) => ({ ...a, [qid]: val })); + } + + async function onSubmit(e: FormEvent) { + e.preventDefault(); + setSubmitting(true); + setError(null); + try { + const r = await gradeQuiz(sceneId, answers); + setResult(r); + // Best-effort: complete the scene (admin user — student_id needs a real id; + // in the demo we use the first seeded student — admin won't actually + // complete, but the call exercises the endpoint.) + try { + await completeScene(sceneId, '11111111-1111-1111-1111-111111111111', courseId); + } catch { + /* ignore — caller can retry */ + } + } catch (e: any) { + setError(e.message ?? 'grade failed'); + } finally { + setSubmitting(false); + } + } + + return ( +
    +
    + {data.questions.map((q, i) => ( +
    + + Q{i + 1} ({q.type}) + +

    {q.prompt}

    + {q.type === 'choice' && ( +
    + {(q.options ?? []).map((opt) => ( + + ))} +
    + )} + {q.type === 'short' && ( + setAnswer(q.id, e.target.value)} + style={{ width: '100%', padding: 4 }} + /> + )} +
    + ))} + +
    + {error &&
    {error}
    } + {result && ( +
    + score: {result.score.toFixed(2)} ·{' '} + correct: {result.correct_count}/{result.total_count} +
    + )} +
    + ); +} \ No newline at end of file diff --git a/src/frontend/src/views/LMS/SceneRenderer.tsx b/src/frontend/src/views/LMS/SceneRenderer.tsx new file mode 100644 index 0000000..39843fb --- /dev/null +++ b/src/frontend/src/views/LMS/SceneRenderer.tsx @@ -0,0 +1,66 @@ +import { useEffect, useState } from 'react'; +import { useParams, Link } from 'react-router-dom'; +import { renderScene, SceneRender as SceneRenderT } from '../../api/lms/client'; +import SlideScene from './SlideScene'; +import QuizScene from './QuizScene'; +import SimScene from './SimScene'; +import PBLScene from './PBLScene'; + +/** + * SceneRenderer — dispatcher: fetches scene payload from /render, then + * routes to the matching Scene component (slide / quiz / simulation / pbl). + * + * For PBL scene (501 NOT_IMPLEMENTED), the backend throws and the api helper + * propagates an Error — we render PBLScene with a "coming soon" message + * matching the backend's 501 response body text exactly: + * "PBL 场景 v2 实现,当前仅作课程占位" + */ +export default function SceneRenderer() { + const { courseId, sceneId } = useParams<{ + courseId: string; + sceneId: string; + }>(); + const [data, setData] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + if (!courseId || !sceneId) return; + setError(null); + setData(null); + renderScene(courseId, sceneId) + .then(setData) + .catch((e) => setError(e.message ?? 'render failed')); + }, [courseId, sceneId]); + + if (!courseId || !sceneId) { + return
    missing courseId/sceneId
    ; + } + + return ( +
    + ← 返回课程详情 +

    Scene Renderer

    + {error && ( + // Backend returns 501 NOT_IMPLEMENTED for pbl; we surface its msg + + )} + {data && data.scene_type === 'slide' && ( + + )} + {data && data.scene_type === 'quiz' && ( + + )} + {data && data.scene_type === 'simulation' && ( + + )} +
    + ); +} \ No newline at end of file diff --git a/src/frontend/src/views/LMS/SimScene.tsx b/src/frontend/src/views/LMS/SimScene.tsx new file mode 100644 index 0000000..aeef747 --- /dev/null +++ b/src/frontend/src/views/LMS/SimScene.tsx @@ -0,0 +1,28 @@ +import { SimRender } from '../../api/lms/client'; + +/** + * SimScene — iframe-rendered simulation scene. + * Default sandbox: 'allow-same-origin' (server picks it from payload.sandbox). + * The embed_url must start with http(s):// — server validates that on create. + */ +export default function SimScene({ data }: { data: SimRender }) { + return ( +
    + {data.title &&

    {data.title}

    } +