feat(education): complete student core loop delivery
This commit is contained in:
115
docs/education/pilot-acceptance-runbook.md
Normal file
115
docs/education/pilot-acceptance-runbook.md
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
# Education Pilot 验收与回滚手册
|
||||||
|
|
||||||
|
## 1. 范围
|
||||||
|
|
||||||
|
本文覆盖学生核心学习闭环后端的 Pilot 发布、验证、监控和应用回滚。完整 Student Web/H5 源码当前不在本工作区,因此浏览器 E2E、桌面/H5 截图和前端构建验收仍是明确阻塞项,不能以 HTTP 或单元测试替代。
|
||||||
|
|
||||||
|
## 2. Pilot 配置
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
yudao:
|
||||||
|
education:
|
||||||
|
enabled: true
|
||||||
|
catalog-read-enabled: true
|
||||||
|
practice-write-enabled: true
|
||||||
|
pilot-tenant-ids: [<pilot-tenant-id>]
|
||||||
|
catalog-mode: SCALAR_READ
|
||||||
|
scalar:
|
||||||
|
enabled: true
|
||||||
|
base-url: ${EDUCATION_SCALAR_BASE_URL}
|
||||||
|
token: ${EDUCATION_SCALAR_TOKEN}
|
||||||
|
```
|
||||||
|
|
||||||
|
要求:
|
||||||
|
|
||||||
|
- `pilot-tenant-ids` 在 Pilot 环境必须显式配置,不能使用空列表。
|
||||||
|
- Scalar token 只能通过密钥管理或环境变量注入,不写入仓库、日志或测试报告。
|
||||||
|
- 发布前调用管理端 `/admin-api/education/capability`,核对模块、题库读取、练习写入和 Pilot 租户数量。
|
||||||
|
|
||||||
|
## 3. 发布步骤
|
||||||
|
|
||||||
|
1. 备份 Education 相关表,并记录应用版本与数据库版本。
|
||||||
|
2. 执行尚未应用的正向 SQL;不得执行 rollback SQL。
|
||||||
|
3. 先以 `catalog-read-enabled=false`、`practice-write-enabled=false` 部署应用。
|
||||||
|
4. 验证 System、Infra、Member 基础 smoke。
|
||||||
|
5. 仅对 Pilot 租户开启题库读取,完成 Scalar 只读 smoke。
|
||||||
|
6. 对 Pilot 租户开启练习写入,完成会话、答案、交卷、报告、错题和收藏 smoke。
|
||||||
|
7. 观察错误率、延迟和数据库写入后再扩大租户列表。
|
||||||
|
|
||||||
|
## 4. Smoke 清单
|
||||||
|
|
||||||
|
### 基础与身份
|
||||||
|
|
||||||
|
- [ ] 非 Pilot 租户访问题库和练习写入被拒绝。
|
||||||
|
- [ ] Pilot 租户可完成 tenant resolve、Member 登录、refresh、logout 和 Education context。
|
||||||
|
- [ ] 错误 `tenant-id` 被租户安全过滤器拒绝。
|
||||||
|
|
||||||
|
### 核心闭环
|
||||||
|
|
||||||
|
- [ ] 目录及题目只经 RuoYi API 返回,响应不含答案或解析。
|
||||||
|
- [ ] 创建练习后刷新可恢复相同会话、题序和已保存答案。
|
||||||
|
- [ ] 相同答案幂等键重试返回首次结果;旧版本和旧序号被拒绝。
|
||||||
|
- [ ] 交卷只生成一个报告,交卷后答案不可修改。
|
||||||
|
- [ ] 错题投影、错题复习和收藏操作仅对当前学生可见。
|
||||||
|
|
||||||
|
### 隔离
|
||||||
|
|
||||||
|
- [ ] tenant A / student A 不能读取或修改 tenant A / student B 的记录。
|
||||||
|
- [ ] tenant A 不能读取或修改 tenant B 的记录,即使资源 ID 被猜中。
|
||||||
|
- [ ] 对 session、report、wrong question、favorite 分别留存拒绝结果证据。
|
||||||
|
|
||||||
|
## 5. 故障与回滚
|
||||||
|
|
||||||
|
### Scalar 故障
|
||||||
|
|
||||||
|
1. 设置 `catalog-read-enabled=false`,停止新的 Scalar 读取。
|
||||||
|
2. 保持 `enabled=true`,使已有会话、报告、错题和收藏仍可访问。
|
||||||
|
3. 如需冻结新写入,再设置 `practice-write-enabled=false`。
|
||||||
|
4. 验证 Education MySQL 表行数和历史查询均未减少。
|
||||||
|
|
||||||
|
### 练习写入熔断
|
||||||
|
|
||||||
|
设置 `practice-write-enabled=false` 后:
|
||||||
|
|
||||||
|
- 新建练习、保存答案和交卷必须被拒绝;
|
||||||
|
- 当前会话恢复、指定会话读取、报告和报告历史仍应可读;
|
||||||
|
- 不执行清理、归档或 rollback SQL。
|
||||||
|
|
||||||
|
### 应用回滚
|
||||||
|
|
||||||
|
1. 将应用回滚到上一已验证版本。
|
||||||
|
2. 保留所有 Education 表和数据,不执行 `sql/mysql/education/*-rollback.sql`。
|
||||||
|
3. 若旧版本与新 schema 不兼容,保持功能关闭并前滚修复;不得通过删表恢复服务。
|
||||||
|
4. 重新验证 Member 登录、System 租户和 Infra 日志功能。
|
||||||
|
|
||||||
|
> `*-rollback.sql` 是显式数据销毁工具,不是常规应用版本回滚步骤。
|
||||||
|
|
||||||
|
## 6. 可观测性
|
||||||
|
|
||||||
|
发布窗口至少观察:
|
||||||
|
|
||||||
|
- Scalar 请求成功率、4xx/5xx/timeout、P95/P99 延迟;
|
||||||
|
- 练习创建成功/冲突数;
|
||||||
|
- 答案保存成功、幂等重放、版本冲突和旧序号拒绝数;
|
||||||
|
- 交卷成功、并发冲突和事务失败数;
|
||||||
|
- Pilot 租户拒绝数;
|
||||||
|
- JVM、数据库连接池、HTTP 错误率和接口延迟。
|
||||||
|
|
||||||
|
Scalar 日志只能记录脱敏路径、tenant ID、上游 request ID、状态、耗时和错误分类;不得记录 Authorization、Scalar token、学生答案、正确答案或完整响应体。RuoYi access/error log 中的 trace ID 用于关联入口请求;验收时需保存一条从入口日志到 Scalar request ID 的关联证据。
|
||||||
|
|
||||||
|
## 7. 验证命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -pl yudao-module-education -am test
|
||||||
|
mvn -pl yudao-server -am package -DskipTests
|
||||||
|
```
|
||||||
|
|
||||||
|
前端源码归位后还必须执行其 lint、类型检查、测试、生产构建及浏览器 E2E。
|
||||||
|
|
||||||
|
## 8. 已知限制
|
||||||
|
|
||||||
|
- 当前工作区缺少完整 Student Web/H5 前端源码。
|
||||||
|
- 尚不能在本仓库完成浏览器 Network 无直连 Scalar 断言。
|
||||||
|
- 尚不能完成桌面和 H5 视觉截图对比。
|
||||||
|
- 真实 Scalar smoke 依赖部署环境、固定上游版本和有效只读凭据。
|
||||||
|
- Pilot 租户列表属于部署配置,修改后需要按配置刷新机制重新加载或重启应用。
|
||||||
216
docs/education/student-core-learning-loop-prd.md
Normal file
216
docs/education/student-core-learning-loop-prd.md
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
# 恭学教育学生核心学习闭环 PRD
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
当前恭学教育系统基于 RuoYi-Vue-Pro,已经具备成熟的租户、后台用户、会员、鉴权、支付、文件、短信、邮件、站内信、权限、字典、定时任务和审计基础设施,但仓库内尚无生产级教育/题库/学习模块,完整前端源码也尚未纳入当前工作区。
|
||||||
|
|
||||||
|
另一个已经运行的 Scalar API 提供了题库、练习、资料、视频、会员和运营等大量教育接口;用户同时提供了学生学习中心、租户运营后台、平台管理后台的功能原型和效果图。若前端直接接入 Scalar,或在 RuoYi 中再次独立实现身份、会员、支付等基础能力,会形成双鉴权、双租户、双订单和双数据源,造成权限不一致、数据难迁移、跨租户风险以及长期维护成本。
|
||||||
|
|
||||||
|
用户首先需要一个能够真实上线和验证的学生学习核心闭环:学生在正确租户下使用现有账号登录,浏览题库,创建练习,稳定保存答案,提交试卷,查看报告,并继续使用错题本和收藏夹。该闭环需要以 RuoYi 为统一入口和最终数据权威,同时允许尚未迁移的只读题库内容暂时经后端适配层来自 Scalar。实现还必须为后续会员支付、私有资料、视频、租户运营后台和平台治理留出清晰边界,但不能让这些后续范围阻塞第一阶段交付。
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
在 RuoYi-Vue-Pro 中新增独立的 Education 业务模块,以 RuoYi 作为所有前端请求、身份、租户、个人学习数据和未来支付权益的统一边界。学生 Web/H5 和 Vue 3 管理后台只能调用 RuoYi API,不得直接访问 Scalar。
|
||||||
|
|
||||||
|
第一阶段交付以下纵向学习闭环:
|
||||||
|
|
||||||
|
1. 根据访问域名或受控租户参数识别租户。
|
||||||
|
2. 复用现有 Member 登录、短信登录、令牌刷新和退出能力。
|
||||||
|
3. 通过 Education 内部目录/题目接口读取题库;尚未迁移的数据由服务器端 Scalar 防腐适配层转换。
|
||||||
|
4. 在 RuoYi/MySQL 中创建归属于当前学生和租户的练习会话,并固定题目顺序与版本。
|
||||||
|
5. 使用幂等键、客户端序号和服务端版本安全地自动保存答案,支持刷新、断网和请求重试恢复。
|
||||||
|
6. 以原子状态转换提交试卷,保存稳定的评分结果和历史快照。
|
||||||
|
7. 生成练习报告、错题记录、收藏和基础学习进度。
|
||||||
|
8. 通过一个最高层的学生核心闭环 E2E 接缝验收整体行为,并使用较低层测试补足租户隔离、所有权、幂等、并发和 Scalar 契约等不可完全由单条 E2E 覆盖的风险。
|
||||||
|
|
||||||
|
后续阶段在同一模块边界内扩展个人中心、词汇、手册、分数线、AI 推荐、资料、视频、会员支付、权益、租户运营和平台治理,并逐项把 Scalar 内容迁移到 Java/MySQL。
|
||||||
|
|
||||||
|
## User Stories
|
||||||
|
|
||||||
|
1. As a student, I want the application to identify the correct school or tenant from my entry point, so that I enter the right branded learning environment.
|
||||||
|
2. As a student, I want a clear error when no valid tenant can be resolved, so that I do not accidentally sign in to the wrong organization.
|
||||||
|
3. As a student, I want to be blocked when a tenant is disabled, so that the platform does not expose inactive tenant data.
|
||||||
|
4. As a student, I want to sign in with my existing mobile number and password, so that I do not need a separate education account.
|
||||||
|
5. As a student, I want to sign in with an SMS verification code, so that I can recover access without remembering a password.
|
||||||
|
6. As a student, I want supported social or WeChat login methods to keep working, so that education does not replace the platform’s existing authentication options.
|
||||||
|
7. As a student, I want my session to refresh securely, so that a long learning session is not lost when an access token expires.
|
||||||
|
8. As a student, I want to log out from the education application, so that another person using the device cannot access my learning data.
|
||||||
|
9. As a student, I want to return to the page I originally requested after login, so that authentication does not interrupt my intended task.
|
||||||
|
10. As a student, I want the application to display my existing nickname and avatar, so that my education profile is consistent with my member account.
|
||||||
|
11. As a student, I want the application to preserve the tenant context after login, so that subsequent requests cannot drift into another tenant.
|
||||||
|
12. As a student, I want to see a learning home page with a clear entry into the question bank, so that I can start studying quickly.
|
||||||
|
13. As a student, I want to resume an unfinished practice session from the learning home page, so that a refresh or temporary interruption does not discard my work.
|
||||||
|
14. As a student, I want to browse question banks by subject, category, region, major, or other supported catalog dimensions, so that I can find relevant material.
|
||||||
|
15. As a student, I want catalog filters to preserve their selected state while I navigate, so that I can compare and refine content efficiently.
|
||||||
|
16. As a student, I want clear loading, empty, unavailable, and permission-denied states in the catalog, so that I understand why content is not displayed.
|
||||||
|
17. As a student, I want only published and permitted question banks to appear, so that I do not see draft or unauthorized content.
|
||||||
|
18. As a student, I want question counts and practice configuration to be accurate, so that I understand what will be included before starting.
|
||||||
|
19. As a student, I want to create a practice session from selected criteria, so that the server prepares a stable set of questions for me.
|
||||||
|
20. As a student, I want the question order to remain stable throughout a practice session, so that refreshing does not reorder my work.
|
||||||
|
21. As a student, I want historical practice to preserve the version of each question I answered, so that later question edits do not change my old result.
|
||||||
|
22. As a student, I want question content to render correctly on desktop and mobile widths, so that I can learn on either device.
|
||||||
|
23. As a student, I want formulas and rich question content to render correctly, so that mathematical and technical questions remain understandable.
|
||||||
|
24. As a student, I want answer options to be easy to select using touch or mouse, so that answering is efficient and accessible.
|
||||||
|
25. As a student, I want to move to the previous or next question, so that I can navigate the practice naturally.
|
||||||
|
26. As a student, I want an answer-card overview, so that I can see answered, unanswered, and current questions.
|
||||||
|
27. As a student, I want my answer to save automatically, so that I do not lose progress if I leave the page unexpectedly.
|
||||||
|
28. As a student, I want to see whether an answer is saving, saved, retrying, or failed, so that I know whether my progress is safe.
|
||||||
|
29. As a student, I want a failed autosave to retry safely, so that network instability does not create duplicate or corrupted answers.
|
||||||
|
30. As a student, I want an older delayed save request to be rejected rather than overwrite my newer answer, so that request reordering cannot corrupt progress.
|
||||||
|
31. As a student, I want refreshing the page to restore the latest server-accepted answers, so that the server remains the durable source of truth.
|
||||||
|
32. As a student, I want duplicate clicks or requests to have one effective result, so that accidental repetition does not change my practice incorrectly.
|
||||||
|
33. As a student, I want to be prevented from answering a submitted, expired, cancelled, or foreign session, so that session state remains trustworthy.
|
||||||
|
34. As a student, I want correct answers and explanations hidden before submission, so that the practice cannot be cheated through API inspection.
|
||||||
|
35. As a student, I want a confirmation before final submission when unanswered questions remain, so that I can choose whether to review them.
|
||||||
|
36. As a student, I want submitting a practice session to be atomic, so that I never receive a partially scored report.
|
||||||
|
37. As a student, I want repeated submission after a timeout to return the original result, so that I do not create duplicate reports.
|
||||||
|
38. As a student, I want a clear score, correct count, incorrect count, and completion summary after submission, so that I understand my performance.
|
||||||
|
39. As a student, I want question-level result details after submission, so that I can learn from mistakes.
|
||||||
|
40. As a student, I want permitted explanations to appear after submission, so that I can understand the correct reasoning.
|
||||||
|
41. As a student, I want my practice history ordered and paginated, so that I can revisit previous work.
|
||||||
|
42. As a student, I want a report to remain stable even if an administrator later edits a question, so that historical records are auditable.
|
||||||
|
43. As a student, I want incorrectly answered questions added to my wrong-question book, so that I can focus future review.
|
||||||
|
44. As a student, I want repeated mistakes on the same question to increase its error count rather than create duplicate rows, so that the wrong-question book remains useful.
|
||||||
|
45. As a student, I want to mark a wrong question as mastered without deleting its history, so that progress remains visible.
|
||||||
|
46. As a student, I want to create a review practice from wrong questions, so that I can close knowledge gaps.
|
||||||
|
47. As a student, I want to favorite a question, so that I can return to important material later.
|
||||||
|
48. As a student, I want favoriting the same question repeatedly to remain idempotent, so that duplicate actions do not create duplicate records.
|
||||||
|
49. As a student, I want to remove a favorite, so that my collection remains relevant.
|
||||||
|
50. As a student, I want wrong questions and favorites to be paginated and filterable, so that large collections remain manageable.
|
||||||
|
51. As a student, I want another student to be unable to read or mutate my sessions, reports, wrong questions, or favorites, so that my learning data remains private.
|
||||||
|
52. As a student, I want another tenant to be unable to access my tenant’s private question banks or learning records, so that organizations remain isolated.
|
||||||
|
53. As a student, I want a traceable support reference when an upstream content service fails, so that support can investigate without exposing sensitive details.
|
||||||
|
54. As a tenant operator, I want student authentication to reuse the platform’s member system, so that I do not manage duplicate accounts.
|
||||||
|
55. As a tenant operator, I want education data automatically scoped to my tenant, so that I cannot accidentally view another tenant’s students or content.
|
||||||
|
56. As a tenant operator, I want permission-controlled access to future education management screens, so that roles can be assigned through the existing menu and role system.
|
||||||
|
57. As a tenant operator, I want student learning reports to be based on immutable practice snapshots, so that supervision data remains trustworthy.
|
||||||
|
58. As a tenant operator, I want education actions to appear in existing access, error, and operation logs, so that incidents can be investigated centrally.
|
||||||
|
59. As a platform operator, I want public and tenant-owned content represented explicitly, so that public sharing does not require disabling tenant isolation globally.
|
||||||
|
60. As a platform operator, I want Scalar-backed capabilities to be visible through configuration and metrics, so that migration progress and dependency risk are measurable.
|
||||||
|
61. As a platform operator, I want to enable the new learning flow for pilot tenants first, so that production risk is contained.
|
||||||
|
62. As a platform operator, I want independent feature switches for catalog reads, practice creation, payments, private media, and imports, so that failures can be isolated.
|
||||||
|
63. As a platform operator, I want rollback to preserve practice history and idempotency records, so that deployment rollback does not lose student work.
|
||||||
|
64. As a support engineer, I want requests correlated by request or trace ID across RuoYi and Scalar, so that cross-system failures are diagnosable.
|
||||||
|
65. As a support engineer, I want logs to exclude tokens, phone numbers, correct answers, payment secrets, and signed URLs, so that observability does not create a data leak.
|
||||||
|
66. As a developer, I want one internal education contract independent of Scalar DTOs, so that the external provider can be changed or retired safely.
|
||||||
|
67. As a developer, I want Scalar errors translated consistently rather than converted to successful empty data, so that frontend and monitoring behavior is honest.
|
||||||
|
68. As a developer, I want contract tests for the Scalar envelope and errors, so that upstream changes fail before deployment.
|
||||||
|
69. As a developer, I want all personal learning writes to go directly to Java/MySQL, so that there is no dual-write reconciliation problem.
|
||||||
|
70. As a developer, I want existing member, tenant, permission, file, notification, and later payment APIs reused, so that the education module remains focused on education behavior.
|
||||||
|
71. As a developer, I want the education module to expose narrow module APIs, so that other modules do not import its mappers or data objects.
|
||||||
|
72. As a developer, I want schema changes delivered as ordered, reversible or explicitly non-reversible scripts, so that database releases can be operated safely.
|
||||||
|
73. As a QA engineer, I want one high-level E2E scenario to cover the entire student core loop, so that the released experience is tested from the user’s perspective.
|
||||||
|
74. As a QA engineer, I want targeted integration tests for tenant isolation, ownership, idempotency, concurrency, and adapter behavior, so that security and consistency failures are exercised deterministically.
|
||||||
|
75. As a product owner, I want the first release limited to the student core learning loop, so that value can be validated before building every prototype screen.
|
||||||
|
76. As a product owner, I want later membership, payment, private media, tenant operations, and platform governance to fit the same architecture, so that the first release does not become a dead end.
|
||||||
|
77. As a product owner, I want visual acceptance against the supplied concept images on desktop and H5 widths, so that functional completion also meets the intended experience.
|
||||||
|
78. As a product owner, I want incomplete future features clearly labeled rather than represented with mock data, so that release status is transparent.
|
||||||
|
|
||||||
|
## Implementation Decisions
|
||||||
|
|
||||||
|
- RuoYi is the unified application boundary and final source of truth. Frontends will not call Scalar directly.
|
||||||
|
- A new Education business module will own education-specific behavior and data. It will follow the repository’s controller, service, conversion, data-object, mapper, enum, job, and module-API conventions.
|
||||||
|
- The existing Member module will own student credentials, login, token refresh, logout, mobile number, nickname, avatar, level, points, tags, and other generic member data. Education-specific profile data will reference the member ID instead of duplicating account fields.
|
||||||
|
- The existing System module will own tenant administration, admin users, roles, menus, permissions, dictionaries, configuration, notifications, email, SMS, and audit facilities.
|
||||||
|
- The existing Infra module will own file records and storage. Education will own the authorization decision for paid or private resources.
|
||||||
|
- The Pay module will remain disabled during the first student-core release and will be activated in a later payment slice. Education orders and entitlements will be projections linked to Pay orders rather than an independent payment engine.
|
||||||
|
- The first release will activate Member and Education in the Maven reactor and server. Unrelated modules will remain disabled to limit build and runtime scope.
|
||||||
|
- The Scalar integration will be a server-side anti-corruption layer. External DTOs, enum values, pagination, errors, timestamps, identifiers, and metadata will be converted to internal education contracts before reaching services or controllers.
|
||||||
|
- Scalar will initially provide only explicitly approved read-only content capabilities. Student practice sessions, answers, reports, wrong questions, favorites, progress, future orders, entitlements, and private-resource decisions will never be written to Scalar.
|
||||||
|
- Each capability will have an explicit source state such as `SCALAR_READ`, `JAVA_NATIVE`, or `MIGRATED`. The system will not silently fall back between providers.
|
||||||
|
- Scalar failures will be mapped to explicit domain errors. An unavailable upstream must not appear as an empty successful catalog.
|
||||||
|
- Scalar requests will receive tenant context derived from the authenticated server context. The frontend cannot override authorization, tenant, user, or platform identity headers.
|
||||||
|
- Scalar authentication will use an approved server credential or token-exchange mechanism. Forwarding a frontend token is not permitted unless the frozen contract explicitly requires it and it passes security review.
|
||||||
|
- The public student API will use the repository’s existing app API conventions, standard success envelope, and page representation. A compatibility facade may preserve `/api` paths if the restored frontend requires them, but it will delegate to the same services rather than duplicate logic.
|
||||||
|
- Student IDs and tenant IDs for protected resources will be derived from the security context. Request-body user or tenant IDs will not be trusted.
|
||||||
|
- Tenant-scoped education data will use the platform’s tenant-aware base object and database interceptor by default.
|
||||||
|
- Public content will use an explicit ownership scope or public marker. It will not be implemented by broadly disabling the tenant interceptor.
|
||||||
|
- Any tenant bypass will be isolated to a narrow platform service, documented, permission-protected, and covered by cross-tenant tests.
|
||||||
|
- The initial content model will include question banks, hierarchical catalog nodes, questions, options, source identifiers, publication state, content versions, and appropriate tenant-aware indexes.
|
||||||
|
- Correct answers and explanations will be treated as protected fields. Pre-submission student DTOs will not contain them.
|
||||||
|
- A practice session will belong to one tenant and one member. It will include a client-generated session identifier, lifecycle state, content selection, question count, score, timestamps, and a concurrency version.
|
||||||
|
- Starting a practice will freeze the question sequence and version. The system will retain enough snapshot data to keep historical reports stable after content changes.
|
||||||
|
- Answer autosave will require an idempotency key, a client command sequence, and the latest known server session version.
|
||||||
|
- Replaying the same idempotency key with the same request will return the original result. Reusing it for a different payload will return a conflict.
|
||||||
|
- Stale sequence or version updates will be rejected instead of overwriting newer accepted answers.
|
||||||
|
- Session submission will be an atomic, one-way state transition. Retrying a successfully committed submission will return the original result.
|
||||||
|
- Session ownership and active state will be checked in the service layer even when a controller is authenticated.
|
||||||
|
- Wrong questions will use one record per tenant, student, and question, with accumulated error count and mastery state. Marking as mastered will not erase history.
|
||||||
|
- Favorites will use one record per tenant, student, target type, and target ID and will support idempotent add/remove behavior.
|
||||||
|
- Basic learning progress will be stored as reliable aggregates. Expensive trends and summaries may later be calculated asynchronously through the existing job system.
|
||||||
|
- External resource mappings will preserve provider, external resource type, external ID, local ID, source version, synchronization state, and last synchronization time.
|
||||||
|
- Import and synchronization operations will use durable jobs and issue records rather than executing large migrations in a web request.
|
||||||
|
- Database changes will be delivered as ordered education SQL scripts with preconditions, verification queries, rollback SQL where safe, explicit rollback limitations, and lock-impact notes. The project will not pretend that Flyway or Liquibase exists when it does not.
|
||||||
|
- Permission names will follow the established `education:<resource>:<action>` pattern and will be seeded with menus and dictionaries rather than hardcoded only in the frontend.
|
||||||
|
- Stable business state machines will use Java enums and centralized transition validation. Dictionaries will provide configurable display values.
|
||||||
|
- Existing notification templates, mail accounts, SMS services, and in-app notification services will be reused. Education services will provide template codes and parameters rather than implementing a second delivery engine.
|
||||||
|
- Existing API access logs, API error logs, operation logs, login logs, and job logs will be reused. Education will add domain records only where business history must survive general log retention.
|
||||||
|
- Private media will not rely on the generic public and tenant-ignored file download route. A future Education access endpoint will authenticate the caller, validate tenant and resource state, check entitlement or operator permission, issue a short-lived URL, and audit the decision.
|
||||||
|
- The administration frontend will use the restored Vue 3 and Element Plus codebase and its existing request, route, store, permission, layout, form, table, pagination, upload, and theme conventions.
|
||||||
|
- The student frontend will be a responsive Web/H5 experience using the restored production frontend baseline. The static prototype is an acceptance reference, not a replacement architecture.
|
||||||
|
- The first release will cover tenant resolution, authentication shell, question-bank browsing, practice creation, answer autosave and recovery, submission, report, history, wrong questions, and favorites.
|
||||||
|
- Vocabulary, handbook, scorelines, AI recommendations, resources, videos, messages, growth, membership, payments, entitlements, tenant operations, platform governance, and full Scalar retirement will be implemented as later vertical slices.
|
||||||
|
- Feature flags will independently control Scalar catalog reads, Java content reads, practice creation, future payments, private media, imports, and frontend route exposure.
|
||||||
|
- Initial production rollout will use a pilot tenant. The release sequence will expand schema first, deploy disabled code, verify existing modules, enable read paths, then enable learning writes.
|
||||||
|
- Rollback will preserve practice history, reports, idempotency records, future orders, and entitlements. User-specific data will never roll back to Scalar.
|
||||||
|
- Observability will include request/trace ID, tenant, actor, use case, provider, upstream request ID, endpoint, latency, result, practice session, future order/import job, and authorization decision. Sensitive values will be redacted.
|
||||||
|
- The complete frontend sources, exact commits, machine-readable Scalar OpenAPI contract, production database version, Scalar availability expectations, and stable external identifier semantics are prerequisites to implementation.
|
||||||
|
|
||||||
|
## Testing Decisions
|
||||||
|
|
||||||
|
- Tests will assert externally observable behavior rather than private method calls, mapper invocation counts, or implementation-specific object construction.
|
||||||
|
- The primary acceptance seam will be one browser-level student core-loop E2E: resolve tenant, authenticate, browse a question bank, create a practice, save answers, refresh and recover, retry one simulated failed save, submit, inspect the report, and visit wrong questions and favorites.
|
||||||
|
- The E2E will also assert that browser network traffic contains no direct request to Scalar.
|
||||||
|
- The E2E will run at both representative desktop and H5 viewport sizes and capture key screenshots for comparison with the supplied concepts.
|
||||||
|
- Authentication tests will reuse the highest existing authentication seams: login endpoints, refresh, logout, and current-member behavior. Education will not unit-test the internals of Member authentication.
|
||||||
|
- Tenant isolation tests will create at least two tenants and overlapping-looking resource identifiers. They will assert that cross-tenant catalog, session, report, wrong-question, favorite, and future media access is denied.
|
||||||
|
- Ownership tests will create at least two students in one tenant and assert that one student cannot read, update, submit, or replay another student’s practice.
|
||||||
|
- Scalar adapter contract tests will cover single-item and paginated envelopes, request metadata, missing optional fields, additional fields, malformed required fields, 400, 401, 403, 404, 409, 429, timeout, and 5xx behavior.
|
||||||
|
- Scalar adapter tests will assert that failures are not converted to empty successes and that sensitive headers are not accepted from callers.
|
||||||
|
- Practice creation tests will assert stable question order, content version retention, ownership, tenant scope, and idempotent handling of a repeated client session identifier.
|
||||||
|
- Autosave tests will assert normal save, identical replay, payload mismatch conflict, stale sequence rejection, stale server-version rejection, delayed request ordering, refresh recovery, inactive-session rejection, and cross-user rejection.
|
||||||
|
- Submission tests will assert atomic scoring, unanswered questions, repeated submission, a timeout after commit, content edits after session creation, and stable historical reports.
|
||||||
|
- Wrong-question tests will assert unique upsert behavior, accumulated error count, mastery without history deletion, and review selection.
|
||||||
|
- Favorite tests will assert idempotent add, idempotent remove, tenant and owner filtering, and pagination.
|
||||||
|
- Response-security tests will assert that pre-submission DTOs and error logs do not contain correct answers or explanations.
|
||||||
|
- Logging tests will focus on the observable presence of correlation fields and absence of secrets, not exact log-line formatting.
|
||||||
|
- Database tests will follow the project’s existing Spring and database test foundations and test real constraints for unique tenant/source mappings, sessions, answers, wrong questions, favorites, and idempotency records.
|
||||||
|
- Build verification will include the Education module with dependencies, the server package with activated Member/Education modules, and the restored frontend’s actual lint, type-check, test, and production build commands.
|
||||||
|
- Smoke tests against the real Scalar deployment will be read-only and version-pinned. They will run before enabling an adapter-backed feature in a target environment.
|
||||||
|
- Release verification will check existing System, Infra, and Member behavior for regressions before enabling any Education feature flag.
|
||||||
|
- Future payment tests will cover duplicate provider callbacks, status polling, browser return URLs that disagree with server state, refund replay, entitlement projection, and refund-access semantics.
|
||||||
|
- Future private-media tests will cover unauthenticated requests, wrong tenant, wrong student, expired entitlement, unpublished asset, short-lived URL generation, and audit records.
|
||||||
|
- Test fixtures will not contain production tokens, real student personal data, provider secrets, or licensed content not approved for test storage.
|
||||||
|
|
||||||
|
## Out of Scope
|
||||||
|
|
||||||
|
- Implementing all 18 student screens in the first release.
|
||||||
|
- Implementing all 34 tenant operations pages in the first release.
|
||||||
|
- Implementing platform tenant lifecycle, plans, subscriptions, public-bank governance, alerts, dunning, invoices, usage, and platform permissions in the first release.
|
||||||
|
- Activating payment, refunds, wallet checkout, membership entitlements, coupons, or activation codes in the first release.
|
||||||
|
- Implementing private paid-resource delivery or protected video playback in the first release.
|
||||||
|
- Implementing vocabulary study, knowledge handbook, historical scorelines, AI school recommendations, downloadable resources, messages, badges, check-in, tasks, or growth features in the first release.
|
||||||
|
- Implementing generic course and lesson management. The supplied product is initially modeled as an exam-prep catalog, question-bank, and practice system.
|
||||||
|
- Replacing the existing Member, System, Pay, Infra, notification, email, SMS, dictionary, role, menu, job, or audit infrastructure.
|
||||||
|
- Direct frontend integration with Scalar or persistence of Scalar/Supabase credentials in browser storage.
|
||||||
|
- Dual-writing personal learning data to RuoYi and Scalar.
|
||||||
|
- Treating the static prototype’s CSS, state management, or mock data as production source code.
|
||||||
|
- Building the production frontend before the complete frontend repository and exact revision are provided.
|
||||||
|
- Claiming DRM, anti-download, watermarking, or advanced video protection without a separately approved media-security design.
|
||||||
|
- Introducing a new migration framework as part of the first Education slice. Database scripts will follow an explicit ordered-script process unless a separate migration decision is approved.
|
||||||
|
- Supporting every database vendor present in the repository in the first release. MySQL is the working assumption pending production confirmation.
|
||||||
|
- Migrating all Scalar content or decommissioning Scalar in the first release.
|
||||||
|
- Sending private student profile data to an AI provider.
|
||||||
|
- Building new email administration APIs unless a later frontend requirement demonstrates that the existing template and account capabilities are insufficient.
|
||||||
|
|
||||||
|
## Further Notes
|
||||||
|
|
||||||
|
- The currently checked-out frontend directories are incomplete. Implementation must pause at the frontend boundary until the production Vue 3 admin and student Web/H5 sources, branches, and exact commits are available.
|
||||||
|
- The Scalar share page is usable for discovery, but a machine-readable OpenAPI JSON or YAML export must be frozen before adapter implementation.
|
||||||
|
- The Scalar contract currently models education mainly as catalog nodes, content entries, question collections, practice blueprints, and questions rather than generic courses and lessons. The domain language in implementation should follow the exam-prep product unless product requirements change.
|
||||||
|
- Known Scalar uncertainties include management question list/detail reads, platform login, payment return and polling semantics, entitlement-resource relationships, answer autosave idempotency, and asynchronous media/import job states.
|
||||||
|
- The existing generic file download route is public and tenant-ignored. It must not be reused as the authorization boundary for paid education content.
|
||||||
|
- The root build currently leaves Member and Pay disabled. Member is required for the first release; Pay should be activated only when the payment slice starts.
|
||||||
|
- The desired execution order for an implementation agent is: module activation, tenant/auth shell, Scalar catalog adapter and contract tests, question read facade, practice creation, autosave and recovery, atomic submission and report, wrong questions/favorites, then full E2E and visual acceptance.
|
||||||
|
- Each implementation change set should contain schema, seed data, domain implementation, tests, API documentation, one complete frontend slice, and verified commands. Mock data or an uncalled endpoint must not be reported as complete.
|
||||||
|
- The issue tracker is the project’s self-hosted Gitea instance. This spec should be labeled `ready-for-agent` once published.
|
||||||
5
tools/education-student-harness/.gitignore
vendored
Normal file
5
tools/education-student-harness/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
artifacts/
|
||||||
|
*.har
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
node_modules/
|
||||||
22
tools/education-student-harness/README.md
Normal file
22
tools/education-student-harness/README.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Browser acceptance harness
|
||||||
|
|
||||||
|
This directory contains a local-only student client and an acceptance suite. It has no lockfile or vendored browser binaries: do not install from the network during normal repository checks.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
From this directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run smoke # dependency-free route smoke test
|
||||||
|
npm run contract # dependency-free HTTP and adapter tests
|
||||||
|
npm run browser:if-available # runs Playwright only when it is already resolvable
|
||||||
|
npm run browser # explicit Playwright command, requires an existing install
|
||||||
|
```
|
||||||
|
|
||||||
|
The browser suite starts `server.js` itself, uses Chromium headlessly, and writes screenshots/traces to `artifacts/` (gitignored). It is intentionally not reported as passing when Playwright or its browser binary is unavailable.
|
||||||
|
|
||||||
|
To run against a real application instead of the deterministic local server, set `BASE_URL`; the server is then not started and the supplied token must be accepted by that application.
|
||||||
|
|
||||||
|
Required coverage includes desktop and H5 viewport core loops, timeout-after-commit with same-key retry, reload/current recovery, submit/report/wrong/favorite, logout, tenant/student isolation, and a request guard installed before navigation. The guard aborts every non-loopback request and any URL containing Scalar, Supabase, or provider-token patterns.
|
||||||
|
|
||||||
|
The dependency-free smoke route uses only Node built-ins and starts the local harness on loopback. It is the minimum check for environments without Playwright.
|
||||||
143
tools/education-student-harness/acceptance.spec.js
Normal file
143
tools/education-student-harness/acceptance.spec.js
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
// @ts-check
|
||||||
|
const { test, expect } = require('@playwright/test');
|
||||||
|
|
||||||
|
const token = (name) => name;
|
||||||
|
const LOOPBACK = /^https?:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?(?:\/|$)/i;
|
||||||
|
const FORBIDDEN = /(scalar|supabase|(?:sk|pk|anon|service)[_-]?key|api[_-]?key|access[_-]?token|provider[_-]?token|anthropic|openai|gemini|deepseek)/i;
|
||||||
|
|
||||||
|
function installRequestGuard(page) {
|
||||||
|
const blocked = [];
|
||||||
|
const allowedViolations = [];
|
||||||
|
page.route('**/*', async (route) => {
|
||||||
|
const url = route.request().url();
|
||||||
|
if (!LOOPBACK.test(url) || FORBIDDEN.test(url)) {
|
||||||
|
blocked.push(`${route.request().method()} ${url}`);
|
||||||
|
await route.abort('blockedbyclient');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await route.continue();
|
||||||
|
});
|
||||||
|
return (expectedBlocked = 0) => {
|
||||||
|
expect(allowedViolations, `unexpected request guard violations: ${allowedViolations.join(', ')}`).toEqual([]);
|
||||||
|
expect(blocked.length, `expected ${expectedBlocked} blocked requests, saw ${blocked.length}`).toBe(expectedBlocked);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function connect(page, student) {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
await page.getByLabel('Local access token').fill(token(student));
|
||||||
|
await page.getByTestId('connect').click();
|
||||||
|
await expect(page.getByTestId('status')).toContainText(/Catalog ready|Session recovered|No active session/);
|
||||||
|
await expect(page.getByTestId('identity-chip')).toContainText(student.includes('tenant-a') ? 'Student A1' : 'Student B1');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start(page) {
|
||||||
|
await page.getByRole('button', { name: 'Start practice' }).click();
|
||||||
|
await expect(page.getByTestId('practice')).toContainText('Q1');
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe('education student core loop', () => {
|
||||||
|
test('request guard aborts external and provider-token URLs', async ({ page }) => {
|
||||||
|
const checkGuard = installRequestGuard(page);
|
||||||
|
await page.goto('/');
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
const blocked = await page.evaluate(async () => {
|
||||||
|
const urls = ['https://example.invalid/scalar', 'https://provider.invalid/api?access_token=redacted'];
|
||||||
|
return Promise.all(urls.map(async (url) => {
|
||||||
|
try { await fetch(url); return false; } catch (_) { return true; }
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
checkGuard(2);
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
test('desktop recovery, submit, wrong questions, and favorites', async ({ page }) => {
|
||||||
|
const checkGuard = installRequestGuard(page);
|
||||||
|
await connect(page, 'tenant-a-student-1');
|
||||||
|
await start(page);
|
||||||
|
|
||||||
|
const requests = [];
|
||||||
|
page.on('request', (request) => {
|
||||||
|
if (request.url().includes('/practice-session/answer')) requests.push(request);
|
||||||
|
});
|
||||||
|
await page.getByLabel('Database').check();
|
||||||
|
await expect(page.getByTestId('practice')).toContainText(/Saved|Ready/);
|
||||||
|
expect(requests.length).toBeGreaterThan(0);
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
await page.getByLabel('Local access token').fill('tenant-a-student-1');
|
||||||
|
await page.getByTestId('connect').click();
|
||||||
|
await expect(page.getByTestId('status')).toContainText(/Session recovered|Catalog ready/);
|
||||||
|
await expect(page.getByTestId('practice')).toContainText('Database');
|
||||||
|
|
||||||
|
await page.getByLabel('Random delay').check();
|
||||||
|
await page.getByLabel('Version check').check();
|
||||||
|
await page.getByRole('button', { name: 'Submit practice' }).click();
|
||||||
|
await expect(page.getByTestId('status')).toContainText(/Submitted|Wrong questions loaded/);
|
||||||
|
await page.getByTestId('load-wrong').click();
|
||||||
|
await expect(page.getByTestId('wrong')).toBeVisible();
|
||||||
|
|
||||||
|
const favorite = await page.evaluate(async () => (await fetch('/app-api/education/favorite/create', { method: 'POST', headers: { Authorization: 'Bearer tenant-a-student-1', 'Content-Type': 'application/json' }, body: JSON.stringify({ targetType: 'QUESTION', targetId: 'q-a-1' }) })).json());
|
||||||
|
expect(favorite.code).toBe(0);
|
||||||
|
await page.getByTestId('load-favorites').click();
|
||||||
|
await expect(page.getByTestId('favorites-list')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('favorites-list')).not.toContainText('No favorites yet.');
|
||||||
|
await page.screenshot({ path: 'artifacts/desktop-core-loop.png', fullPage: true });
|
||||||
|
checkGuard();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('H5 viewport core loop', async ({ page }) => {
|
||||||
|
const checkGuard = installRequestGuard(page);
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await connect(page, 'tenant-a-student-1');
|
||||||
|
await start(page);
|
||||||
|
await page.getByLabel('Controller').check();
|
||||||
|
await expect(page.getByTestId('practice')).toContainText(/Saved|Ready/);
|
||||||
|
await page.screenshot({ path: 'artifacts/h5-core-loop.png', fullPage: true });
|
||||||
|
checkGuard();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('timeout after commit retries with the same idempotency key', async ({ page }) => {
|
||||||
|
const checkGuard = installRequestGuard(page);
|
||||||
|
await connect(page, 'tenant-a-student-1');
|
||||||
|
const result = await page.evaluate(async () => {
|
||||||
|
const create = await fetch('/app-api/education/practice-session/create', {
|
||||||
|
method: 'POST', headers: { Authorization: 'Bearer tenant-a-student-1', 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ clientSessionId: `browser-timeout-${crypto.randomUUID()}`, collectionId: 'col-a-core', questionCount: 1 }),
|
||||||
|
});
|
||||||
|
const session = (await create.json()).data;
|
||||||
|
const body = JSON.stringify({ sessionId: session.id, questionSequence: 1, selectedAnswer: 'A', idempotencyKey: 'same-key', clientSequence: 1, expectedSessionVersion: 0 });
|
||||||
|
const first = await fetch('/app-api/education/practice-session/answer?fault=answer-timeout-after-commit', { method: 'PUT', headers: { Authorization: 'Bearer tenant-a-student-1', 'Content-Type': 'application/json' }, body });
|
||||||
|
const retry = await fetch('/app-api/education/practice-session/answer', { method: 'PUT', headers: { Authorization: 'Bearer tenant-a-student-1', 'Content-Type': 'application/json' }, body });
|
||||||
|
return { first: first.status, retry: retry.status, retryBody: await retry.json() };
|
||||||
|
});
|
||||||
|
expect(result.first).toBe(504);
|
||||||
|
expect(result.retry).toBe(200);
|
||||||
|
expect(result.retryBody.data.selectedAnswer).toBe('A');
|
||||||
|
checkGuard();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('logout clears the in-memory student session', async ({ page }) => {
|
||||||
|
const checkGuard = installRequestGuard(page);
|
||||||
|
await connect(page, 'tenant-a-student-1');
|
||||||
|
await page.getByTestId('logout').click();
|
||||||
|
await expect(page.getByTestId('identity-chip')).toHaveText('Offline');
|
||||||
|
await expect(page.getByTestId('status')).toHaveText('Logged out');
|
||||||
|
checkGuard();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two tenants and two students cannot see each other resources', async ({ page, request }) => {
|
||||||
|
const checkGuard = installRequestGuard(page);
|
||||||
|
const a = await request.get('/app-api/education/context', { headers: { Authorization: 'Bearer tenant-a-student-1' } });
|
||||||
|
const b = await request.get('/app-api/education/context', { headers: { Authorization: 'Bearer tenant-b-student-1' } });
|
||||||
|
expect((await a.json()).data.userId).toBe('student-a1');
|
||||||
|
expect((await b.json()).data.userId).toBe('student-b1');
|
||||||
|
const create = await request.post('/app-api/education/practice-session/create', { headers: { Authorization: 'Bearer tenant-a-student-1' }, data: { clientSessionId: 'isolation', collectionId: 'col-a-core', questionCount: 1 } });
|
||||||
|
const session = (await create.json()).data;
|
||||||
|
const stolen = await request.get(`/app-api/education/practice-session/get?id=${session.id}`, { headers: { Authorization: 'Bearer tenant-a-student-2' } });
|
||||||
|
expect(stolen.status()).toBe(404);
|
||||||
|
const otherTenant = await request.get('/app-api/education/questions/page?collectionId=col-a-core', { headers: { Authorization: 'Bearer tenant-b-student-1' } });
|
||||||
|
expect((await otherTenant.json()).data.list).toHaveLength(0);
|
||||||
|
checkGuard();
|
||||||
|
});
|
||||||
|
});
|
||||||
34
tools/education-student-harness/adapter.js
Normal file
34
tools/education-student-harness/adapter.js
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const API_PREFIX = '/app-api';
|
||||||
|
|
||||||
|
function buildRequest(path, options = {}, accessToken = '') {
|
||||||
|
const headers = {
|
||||||
|
Accept: 'application/json',
|
||||||
|
...(options.body ? { 'Content-Type': 'application/json' } : {}),
|
||||||
|
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
||||||
|
};
|
||||||
|
return { url: `${API_PREFIX}${path}`, options: { ...options, headers } };
|
||||||
|
}
|
||||||
|
|
||||||
|
function answerCommand(session, questionSequence, selectedAnswer, idempotencyKey, clientSequence) {
|
||||||
|
return {
|
||||||
|
sessionId: session.id,
|
||||||
|
questionSequence,
|
||||||
|
selectedAnswer,
|
||||||
|
idempotencyKey,
|
||||||
|
clientSequence,
|
||||||
|
expectedSessionVersion: session.sessionVersion,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyAnswerResult(session, result) {
|
||||||
|
return {
|
||||||
|
...session,
|
||||||
|
sessionVersion: result.sessionVersion,
|
||||||
|
serverVersion: result.serverVersion ?? result.sessionVersion,
|
||||||
|
acceptedSequence: Math.max(session.acceptedSequence || 0, result.acceptedSequence || 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { buildRequest, answerCommand, applyAnswerResult };
|
||||||
19
tools/education-student-harness/adapter.test.js
Normal file
19
tools/education-student-harness/adapter.test.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
'use strict';
|
||||||
|
const assert = require('assert');
|
||||||
|
const { buildRequest, answerCommand, applyAnswerResult } = require('./adapter');
|
||||||
|
|
||||||
|
const request = buildRequest('/education/context', { method: 'GET' }, 'memory-token');
|
||||||
|
assert.equal(request.url, '/app-api/education/context');
|
||||||
|
assert.equal(request.options.headers.Authorization, 'Bearer memory-token');
|
||||||
|
assert.equal(request.options.headers.Accept, 'application/json');
|
||||||
|
|
||||||
|
const session = { id: 's-1', sessionVersion: 4, acceptedSequence: 2 };
|
||||||
|
const command = answerCommand(session, 3, 'B', 'answer-key-1', 3);
|
||||||
|
assert.deepEqual(command, { sessionId: 's-1', questionSequence: 3, selectedAnswer: 'B', idempotencyKey: 'answer-key-1', clientSequence: 3, expectedSessionVersion: 4 });
|
||||||
|
|
||||||
|
const advanced = applyAnswerResult(session, { sessionVersion: 5, acceptedSequence: 3 });
|
||||||
|
assert.equal(advanced.sessionVersion, 5);
|
||||||
|
assert.equal(advanced.acceptedSequence, 3);
|
||||||
|
assert.equal(applyAnswerResult(advanced, { sessionVersion: 6, acceptedSequence: 2 }).acceptedSequence, 3);
|
||||||
|
|
||||||
|
process.stdout.write('education student adapter unit tests passed\n');
|
||||||
45
tools/education-student-harness/app.js
Normal file
45
tools/education-student-harness/app.js
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
const API_PREFIX = '/app-api';
|
||||||
|
let accessToken = '';
|
||||||
|
let tenant = null;
|
||||||
|
let currentSession = null;
|
||||||
|
let clientSequence = 0;
|
||||||
|
let expectedSessionVersion = 0;
|
||||||
|
let saveState = 'idle';
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
const tokenFor = () => accessToken;
|
||||||
|
|
||||||
|
export function buildRequest(path, options = {}, token = accessToken) {
|
||||||
|
const headers = { Accept: 'application/json', ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}) };
|
||||||
|
return { url: `${API_PREFIX}${path}`, options: { ...options, headers } };
|
||||||
|
}
|
||||||
|
export function nextAnswerCommand(session, questionSequence, selectedAnswer, key = crypto.randomUUID()) {
|
||||||
|
return { sessionId: session.id, questionSequence, selectedAnswer, idempotencyKey: key, clientSequence: (session.acceptedSequence || 0) + 1, expectedSessionVersion: session.sessionVersion ?? session.serverVersion ?? 0 };
|
||||||
|
}
|
||||||
|
export function applyAnswerState(session, result) { return { ...session, sessionVersion: result.sessionVersion, serverVersion: result.serverVersion ?? result.sessionVersion, acceptedSequence: Math.max(session.acceptedSequence || 0, result.acceptedSequence || 0) }; }
|
||||||
|
|
||||||
|
function setStatus(text, tone = 'neutral') { $('status').textContent = text; $('status').dataset.tone = tone; $('connection-dot').dataset.tone = tone; }
|
||||||
|
function setSaveState(state, text) { saveState = state; const node = $('save-state'); if (node) { node.textContent = text; node.dataset.state = state; } }
|
||||||
|
function requestId(response) { const id = response.headers.get('x-request-id') || response.headers.get('x-trace-id'); if (id) $('request-id').textContent = `req ${id}`; }
|
||||||
|
function query(params = {}) { const value = new URLSearchParams(); Object.entries(params).forEach(([key, item]) => { if (item !== undefined && item !== null && item !== '') value.set(key, item); }); const result = value.toString(); return result ? `?${result}` : ''; }
|
||||||
|
async function api(path, options = {}) { const request = buildRequest(path, options); const response = await fetch(request.url, request.options); requestId(response); const payload = await response.json().catch(() => ({})); if (!response.ok || (payload.code !== undefined && payload.code !== 0)) { const error = new Error(payload.msg || `Request failed (${response.status})`); error.status = response.status; error.data = payload.data; throw error; } return payload.data; }
|
||||||
|
function escapeHtml(value) { return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' }[c])); }
|
||||||
|
function button(label, handler, className = 'button button-outline') { const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.className = className; b.addEventListener('click', handler); return b; }
|
||||||
|
function renderList(target, list, emptyText, render) { const node = $(target); node.innerHTML = ''; if (!list?.length) { node.innerHTML = `<p class="empty-state">${escapeHtml(emptyText)}</p>`; return; } list.forEach((item) => node.appendChild(render(item))); }
|
||||||
|
function item(title, detail, action) { const node = document.createElement('article'); node.className = 'list-item'; node.innerHTML = `<div><strong>${escapeHtml(title)}</strong><span>${escapeHtml(detail || '')}</span></div>`; if (action) node.append(action); return node; }
|
||||||
|
function renderContext(data) { tenant = data; $('identity-chip').textContent = `${data.tenantName || data.tenantId} · ${data.displayName || data.userId}`; $('context').innerHTML = `<div><dt>Tenant</dt><dd>${escapeHtml(data.tenantName || data.tenantId)}</dd></div><div><dt>Student</dt><dd>${escapeHtml(data.displayName || data.userId)}</dd></div>`; }
|
||||||
|
async function resolveTenant() { return api('/education/tenant/resolve'); }
|
||||||
|
async function connect(event) { event?.preventDefault(); accessToken = $('token').value.trim(); if (!accessToken) { const mobile = $('mobile').value.trim(); const password = $('password').value; if (!mobile || !password) { setStatus('Enter member credentials or a local token', 'bad'); return; } try { setStatus('Logging in…'); const login = await api('/member/auth/login', { method: 'POST', body: JSON.stringify({ mobile, password }) }, ''); accessToken = login?.accessToken || login?.token || ''; } catch (error) { setStatus(error.message, 'bad'); return; } } try { setStatus('Resolving tenant…'); await resolveTenant(); const context = await api('/education/context'); renderContext(context); setStatus('Connected', 'good'); await loadCatalog(); await loadCurrent(); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
async function loginWithCredentials() { return null; }
|
||||||
|
async function logout() { try { if (accessToken) await api('/member/auth/logout', { method: 'POST' }); } catch (_) { /* local memory is still cleared */ } accessToken = ''; tenant = null; currentSession = null; $('identity-chip').textContent = 'Offline'; $('context').innerHTML = '<div><dt>Tenant</dt><dd>Not resolved</dd></div><div><dt>Student</dt><dd>Not authenticated</dd></div>'; renderPractice(); setStatus('Logged out', 'neutral'); }
|
||||||
|
async function loadCatalog() { try { setStatus('Loading catalog…'); const [collections, subjects] = await Promise.all([api('/education/catalog/question-collections?limit=20'), api('/education/catalog/subjects')]); const select = $('subject-filter'); select.innerHTML = '<option value="">All subjects</option>' + (subjects || []).map((x) => `<option value="${escapeHtml(x.id)}">${escapeHtml(x.name || x.title || x.id)}</option>`).join(''); renderList('collections', collections, 'No permitted collections returned.', collectionCard); setStatus('Catalog ready', 'good'); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
function collectionCard(collection) { const article = document.createElement('article'); article.className = 'collection-card'; article.innerHTML = `<div class="collection-index">SET</div><h3>${escapeHtml(collection.name || collection.title || collection.id)}</h3><p>${escapeHtml(collection.description || 'A focused set for your next study pass.')}</p><div class="collection-meta"><span>${collection.questionCount ?? '?'} questions</span><span>${escapeHtml(collection.status || 'available')}</span></div>`; article.append(button('Start practice', () => createPractice(collection), 'button button-dark')); return article; }
|
||||||
|
async function createPractice(collection) { try { setStatus('Creating practice…'); currentSession = await api('/education/practice-session/create', { method: 'POST', body: JSON.stringify({ clientSessionId: crypto.randomUUID(), collectionId: collection.id, questionCount: Math.min(collection.questionCount || 5, 5) }) }); clientSequence = currentSession.acceptedSequence || 0; expectedSessionVersion = currentSession.sessionVersion || 0; renderPractice(); setStatus('Practice active', 'good'); location.hash = 'practice'; } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
async function loadCurrent() { try { setStatus('Checking your session…'); currentSession = await api('/education/practice-session/current'); if (currentSession) { clientSequence = currentSession.acceptedSequence || 0; expectedSessionVersion = currentSession.sessionVersion || 0; } renderPractice(); setStatus(currentSession ? 'Session recovered' : 'No active session', currentSession ? 'good' : 'neutral'); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
function renderPractice() { const host = $('practice'); host.innerHTML = ''; $('state-readout').textContent = currentSession ? `${currentSession.status} · v${currentSession.sessionVersion ?? 0}` : 'No session'; if (!currentSession) { host.innerHTML = '<p class="empty-state">No active session. Start one above.</p>'; return; } const heading = document.createElement('div'); heading.className = 'practice-head'; heading.innerHTML = `<div><span class="session-badge">${escapeHtml(currentSession.status)}</span><strong>${currentSession.questionCount || currentSession.questions?.length || 0} questions</strong></div><span id="save-state" class="save-state" data-state="idle">Ready</span>`; host.append(heading); (currentSession.questions || []).forEach((question) => { const field = document.createElement('fieldset'); field.className = 'question'; field.innerHTML = `<legend><span>Q${question.sequence}</span>${escapeHtml(question.stem || question.questionId)}</legend><div class="options">${(question.options || []).map((option, index) => { const value = String.fromCharCode(65 + index); return `<label class="option"><input type="radio" name="q-${question.sequence}" value="${value}" ${question.selectedAnswer === value ? 'checked' : ''}><span><b>${value}</b>${escapeHtml(option)}</span></label>`; }).join('')}</div>`; field.querySelectorAll('input').forEach((input) => input.addEventListener('change', () => saveAnswer(question, input.value))); host.append(field); }); if (currentSession.status === 'ACTIVE') { const actions = document.createElement('div'); actions.className = 'practice-actions'; actions.append(button('Submit practice', submitPractice, 'button button-dark')); host.append(actions); } }
|
||||||
|
async function saveAnswer(question, answer) { const command = nextAnswerCommand({ ...currentSession, acceptedSequence: clientSequence, sessionVersion: expectedSessionVersion }, question.sequence, answer, question.pendingKey || crypto.randomUUID()); question.pendingKey = command.idempotencyKey; setSaveState('saving', 'Saving…'); try { const result = await api('/education/practice-session/answer', { method: 'PUT', body: JSON.stringify(command) }); currentSession = applyAnswerState(currentSession, result); clientSequence = currentSession.acceptedSequence; expectedSessionVersion = currentSession.sessionVersion; question.selectedAnswer = answer; setSaveState('saved', 'Saved'); $('state-readout').textContent = `${currentSession.status} · v${expectedSessionVersion}`; } catch (error) { if (error.status === 504 || error.status >= 500) { setSaveState('retrying', 'Retrying…'); try { const result = await api('/education/practice-session/answer', { method: 'PUT', body: JSON.stringify(command) }); currentSession = applyAnswerState(currentSession, result); clientSequence = currentSession.acceptedSequence; expectedSessionVersion = currentSession.sessionVersion; question.selectedAnswer = answer; setSaveState('saved', 'Saved after retry'); return; } catch (_) {} } setSaveState('failed', 'Save failed — retry by changing this answer'); setStatus(error.message, 'bad'); } }
|
||||||
|
async function submitPractice() { if (!currentSession) return; try { setStatus('Submitting…'); const result = await api('/education/practice-session/submit', { method: 'POST', body: JSON.stringify({ sessionId: currentSession.id, idempotencyKey: crypto.randomUUID(), expectedSessionVersion }) }); currentSession.status = 'SUBMITTED'; currentSession.sessionVersion = result.sessionVersion || expectedSessionVersion + 1; expectedSessionVersion = currentSession.sessionVersion; renderPractice(); setStatus(`Submitted · ${result.score ?? '—'} correct`, 'good'); await loadWrong(); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
async function loadWrong() { try { const data = await api('/education/wrong-question/page?pageNo=1&pageSize=20'); renderList('wrong', data?.list, 'No wrong questions yet.', (x) => item(x.questionStem || x.stem || x.questionId || x.id, `${x.errorCount ?? 0} ${x.errorCount === 1 ? 'miss' : 'misses'} · ${x.masterStatus || 'unmastered'}`, x.masterStatus !== 'MASTERED' ? button('Mark mastered', () => masterWrong(x), 'button button-small') : null)); setStatus('Wrong questions loaded', 'good'); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
async function masterWrong(wrong) { try { await api('/education/wrong-question/master', { method: 'PUT', body: JSON.stringify({ id: wrong.id }) }); await loadWrong(); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
async function loadFavorites() { try { const data = await api('/education/favorite/page?pageNo=1&pageSize=20'); renderList('favorites-list', data?.list, 'No favorites yet.', (x) => item(x.questionStem || x.stem || x.targetId, x.targetType || 'QUESTION', button('Remove', () => removeFavorite(x), 'button button-small'))); setStatus('Favorites loaded', 'good'); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
async function removeFavorite(favorite) { try { await api('/education/favorite/delete', { method: 'DELETE', body: JSON.stringify({ id: favorite.id, targetId: favorite.targetId }) }); await loadFavorites(); } catch (error) { setStatus(error.message, 'bad'); } }
|
||||||
|
$('auth-form').addEventListener('submit', connect); $('logout').addEventListener('click', logout); $('load-catalog').addEventListener('click', loadCatalog); $('load-current').addEventListener('click', loadCurrent); $('load-wrong').addEventListener('click', loadWrong); $('load-favorites').addEventListener('click', loadFavorites);
|
||||||
26
tools/education-student-harness/docs/test-report.md
Normal file
26
tools/education-student-harness/docs/test-report.md
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Education student harness verification
|
||||||
|
|
||||||
|
Date: 2026-07-28
|
||||||
|
|
||||||
|
## Results
|
||||||
|
|
||||||
|
- PASS — `npm run smoke` (dependency-free loopback route smoke test).
|
||||||
|
- PASS — `npm run contract` (dependency-free HTTP/adapter tests).
|
||||||
|
- PASS — Node syntax checks for all harness JavaScript, including `acceptance.spec.js`.
|
||||||
|
- PASS — `npm run browser:if-available`; Playwright Chromium was installed locally and all six acceptance tests passed.
|
||||||
|
- PASS — `git diff --check` for harness and workflow documentation paths.
|
||||||
|
|
||||||
|
## Security boundary review
|
||||||
|
|
||||||
|
- PASS — harness server binds to `127.0.0.1`; browser guard blocks non-loopback URLs and Scalar/provider-token patterns.
|
||||||
|
- PASS — no downloaded code, vendored binaries, copied prototype assets/classes, or external runtime requests found.
|
||||||
|
- PASS — no Scalar URL/token or provider secret found; screenshots/logs/trace artifacts are gitignored.
|
||||||
|
- PASS — identity and tenant are derived from bearer-token server context; resource ownership checks cover tenant and student.
|
||||||
|
- PASS — pre-submit question responses omit answer and explanation; submitted reports expose them only after submission.
|
||||||
|
- PASS — production backend files were not changed by this harness workflow (existing unrelated production changes remain outside this review scope).
|
||||||
|
|
||||||
|
## Remaining limitations
|
||||||
|
|
||||||
|
- Local deterministic harness browser acceptance is complete; it is not a substitute for the real Student Web/H5 application.
|
||||||
|
- Real Student Web/H5 lint, type checking, tests, production build, and browser E2E remain blocked because those sources are not in this workspace.
|
||||||
|
- Real Scalar read-only smoke, Pilot deployment configuration, production database migration, rollback, and trace-to-upstream observability evidence require a deployment environment and approved credentials.
|
||||||
36
tools/education-student-harness/endpoint-matrix.md
Normal file
36
tools/education-student-harness/endpoint-matrix.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Endpoint matrix
|
||||||
|
|
||||||
|
All paths below are browser-relative `/app-api` routes. The server derives authenticated user and tenant context; the harness never sends those as business fields.
|
||||||
|
|
||||||
|
| Capability | Method | Relative route | Request/query used by harness | Expected data shape | Notes |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| Tenant resolution | GET | `/education/tenant/resolve` | deployment-specific resolver query; not called automatically | tenant resolution object | Use server entry-point/domain policy; do not accept a client tenant override. |
|
||||||
|
| Education context | GET | `/education/context` | none | `{ userId, tenantId, tenantName, displayName }` | Authenticated; verifies active tenant. |
|
||||||
|
| Regions | GET | `/education/catalog/regions` | none | array of region objects | Catalog read gate applies. |
|
||||||
|
| Categories | GET | `/education/catalog/categories` | `subjectId`, optional `nodeId` | array | Catalog read gate applies. |
|
||||||
|
| Subjects | GET | `/education/catalog/subjects` | optional `regionId`, `schoolId`, `majorId`, `moduleId`, `type` | array | Catalog read gate applies. |
|
||||||
|
| Question collections | GET | `/education/catalog/question-collections` | optional `regionId`, `entryId`, `nodeId`, `collectionType`, `limit` | array of collections | Harness uses this as the practice start list. |
|
||||||
|
| Safe question page | GET | `/education/questions/page` | `collectionId`, `pageNo`, `pageSize` | page result `{ list, total }` | Must not include answers or explanations. |
|
||||||
|
| Practice preview | GET | `/education/practice-config/preview` | request VO query fields | preview object | Validates criteria without creating a session. |
|
||||||
|
| Create practice | POST | `/education/practice-session/create` | `{ clientSessionId, collectionId, nodeId?, type?, difficulty?, questionCount }` | practice session | Idempotent by client session ID. |
|
||||||
|
| Current practice | GET | `/education/practice-session/current` | none | session or `null` | Used for refresh recovery. |
|
||||||
|
| Practice by ID | GET | `/education/practice-session/get` | `id` | session | Ownership and tenant checks are server-side. |
|
||||||
|
| Save answer | PUT | `/education/practice-session/answer` | `{ sessionId, questionSequence, selectedAnswer, idempotencyKey, clientSequence, expectedSessionVersion }` | answer save result with version | Idempotent and stale-write resistant. |
|
||||||
|
| Submit practice | POST | `/education/practice-session/submit` | `{ sessionId, idempotencyKey, expectedSessionVersion }` | submit/report result | Atomic one-way transition; safe retry. |
|
||||||
|
| Report | GET | `/education/practice-session/report` | `sessionId` | report with details | Correct answers/explanations only after submit. |
|
||||||
|
| Report history | GET | `/education/practice-session/reports` | `pageNo`, `pageSize` | page result | Current student only. |
|
||||||
|
| Wrong questions | GET | `/education/wrong-question/page` | `pageNo`, `pageSize`, optional `masterStatus` | page result | Current student only. |
|
||||||
|
| Wrong question detail | GET | `/education/wrong-question/get` | `id` | detail | Includes answer/explanation after failure is recorded. |
|
||||||
|
| Mark mastered | PUT | `/education/wrong-question/master` | `id` | boolean | Idempotent. |
|
||||||
|
| Unmark mastered | PUT | `/education/wrong-question/unmaster` | `id` | boolean | Idempotent. |
|
||||||
|
| Wrong-question review | POST | `/education/wrong-question/review-session` | `{ clientSessionId, wrongQuestionIds[] }` | practice session | Server validates ownership. |
|
||||||
|
| Favorites | GET | `/education/favorite/page` | `pageNo`, `pageSize`, optional `targetType` | page result | Current student only. |
|
||||||
|
| Favorite create | POST | `/education/favorite/create` | `{ targetType: 'QUESTION', targetId }` | favorite item | Idempotent. |
|
||||||
|
| Favorite delete | DELETE | `/education/favorite/delete` | `{ id? or targetType, targetId? }` | boolean | Logical/idempotent removal. |
|
||||||
|
| Favorite status | POST | `/education/favorite/status` | `{ questionIds[] }` | `{ questionIds }` | Batch status probe. |
|
||||||
|
|
||||||
|
## Envelope and failures
|
||||||
|
|
||||||
|
The project convention is a common result envelope. Successful payloads are expected under `data`; page payloads generally contain `list` and `total`. Errors should remain errors rather than becoming empty success data. Capture the server-provided request/trace ID for local investigation, but never record authorization headers or full sensitive response bodies.
|
||||||
|
|
||||||
|
The route prefix is intentionally `/app-api`, not a direct Scalar URL. If the local server uses another deployment prefix, adapt the reverse proxy rather than changing the harness to call Scalar.
|
||||||
60
tools/education-student-harness/fixtures/README.md
Normal file
60
tools/education-student-harness/fixtures/README.md
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
# Fixture schemas
|
||||||
|
|
||||||
|
Fixtures are synthetic documentation examples, not default application data and not copies of prototype data. They model the stable fields the harness reads.
|
||||||
|
|
||||||
|
## `context.json`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"userId": 1001,
|
||||||
|
"tenantId": 2001,
|
||||||
|
"tenantName": "Local Pilot School",
|
||||||
|
"displayName": "Local Pilot School"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `question-collection.json`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "collection-local-001",
|
||||||
|
"name": "Synthetic practice collection",
|
||||||
|
"collectionType": "QUESTION_BANK",
|
||||||
|
"questionCount": 3,
|
||||||
|
"status": "PUBLISHED"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `practice-session.json`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 9001,
|
||||||
|
"clientSessionId": "local-session-001",
|
||||||
|
"status": "ACTIVE",
|
||||||
|
"questionCount": 3,
|
||||||
|
"sessionVersion": 1,
|
||||||
|
"questions": [
|
||||||
|
{
|
||||||
|
"sequence": 1,
|
||||||
|
"questionId": "question-local-001",
|
||||||
|
"contentVersion": "v1",
|
||||||
|
"stem": "Synthetic question content",
|
||||||
|
"type": "choice",
|
||||||
|
"options": [{ "label": "A", "content": "Synthetic option" }],
|
||||||
|
"selectedAnswer": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `page.json`
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"list": [],
|
||||||
|
"total": 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not add `correctAnswer`, `explanation`, access tokens, phone numbers, real names, provider identifiers, or licensed question text to pre-submission fixtures. Post-submission report examples may include answer/explanation fields only when explicitly needed to document the permitted post-submit response boundary.
|
||||||
6
tools/education-student-harness/fixtures/context.json
Normal file
6
tools/education-student-harness/fixtures/context.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"userId": 1001,
|
||||||
|
"tenantId": 2001,
|
||||||
|
"tenantName": "Local Pilot School",
|
||||||
|
"displayName": "Local Pilot School"
|
||||||
|
}
|
||||||
4
tools/education-student-harness/fixtures/page.json
Normal file
4
tools/education-student-harness/fixtures/page.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"list": [],
|
||||||
|
"total": 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"id": 9001,
|
||||||
|
"clientSessionId": "local-session-001",
|
||||||
|
"status": "ACTIVE",
|
||||||
|
"questionCount": 3,
|
||||||
|
"sessionVersion": 1,
|
||||||
|
"questions": [
|
||||||
|
{
|
||||||
|
"sequence": 1,
|
||||||
|
"questionId": "question-local-001",
|
||||||
|
"contentVersion": "v1",
|
||||||
|
"stem": "Synthetic question content",
|
||||||
|
"type": "choice",
|
||||||
|
"options": [{ "label": "A", "content": "Synthetic option" }],
|
||||||
|
"selectedAnswer": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"id": "collection-local-001",
|
||||||
|
"name": "Synthetic practice collection",
|
||||||
|
"collectionType": "QUESTION_BANK",
|
||||||
|
"questionCount": 3,
|
||||||
|
"status": "PUBLISHED"
|
||||||
|
}
|
||||||
40
tools/education-student-harness/index.html
Normal file
40
tools/education-student-harness/index.html
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="description" content="Local-only student learning loop browser harness">
|
||||||
|
<title>Study loop / education harness</title>
|
||||||
|
<link rel="stylesheet" href="styles.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar">
|
||||||
|
<a class="wordmark" href="./" aria-label="Study loop home"><span class="wordmark-mark" aria-hidden="true">∴</span><span>study loop</span></a>
|
||||||
|
<div class="topbar-actions"><span id="identity-chip" class="identity-chip" data-testid="identity-chip">Offline</span><button id="logout" class="quiet-button" type="button" data-testid="logout">Log out</button></div>
|
||||||
|
</header>
|
||||||
|
<main class="page-shell">
|
||||||
|
<section class="intro" aria-labelledby="page-title">
|
||||||
|
<div><p class="kicker">STUDENT / CORE LOOP</p><h1 id="page-title">Make one good<br><em>pass through.</em></h1><p class="intro-copy">A small, honest browser seam for finding a set, practising, and learning from the misses.</p></div>
|
||||||
|
<div class="connection-card" aria-live="polite"><span class="connection-dot" id="connection-dot"></span><span id="status" data-testid="status">Not connected</span><span id="request-id" class="request-id">—</span></div>
|
||||||
|
</section>
|
||||||
|
<div class="safety-note" role="note"><span aria-hidden="true">↳</span><span><strong>Local harness.</strong> Calls stay on relative <code>/app-api</code> routes. Your token lives in memory and your tenant is always server-derived.</span></div>
|
||||||
|
|
||||||
|
<section class="auth-panel" id="auth-panel" aria-labelledby="auth-title">
|
||||||
|
<div class="section-label"><span>01</span><span>Entry</span></div>
|
||||||
|
<div class="auth-main"><div><h2 id="auth-title">Connect your study space</h2><p>Resolve the tenant, then use an existing member account.</p></div><form id="auth-form"><label for="mobile">Member login</label><div class="login-fields"><input id="mobile" type="tel" autocomplete="username" placeholder="Mobile number"><input id="password" type="password" autocomplete="current-password" placeholder="Password"><button class="button button-dark" type="submit" data-testid="connect">Log in</button></div><p class="field-help">Local stub accepts <code>tenant-a-student-1</code> as a token below, or use the server's member credentials.</p><label class="token-label" for="token">Local access token <span>(memory only, test fallback)</span></label><input id="token" type="password" autocomplete="off" placeholder="tenant-a-student-1"></form></div>
|
||||||
|
<dl class="identity-grid" id="context" data-testid="context"><div><dt>Tenant</dt><dd>Not resolved</dd></div><div><dt>Student</dt><dd>Not authenticated</dd></div></dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="workspace">
|
||||||
|
<nav class="side-nav" aria-label="Learning loop sections"><p class="nav-title">Your loop</p><a href="#discover" class="nav-link active"><span>01</span>Find a set</a><a href="#practice" class="nav-link"><span>02</span>Practice</a><a href="#review" class="nav-link"><span>03</span>Review</a><a href="#favorites" class="nav-link"><span>04</span>Keep close</a><p class="nav-foot">Server truth<br><span id="state-readout">No session</span></p></nav>
|
||||||
|
<div class="content-column">
|
||||||
|
<section class="content-section" id="discover" aria-labelledby="discover-title"><div class="section-label"><span>02</span><span>Discover</span></div><div class="section-heading"><div><h2 id="discover-title">Choose a question set</h2><p>Only published collections permitted for your space appear here.</p></div><button class="button button-outline" id="load-catalog" type="button" data-testid="load-catalog">Load catalog</button></div><fieldset class="filters"><legend class="sr-only">Catalog filters</legend><label>Subject<select id="subject-filter" data-testid="subject-filter"><option value="">All subjects</option></select></label><label>Category<select id="category-filter"><option value="">All categories</option></select></label></fieldset><div id="collections" class="collection-grid" data-testid="collections"><p class="empty-state">Connect first, then load your permitted sets.</p></div></section>
|
||||||
|
<section class="content-section practice-section" id="active-practice" aria-labelledby="practice-title"><div class="section-label"><span>03</span><span>Active work</span></div><div class="section-heading"><div><h2 id="practice-title">Practice, without losing your place</h2><p id="practice-subtitle">Your latest accepted answer is the durable one.</p></div><button class="button button-outline" id="load-current" type="button" data-testid="reload-current">Reload current</button></div><div id="practice" class="practice-card" data-testid="practice"><p class="empty-state">No active session. Start one above.</p></div></section>
|
||||||
|
<section class="content-section result-grid" id="review"><div class="result-panel"><div class="section-label"><span>04</span><span>Review</span></div><div class="section-heading"><div><h2>Wrong questions</h2><p>Turn a miss into the next pass.</p></div><button class="button button-outline" id="load-wrong" type="button" data-testid="load-wrong">Load</button></div><div id="wrong" class="item-list" data-testid="wrong"><p class="empty-state">Not loaded.</p></div></div><div class="result-panel" id="favorites"><div class="section-label"><span>05</span><span>Keep close</span></div><div class="section-heading"><div><h2>Favorites</h2><p>A short list worth returning to.</p></div><button class="button button-outline" id="load-favorites" type="button" data-testid="load-favorites">Load</button></div><div id="favorites-list" class="item-list" data-testid="favorites-list"><p class="empty-state">Not loaded.</p></div></div></section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<footer><span>Education student harness</span><a href="endpoint-matrix.md">Endpoint matrix</a><a href="fixtures/README.md">Fixture schemas</a></footer>
|
||||||
|
<script type="module" src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
76
tools/education-student-harness/package-lock.json
generated
Normal file
76
tools/education-student-harness/package-lock.json
generated
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
{
|
||||||
|
"name": "education-student-harness",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "education-student-harness",
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.52.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.62.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/@playwright/test/-/test-1.62.0.tgz",
|
||||||
|
"integrity": "sha512-9zOJ6ZQRAena31MpOH9VSzIz8Ou3YJ/wtY/eQm5T2uhfhG7/U3COrMS8xOtUrZrp9OgdmzEnIYODye3nY1VqzA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.62.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.62.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.62.0.tgz",
|
||||||
|
"integrity": "sha512-Z14dG305dgaLu6foB1TXQagFiW8JfSUIUaUuPaKQ6NtBPKF1P/qXcqfh6c6K/icPqdy37JmjbiBXf6JNg6Sylw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.62.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.62.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.62.0.tgz",
|
||||||
|
"integrity": "sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15
tools/education-student-harness/package.json
Normal file
15
tools/education-student-harness/package.json
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "education-student-harness",
|
||||||
|
"private": true,
|
||||||
|
"description": "Offline-safe browser acceptance harness for the education student core loop",
|
||||||
|
"scripts": {
|
||||||
|
"smoke": "node smoke-route.test.js",
|
||||||
|
"contract": "node test.js && node adapter.test.js",
|
||||||
|
"test": "npm run smoke && npm run contract && npm run browser:if-available",
|
||||||
|
"browser": "playwright test",
|
||||||
|
"browser:if-available": "node run-playwright-if-available.js"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.52.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
25
tools/education-student-harness/playwright.config.js
Normal file
25
tools/education-student-harness/playwright.config.js
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
// @ts-check
|
||||||
|
const { defineConfig } = require('@playwright/test');
|
||||||
|
|
||||||
|
const port = process.env.PW_PORT || '4197';
|
||||||
|
|
||||||
|
module.exports = defineConfig({
|
||||||
|
testDir: '.',
|
||||||
|
testMatch: /acceptance\.spec\.js$/,
|
||||||
|
timeout: 30_000,
|
||||||
|
fullyParallel: false,
|
||||||
|
reporter: [['list'], ['json', { outputFile: 'artifacts/playwright-results.json' }]],
|
||||||
|
use: {
|
||||||
|
baseURL: process.env.BASE_URL || `http://127.0.0.1:${port}`,
|
||||||
|
headless: true,
|
||||||
|
trace: 'retain-on-failure',
|
||||||
|
screenshot: 'only-on-failure',
|
||||||
|
video: 'off',
|
||||||
|
},
|
||||||
|
webServer: process.env.BASE_URL ? undefined : {
|
||||||
|
command: `PORT=${port} node server.js`,
|
||||||
|
url: `http://127.0.0.1:${port}`,
|
||||||
|
reuseExistingServer: false,
|
||||||
|
timeout: 10_000,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { spawnSync } = require('child_process');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const cwd = __dirname;
|
||||||
|
const result = spawnSync(process.execPath, ['-e', "try { require.resolve('@playwright/test'); require.resolve('playwright'); } catch (_) { process.exit(2); }"], { cwd, stdio: 'inherit' });
|
||||||
|
if (result.status === 2) {
|
||||||
|
process.stdout.write('Playwright unavailable; dependency-free smoke/contract checks remain available.\n');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
const command = process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
||||||
|
const run = spawnSync(command, ['playwright', 'test'], { cwd, stdio: 'inherit' });
|
||||||
|
process.exit(run.status == null ? 1 : run.status);
|
||||||
80
tools/education-student-harness/server.js
Normal file
80
tools/education-student-harness/server.js
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const http = require('http');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const ROOT = __dirname;
|
||||||
|
const PORT = Number(process.env.PORT || 4173);
|
||||||
|
const HOST = '127.0.0.1';
|
||||||
|
const TOKENS = {
|
||||||
|
'tenant-a-student-1': { tenantId: 'tenant-a', userId: 'student-a1', displayName: 'Student A1', tenantName: 'Tenant Alpha' },
|
||||||
|
'tenant-a-student-2': { tenantId: 'tenant-a', userId: 'student-a2', displayName: 'Student A2', tenantName: 'Tenant Alpha' },
|
||||||
|
'tenant-b-student-1': { tenantId: 'tenant-b', userId: 'student-b1', displayName: 'Student B1', tenantName: 'Tenant Beta' },
|
||||||
|
'tenant-b-student-2': { tenantId: 'tenant-b', userId: 'student-b2', displayName: 'Student B2', tenantName: 'Tenant Beta' },
|
||||||
|
};
|
||||||
|
const QUESTION_DATA = [
|
||||||
|
{ id: 'q-a-1', tenantId: 'tenant-a', collectionId: 'col-a-core', stem: 'Which layer owns the API contract?', type: 'SINGLE', options: ['Controller', 'Database', 'Browser'], answer: 'A', explanation: 'The controller owns the API boundary.' },
|
||||||
|
{ id: 'q-a-2', tenantId: 'tenant-a', collectionId: 'col-a-core', stem: 'What prevents a stale answer overwrite?', type: 'SINGLE', options: ['Version check', 'Random delay', 'Client tenant ID'], answer: 'A', explanation: 'The session version is checked atomically.' },
|
||||||
|
{ id: 'q-a-3', tenantId: 'tenant-a', collectionId: 'col-a-core', stem: 'Which response shape is paged?', type: 'SINGLE', options: ['PageResult', 'String', 'Token'], answer: 'A', explanation: 'PageResult carries list and total.' },
|
||||||
|
{ id: 'q-b-1', tenantId: 'tenant-b', collectionId: 'col-b-core', stem: 'Which boundary carries tenant context?', type: 'SINGLE', options: ['Auth context', 'Question stem', 'Answer text'], answer: 'A', explanation: 'Tenant context comes from authentication.' },
|
||||||
|
{ id: 'q-b-2', tenantId: 'tenant-b', collectionId: 'col-b-core', stem: 'When are explanations visible?', type: 'SINGLE', options: ['After submit', 'Before auth', 'Never'], answer: 'A', explanation: 'Reports reveal explanations after submission.' },
|
||||||
|
{ id: 'q-b-3', tenantId: 'tenant-b', collectionId: 'col-b-core', stem: 'Which operation is idempotent?', type: 'SINGLE', options: ['Save answer', 'Changing tenant', 'Reading a secret'], answer: 'A', explanation: 'Answer saves use an idempotency key.' },
|
||||||
|
];
|
||||||
|
let state;
|
||||||
|
function resetState() {
|
||||||
|
state = { sessions: new Map(), answers: new Map(), reports: new Map(), wrong: new Map(), favorites: new Map(), next: 1 };
|
||||||
|
}
|
||||||
|
resetState();
|
||||||
|
const id = (prefix) => `${prefix}-${state.next++}`;
|
||||||
|
const json = (res, status, data, msg = '成功') => { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Request-Id': id('req') }); res.end(JSON.stringify({ code: status >= 400 ? status : 0, msg, data: data === undefined ? null : data })); };
|
||||||
|
const safe = (q) => { const { answer, explanation, ...result } = q; return result; };
|
||||||
|
const page = (list, query) => ({ list, total: list.length, pageNo: Number(query.get('pageNo') || 1), pageSize: Number(query.get('pageSize') || list.length || 10) });
|
||||||
|
function auth(req) {
|
||||||
|
const match = /^Bearer\s+(.+)$/.exec(req.headers.authorization || '');
|
||||||
|
return match && TOKENS[match[1]] ? TOKENS[match[1]] : null;
|
||||||
|
}
|
||||||
|
function body(req) { return new Promise((resolve, reject) => { let raw = ''; req.on('data', c => { raw += c; if (raw.length > 1024 * 1024) reject(new Error('body too large')); }); req.on('end', () => { try { resolve(raw ? JSON.parse(raw) : {}); } catch { reject(new Error('invalid json')); } }); req.on('error', reject); }); }
|
||||||
|
function fault(req, name) { return req.headers['x-harness-fault'] === name || new URL(req.url, 'http://127.0.0.1').searchParams.get('fault') === name; }
|
||||||
|
function own(ctx, resource) { return resource && resource.tenantId === ctx.tenantId && resource.userId === ctx.userId; }
|
||||||
|
function sessionView(session, submitted = false) { return { id: session.id, clientSessionId: session.clientSessionId, tenantId: session.tenantId, userId: session.userId, collectionId: session.collectionId, status: session.status, sessionVersion: session.version, serverVersion: session.version, acceptedSequence: session.acceptedSequence, questionCount: session.questions.length, questions: session.questions.map(q => ({ sequence: q.sequence, questionId: q.questionId, stem: q.stem, type: q.type, options: q.options, selectedAnswer: q.selectedAnswer || null, ...(submitted ? { answer: q.answer, explanation: q.explanation, isCorrect: q.selectedAnswer === q.answer } : {}) })) }; }
|
||||||
|
function findSession(ctx, value) { const s = state.sessions.get(String(value)); return own(ctx, s) ? s : null; }
|
||||||
|
function findQuestion(ctx, qid) { return QUESTION_DATA.find(q => q.id === String(qid) && q.tenantId === ctx.tenantId); }
|
||||||
|
async function handler(req, res) {
|
||||||
|
const url = new URL(req.url, `http://${HOST}`); const p = url.pathname;
|
||||||
|
if (p === '/' || p === '/index.html') return serve(res, p === '/' ? '/index.html' : p);
|
||||||
|
if (p === '/styles.css' || p === '/app.js' || p.startsWith('/fixtures/') || p === '/endpoint-matrix.md') return serve(res, p);
|
||||||
|
if (!p.startsWith('/app-api/')) return json(res, 404, null, 'Not found');
|
||||||
|
if (p === '/app-api/education/tenant/resolve' && req.method === 'GET') return json(res, 200, { tenantId: 'tenant-a', tenantName: 'Tenant Alpha', resolved: true });
|
||||||
|
const ctx = auth(req); if (!ctx) return json(res, 401, null, '未认证');
|
||||||
|
if (p === '/app-api/education/context' && req.method === 'GET') return json(res, 200, ctx);
|
||||||
|
if (fault(req, 'upstream-failure') && p.includes('/catalog/')) return json(res, 503, null, 'upstream failure');
|
||||||
|
if (p === '/app-api/education/catalog/regions' && req.method === 'GET') return json(res, 200, [{ id: `${ctx.tenantId}-region-1`, name: ctx.tenantName + ' Region' }]);
|
||||||
|
if (p === '/app-api/education/catalog/categories' && req.method === 'GET') return json(res, 200, [{ id: `${ctx.tenantId}-category-1`, name: 'Core' }]);
|
||||||
|
if (p === '/app-api/education/catalog/subjects' && req.method === 'GET') return json(res, 200, [{ id: `${ctx.tenantId}-subject-1`, name: 'Engineering' }]);
|
||||||
|
if (p === '/app-api/education/catalog/question-collections' && req.method === 'GET') return json(res, 200, [{ id: `col-${ctx.tenantId.slice(-1)}-core`, name: 'Core Loop', questionCount: 3, status: 'AVAILABLE', tenantId: ctx.tenantId }]);
|
||||||
|
if (p === '/app-api/education/questions/page' && req.method === 'GET') { const list = QUESTION_DATA.filter(q => q.tenantId === ctx.tenantId && (!url.searchParams.get('collectionId') || q.collectionId === url.searchParams.get('collectionId'))).map(safe); return json(res, 200, page(list, url.searchParams)); }
|
||||||
|
if (p === '/app-api/education/practice-config/preview' && req.method === 'GET') return json(res, 200, { valid: true, questionCount: Math.min(Number(url.searchParams.get('questionCount') || 3), 3), collectionId: url.searchParams.get('collectionId') || `col-${ctx.tenantId.slice(-1)}-core` });
|
||||||
|
if (p === '/app-api/education/practice-session/create' && req.method === 'POST') { const b = await body(req); if (!b.clientSessionId || !b.collectionId) return json(res, 400, null, 'clientSessionId and collectionId required'); const existing = [...state.sessions.values()].find(s => own(ctx, s) && s.clientSessionId === b.clientSessionId); if (existing) return json(res, 200, sessionView(existing)); const qs = QUESTION_DATA.filter(q => q.tenantId === ctx.tenantId && q.collectionId === b.collectionId).slice(0, Math.max(1, Math.min(Number(b.questionCount || 3), 3))); if (!qs.length) return json(res, 404, null, 'collection not found'); const s = { id: id('session'), tenantId: ctx.tenantId, userId: ctx.userId, clientSessionId: b.clientSessionId, collectionId: b.collectionId, status: 'ACTIVE', version: 0, acceptedSequence: 0, questions: qs.map((q, i) => ({ ...q, questionId: q.id, sequence: i + 1, selectedAnswer: null })) }; state.sessions.set(s.id, s); return json(res, 200, sessionView(s)); }
|
||||||
|
if (p === '/app-api/education/practice-session/current' && req.method === 'GET') { const s = [...state.sessions.values()].reverse().find(s => own(ctx, s) && s.status === 'ACTIVE'); return json(res, 200, s ? sessionView(s) : null); }
|
||||||
|
if (p === '/app-api/education/practice-session/get' && req.method === 'GET') { const s = findSession(ctx, url.searchParams.get('id')); return s ? json(res, 200, sessionView(s, s.status === 'SUBMITTED')) : json(res, 404, null, 'session not found'); }
|
||||||
|
if (p === '/app-api/education/practice-session/answer' && req.method === 'PUT') { const b = await body(req); const s = findSession(ctx, b.sessionId); if (!s) return json(res, 404, null, 'session not found'); if (s.status !== 'ACTIVE') return json(res, 409, null, 'submitted session is immutable'); const key = `${s.id}:${b.idempotencyKey}`; if (state.answers.has(key)) { if (fault(req, 'answer-timeout-after-commit')) return json(res, 504, null, 'timeout after commit'); return json(res, 200, state.answers.get(key)); } if (b.expectedSessionVersion !== s.version) return json(res, 409, { currentVersion: s.version }, 'stale session version'); const q = s.questions.find(q => q.sequence === Number(b.questionSequence)); if (!q || typeof b.selectedAnswer !== 'string') return json(res, 400, null, 'invalid answer'); q.selectedAnswer = b.selectedAnswer; s.version++; s.acceptedSequence = Math.max(s.acceptedSequence, Number(b.clientSequence) || 0); const result = { sessionId: s.id, questionSequence: q.sequence, selectedAnswer: q.selectedAnswer, sessionVersion: s.version, serverVersion: s.version, acceptedSequence: s.acceptedSequence }; state.answers.set(key, result); if (fault(req, 'answer-timeout-after-commit')) return json(res, 504, null, 'timeout after commit'); return json(res, 200, result); }
|
||||||
|
if (p === '/app-api/education/practice-session/submit' && req.method === 'POST') { const b = await body(req); const s = findSession(ctx, b.sessionId); if (!s) return json(res, 404, null, 'session not found'); if (s.status === 'SUBMITTED') return json(res, 200, state.reports.get(s.id)); if (b.expectedSessionVersion !== s.version) return json(res, 409, { currentVersion: s.version }, 'stale session version'); if (!b.idempotencyKey) return json(res, 400, null, 'idempotencyKey required'); const details = s.questions.map(q => ({ questionId: q.questionId, selectedAnswer: q.selectedAnswer, answer: q.answer, explanation: q.explanation, isCorrect: q.selectedAnswer === q.answer })); const report = { id: id('report'), sessionId: s.id, score: details.filter(x => x.isCorrect).length, total: details.length, details }; s.status = 'SUBMITTED'; s.version++; state.reports.set(s.id, report); details.filter(x => !x.isCorrect).forEach(x => { const k = `${ctx.tenantId}:${ctx.userId}:${x.questionId}`; const w = state.wrong.get(k) || { id: id('wrong'), tenantId: ctx.tenantId, userId: ctx.userId, questionId: x.questionId, questionStem: QUESTION_DATA.find(q => q.id === x.questionId)?.stem, stem: QUESTION_DATA.find(q => q.id === x.questionId)?.stem, errorCount: 0, masterStatus: 'UNMASTERED' }; w.errorCount++; state.wrong.set(k, w); }); return json(res, 200, { ...report, sessionVersion: s.version, status: s.status }); }
|
||||||
|
if (p === '/app-api/education/practice-session/report' && req.method === 'GET') { const s = findSession(ctx, url.searchParams.get('sessionId')); const r = s && state.reports.get(s.id); return r ? json(res, 200, r) : json(res, 404, null, 'report not found'); }
|
||||||
|
if (p === '/app-api/education/practice-session/reports' && req.method === 'GET') return json(res, 200, page([...state.reports].map(([sid, r]) => { const s = state.sessions.get(sid); return own(ctx, s) ? r : null; }).filter(Boolean), url.searchParams));
|
||||||
|
if (p === '/app-api/education/wrong-question/page' && req.method === 'GET') { let list = [...state.wrong.values()].filter(w => own(ctx, w)); if (url.searchParams.get('masterStatus')) list = list.filter(w => w.masterStatus === url.searchParams.get('masterStatus')); return json(res, 200, page(list, url.searchParams)); }
|
||||||
|
if (p === '/app-api/education/wrong-question/get' && req.method === 'GET') { const w = [...state.wrong.values()].find(w => own(ctx, w) && w.id === url.searchParams.get('id')); const q = w && findQuestion(ctx, w.questionId); return w && q ? json(res, 200, { ...w, questionId: q.id, stem: q.stem, answer: q.answer, explanation: q.explanation }) : json(res, 404, null, 'wrong question not found'); }
|
||||||
|
if ((p.endsWith('/master') || p.endsWith('/unmaster')) && req.method === 'PUT') { const b = await body(req); const w = [...state.wrong.values()].find(w => own(ctx, w) && w.id === String(b.id || url.searchParams.get('id'))); if (!w) return json(res, 404, null, 'wrong question not found'); w.masterStatus = p.endsWith('/master') ? 'MASTERED' : 'UNMASTERED'; return json(res, 200, { mastered: w.masterStatus === 'MASTERED', masterStatus: w.masterStatus }); }
|
||||||
|
if (p === '/app-api/education/wrong-question/review-session' && req.method === 'POST') { const b = await body(req); const ids = Array.isArray(b.wrongQuestionIds) ? b.wrongQuestionIds : []; const qs = ids.map(x => [...state.wrong.values()].find(w => own(ctx, w) && w.id === String(x))).filter(Boolean).map(w => findQuestion(ctx, w.questionId)).filter(Boolean); if (!qs.length) return json(res, 400, null, 'no owned wrong questions'); const s = { id: id('session'), tenantId: ctx.tenantId, userId: ctx.userId, clientSessionId: b.clientSessionId || id('client'), collectionId: 'wrong-review', status: 'ACTIVE', version: 0, acceptedSequence: 0, questions: qs.map((q, i) => ({ ...q, questionId: q.id, sequence: i + 1, selectedAnswer: null })) }; state.sessions.set(s.id, s); return json(res, 200, sessionView(s)); }
|
||||||
|
if (p === '/app-api/education/favorite/page' && req.method === 'GET') return json(res, 200, page([...state.favorites.values()].filter(f => own(ctx, f)), url.searchParams));
|
||||||
|
if (p === '/app-api/education/favorite/create' && req.method === 'POST') { const b = await body(req); const q = findQuestion(ctx, b.targetId); if (b.targetType !== 'QUESTION' || !q) return json(res, 404, null, 'question not found'); const key = `${ctx.tenantId}:${ctx.userId}:${q.id}`; const f = state.favorites.get(key) || { id: id('favorite'), tenantId: ctx.tenantId, userId: ctx.userId, targetType: 'QUESTION', targetId: q.id, questionId: q.id, questionStem: q.stem, status: 'ACTIVE' }; f.status = 'ACTIVE'; state.favorites.set(key, f); return json(res, 200, f); }
|
||||||
|
if (p === '/app-api/education/favorite/delete' && req.method === 'DELETE') { const b = await body(req); const f = [...state.favorites.values()].find(f => own(ctx, f) && (b.id && f.id === String(b.id) || b.targetId && f.targetId === String(b.targetId))); if (f) f.status = 'DELETED'; return json(res, 200, { deleted: true }); }
|
||||||
|
if (p === '/app-api/education/favorite/status' && req.method === 'POST') { const b = await body(req); const ids = (b.questionIds || []).filter(qid => findQuestion(ctx, qid)); return json(res, 200, { questionIds: ids.filter(qid => [...state.favorites.values()].some(f => own(ctx, f) && f.status === 'ACTIVE' && f.targetId === String(qid))) }); }
|
||||||
|
return json(res, 404, null, 'Not found');
|
||||||
|
}
|
||||||
|
function serve(res, requestPath) { const file = path.resolve(ROOT, requestPath.slice(1)); if (!file.startsWith(path.resolve(ROOT)) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return json(res, 404, null, 'Not found'); const types = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json' }; res.writeHead(200, { 'Content-Type': types[path.extname(file)] || 'application/octet-stream' }); fs.createReadStream(file).pipe(res); }
|
||||||
|
function createServer() { return http.createServer((req, res) => { const original = req.headers.authorization; if (original) req.headers.authorization = original; handler(req, res).catch(err => json(res, 400, null, err.message)); }); }
|
||||||
|
if (require.main === module) createServer().listen(PORT, HOST, () => process.stdout.write(`education harness listening on http://${HOST}:${PORT}\n`));
|
||||||
|
module.exports = { createServer, resetState, TOKENS };
|
||||||
38
tools/education-student-harness/smoke-route.test.js
Normal file
38
tools/education-student-harness/smoke-route.test.js
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const assert = require('assert');
|
||||||
|
const http = require('http');
|
||||||
|
const { createServer, resetState } = require('./server');
|
||||||
|
|
||||||
|
const port = Number(process.env.SMOKE_PORT || 4188);
|
||||||
|
function request(method, path, token, body) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const payload = body === undefined ? undefined : JSON.stringify(body);
|
||||||
|
const req = http.request({ hostname: '127.0.0.1', port, path, method, headers: { Authorization: `Bearer ${token}`, ...(payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {}) } }, (res) => {
|
||||||
|
let raw = '';
|
||||||
|
res.on('data', (chunk) => { raw += chunk; });
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(raw) }));
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
if (payload) req.write(payload);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
resetState();
|
||||||
|
const server = createServer().listen(port, '127.0.0.1');
|
||||||
|
try {
|
||||||
|
let response = await request('GET', '/app-api/education/context', 'tenant-a-student-1');
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
assert.equal(response.body.data.tenantId, 'tenant-a');
|
||||||
|
response = await request('GET', '/app-api/education/questions/page?collectionId=col-a-core', 'tenant-a-student-1');
|
||||||
|
assert.equal(response.body.data.list.length, 3);
|
||||||
|
assert.equal(response.body.data.list[0].answer, undefined);
|
||||||
|
process.stdout.write('education student harness smoke route passed\n');
|
||||||
|
} finally {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
main().catch((error) => { process.stderr.write(`${error.stack}\n`); process.exitCode = 1; });
|
||||||
44
tools/education-student-harness/styles.css
Normal file
44
tools/education-student-harness/styles.css
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||||
|
--ink: #18232b; --muted: #5d696f; --paper: #f5f7f4; --panel: #ffffff; --line: #d9e0dc;
|
||||||
|
--leaf: #245c4d; --deep: #183d3d; --gold: #9a6b20; --wash: #e6efea; --danger: #913d38;
|
||||||
|
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: var(--ink); background: var(--paper); line-height: 1.5;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html { scroll-behavior: smooth; }
|
||||||
|
body { margin: 0; min-width: 320px; background: var(--paper); }
|
||||||
|
button, input, select { font: inherit; }
|
||||||
|
button, a { -webkit-tap-highlight-color: transparent; }
|
||||||
|
button { cursor: pointer; }
|
||||||
|
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible { outline: 3px solid #d5a550; outline-offset: 3px; }
|
||||||
|
.topbar { height: 70px; border-bottom: 1px solid var(--line); background: rgba(255,255,255,.82); display: flex; align-items: center; justify-content: space-between; padding: 0 clamp(18px, 5vw, 72px); position: sticky; top: 0; z-index: 3; backdrop-filter: blur(12px); }
|
||||||
|
.wordmark { display: inline-flex; align-items: center; gap: 10px; color: var(--deep); text-decoration: none; font-size: 15px; font-weight: 760; letter-spacing: -.03em; }
|
||||||
|
.wordmark-mark { display: grid; place-items: center; width: 29px; height: 29px; color: white; background: var(--deep); border-radius: 50%; font-size: 21px; line-height: 1; }
|
||||||
|
.topbar-actions { display: flex; align-items: center; gap: 14px; }
|
||||||
|
.identity-chip { padding: 6px 10px; color: var(--leaf); background: var(--wash); border-radius: 99px; font-size: 11px; font-weight: 750; }
|
||||||
|
.quiet-button { border: 0; color: var(--muted); background: transparent; font-size: 12px; padding: 8px; }
|
||||||
|
.page-shell { width: min(1180px, calc(100% - 36px)); margin: 0 auto; padding: 74px 0 80px; }
|
||||||
|
.intro { display: flex; align-items: end; justify-content: space-between; gap: 30px; margin-bottom: 37px; }
|
||||||
|
.kicker, .section-label, .nav-title { margin: 0; color: var(--leaf); font-size: 10px; font-weight: 800; letter-spacing: .17em; text-transform: uppercase; }
|
||||||
|
h1, h2, h3, p { margin-top: 0; } h1 { margin: 13px 0 16px; color: var(--deep); font-family: Georgia, "Times New Roman", serif; font-size: clamp(48px, 7.4vw, 92px); font-weight: 400; letter-spacing: -.07em; line-height: .88; } h1 em { color: var(--gold); font-style: italic; } h2 { margin-bottom: 6px; font-size: 22px; letter-spacing: -.04em; line-height: 1.1; } h3 { margin: 17px 0 8px; font-size: 17px; letter-spacing: -.03em; }
|
||||||
|
.intro-copy { max-width: 395px; margin-bottom: 0; color: var(--muted); font-size: 14px; }
|
||||||
|
.connection-card { display: flex; align-items: center; gap: 9px; align-self: start; min-width: 180px; padding: 11px 13px; border: 1px solid var(--line); background: white; color: var(--leaf); font-size: 12px; font-weight: 700; }
|
||||||
|
.connection-dot { width: 7px; height: 7px; background: var(--gold); border-radius: 50%; } .connection-dot[data-tone="good"] { background: var(--leaf); } .connection-dot[data-tone="bad"] { background: var(--danger); }
|
||||||
|
.request-id { margin-left: auto; color: #a5afb0; font: 10px ui-monospace, monospace; font-weight: 400; }
|
||||||
|
.safety-note { display: flex; gap: 12px; align-items: start; margin-bottom: 32px; padding: 13px 16px; border-left: 2px solid var(--gold); background: #fbf7ee; color: #755f43; font-size: 12px; } .safety-note > span:first-child { color: var(--gold); font-size: 17px; line-height: 1; } code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .9em; }
|
||||||
|
.auth-panel, .content-section { border-top: 1px solid var(--line); padding-top: 18px; } .auth-panel { display: grid; grid-template-columns: 95px 1fr; gap: 35px; padding-bottom: 38px; }
|
||||||
|
.section-label { display: flex; gap: 11px; color: #8c9896; } .section-label span:first-child { color: var(--gold); }
|
||||||
|
.auth-main { display: grid; grid-template-columns: 1fr minmax(300px, 410px); gap: 32px; } .auth-main p, .section-heading p { color: var(--muted); font-size: 13px; margin-bottom: 0; } form label { display: block; margin-bottom: 7px; color: var(--ink); font-size: 12px; font-weight: 700; } form label span { color: var(--muted); font-weight: 400; }
|
||||||
|
.login-fields { display: grid; grid-template-columns: 1fr 1fr auto; gap: 8px; } .token-label { margin-top: 14px; } .token-label + input { max-width: 280px; }
|
||||||
|
.input-action { display: flex; gap: 8px; } input, select { width: 100%; min-height: 42px; border: 1px solid var(--line); border-radius: 2px; color: var(--ink); background: #fbfcfb; padding: 9px 11px; } .field-help { color: var(--muted); font-size: 11px !important; margin-top: 7px !important; }
|
||||||
|
.button { min-height: 39px; padding: 8px 14px; border: 1px solid var(--line); border-radius: 2px; font-size: 12px; font-weight: 750; white-space: nowrap; transition: transform .15s ease, background .15s ease, border-color .15s ease; } .button:hover { transform: translateY(-1px); } .button-dark { border-color: var(--deep); color: white; background: var(--deep); } .button-outline { color: var(--leaf); background: white; } .button-small { min-height: 31px; padding: 5px 9px; font-size: 11px; }
|
||||||
|
.identity-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; grid-column: 2; margin: 26px 0 0; } .identity-grid div { padding: 11px 13px; background: var(--wash); } dt { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: .1em; } dd { margin: 2px 0 0; font-weight: 700; font-size: 13px; }
|
||||||
|
.workspace { display: grid; grid-template-columns: 160px 1fr; gap: 52px; } .side-nav { border-top: 1px solid var(--line); padding-top: 18px; } .nav-title { margin-bottom: 22px; color: #8c9896; } .nav-link { display: flex; gap: 11px; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--line); color: var(--muted); text-decoration: none; font-size: 12px; } .nav-link span { color: var(--gold); font: 10px ui-monospace, monospace; } .nav-link.active { color: var(--deep); font-weight: 750; } .nav-foot { margin-top: 45px; color: #8d9997; font-size: 10px; line-height: 1.6; } .nav-foot span { color: var(--leaf); }
|
||||||
|
.content-column { min-width: 0; } .content-section { margin-bottom: 52px; } .section-heading { display: flex; justify-content: space-between; align-items: end; gap: 20px; margin: 18px 0 20px; } .filters { display: flex; gap: 9px; max-width: 460px; margin-bottom: 20px; } .filters label { flex: 1; color: var(--muted); font-size: 11px; } .filters select { display: block; margin-top: 5px; }
|
||||||
|
.collection-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; } .collection-card { min-height: 225px; display: flex; flex-direction: column; padding: 19px; border: 1px solid var(--line); background: white; } .collection-index { color: var(--gold); font: 10px ui-monospace, monospace; letter-spacing: .15em; } .collection-card p { min-height: 42px; color: var(--muted); font-size: 12px; } .collection-meta { display: flex; justify-content: space-between; margin: auto 0 16px; color: var(--muted); font: 10px ui-monospace, monospace; text-transform: uppercase; }
|
||||||
|
.practice-section { scroll-margin-top: 90px; } .practice-card { border: 1px solid var(--line); background: white; } .empty-state { padding: 25px 0; margin: 0; color: var(--muted); font-size: 13px; } .practice-card > .empty-state, .item-list > .empty-state { padding: 25px; } .practice-head { display: flex; justify-content: space-between; align-items: center; padding: 15px 18px; border-bottom: 1px solid var(--line); } .practice-head strong { margin-left: 10px; font-size: 12px; } .session-badge { color: var(--leaf); font: 10px ui-monospace, monospace; letter-spacing: .1em; } .save-state { color: var(--muted); font-size: 11px; } .save-state[data-state="saved"] { color: var(--leaf); } .save-state[data-state="retrying"] { color: var(--gold); } .save-state[data-state="failed"] { color: var(--danger); }
|
||||||
|
.question { border: 0; border-bottom: 1px solid var(--line); margin: 0; padding: 22px 22px 20px; } .question legend { display: flex; gap: 12px; width: 100%; margin-bottom: 15px; font-size: 14px; font-weight: 700; } .question legend span { color: var(--gold); font: 11px ui-monospace, monospace; } .options { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } .option { position: relative; } .option input { position: absolute; opacity: 0; } .option span { display: block; min-height: 44px; padding: 11px 12px; border: 1px solid var(--line); color: var(--muted); font-size: 12px; cursor: pointer; } .option b { margin-right: 8px; color: var(--gold); font: 11px ui-monospace, monospace; } .option input:checked + span { border-color: var(--leaf); color: var(--deep); background: var(--wash); } .practice-actions { display: flex; justify-content: flex-end; padding: 18px 22px; }
|
||||||
|
.result-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 32px; } .result-panel { min-width: 0; border-top: 1px solid var(--line); padding-top: 18px; } .item-list { border: 1px solid var(--line); background: white; } .list-item { display: flex; justify-content: space-between; align-items: center; gap: 14px; padding: 13px 15px; border-bottom: 1px solid var(--line); } .list-item:last-child { border-bottom: 0; } .list-item strong, .list-item span { display: block; } .list-item strong { font-size: 12px; } .list-item span { margin-top: 3px; color: var(--muted); font-size: 11px; }
|
||||||
|
footer { display: flex; gap: 19px; width: min(1180px, calc(100% - 36px)); margin: 0 auto; padding: 20px 0 30px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11px; } footer a { color: var(--leaf); }
|
||||||
|
@media (max-width: 820px) { .page-shell { padding-top: 48px; } .intro { display: block; } .connection-card { width: fit-content; margin-top: 24px; } .auth-panel { grid-template-columns: 1fr; gap: 18px; } .auth-main { grid-template-columns: 1fr; gap: 22px; } .identity-grid { grid-column: 1; margin-top: 0; } .workspace { grid-template-columns: 1fr; gap: 25px; } .side-nav { display: flex; gap: 14px; align-items: center; overflow-x: auto; } .nav-title, .nav-foot { display: none; } .nav-link { border-bottom: 0; white-space: nowrap; } .collection-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
|
@media (max-width: 560px) { .topbar { height: 62px; padding: 0 17px; } .identity-chip { max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .page-shell { width: min(100% - 28px, 500px); padding-top: 38px; } h1 { font-size: 57px; } .auth-main, .section-heading { display: block; } .section-heading .button { margin-top: 16px; } .login-fields { grid-template-columns: 1fr; } .input-action { display: grid; grid-template-columns: 1fr; } .filters, .options, .collection-grid, .result-grid { grid-template-columns: 1fr; display: grid; max-width: none; } .collection-card { min-height: 0; } .question { padding: 19px 15px; } footer { width: min(100% - 28px, 500px); flex-wrap: wrap; } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } *, *::before, *::after { transition-duration: .01ms !important; } }
|
||||||
30
tools/education-student-harness/test.js
Normal file
30
tools/education-student-harness/test.js
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
const assert = require('assert');
|
||||||
|
const http = require('http');
|
||||||
|
const { createServer, resetState } = require('./server');
|
||||||
|
const port = 4187;
|
||||||
|
let server;
|
||||||
|
function request(method, path, token, body, headers = {}) { return new Promise((resolve, reject) => { const data = body === undefined ? undefined : JSON.stringify(body); const req = http.request({ hostname: '127.0.0.1', port, path, method, headers: { Authorization: `Bearer ${token}`, ...(data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {}), ...headers } }, res => { let raw = ''; res.on('data', c => raw += c); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(raw) })); }); req.on('error', reject); if (data) req.write(data); req.end(); }); }
|
||||||
|
async function run() {
|
||||||
|
resetState(); server = createServer().listen(port, '127.0.0.1');
|
||||||
|
const a1 = 'tenant-a-student-1'; const a2 = 'tenant-a-student-2'; const b1 = 'tenant-b-student-1';
|
||||||
|
let r = await request('GET', '/app-api/education/context', a1); assert.equal(r.body.data.tenantId, 'tenant-a');
|
||||||
|
r = await request('GET', '/app-api/education/questions/page?collectionId=col-a-core', a1); assert.equal(r.body.data.list[0].answer, undefined); assert.equal(r.body.data.list.length, 3);
|
||||||
|
r = await request('POST', '/app-api/education/practice-session/create', a1, { clientSessionId: 'client-1', collectionId: 'col-a-core', questionCount: 3 }); const s = r.body.data;
|
||||||
|
r = await request('POST', '/app-api/education/practice-session/create', a1, { clientSessionId: 'client-1', collectionId: 'col-a-core', questionCount: 3 }); assert.equal(r.body.data.id, s.id);
|
||||||
|
r = await request('PUT', '/app-api/education/practice-session/answer', a1, { sessionId: s.id, questionSequence: 1, selectedAnswer: 'A', idempotencyKey: 'ans-1', clientSequence: 1, expectedSessionVersion: 0 }, { 'X-Harness-Fault': 'answer-timeout-after-commit' }); assert.equal(r.status, 504);
|
||||||
|
r = await request('PUT', '/app-api/education/practice-session/answer', a1, { sessionId: s.id, questionSequence: 1, selectedAnswer: 'A', idempotencyKey: 'ans-1', clientSequence: 1, expectedSessionVersion: 0 }); assert.equal(r.status, 200); assert.equal(r.body.data.selectedAnswer, 'A');
|
||||||
|
r = await request('GET', `/app-api/education/practice-session/get?id=${s.id}`, a1); assert.equal(r.body.data.questions[0].selectedAnswer, 'A');
|
||||||
|
r = await request('PUT', '/app-api/education/practice-session/answer', a1, { sessionId: s.id, questionSequence: 2, selectedAnswer: 'B', idempotencyKey: 'ans-2', clientSequence: 2, expectedSessionVersion: 0 }); assert.equal(r.status, 409);
|
||||||
|
r = await request('PUT', '/app-api/education/practice-session/answer', a1, { sessionId: s.id, questionSequence: 2, selectedAnswer: 'B', idempotencyKey: 'ans-2', clientSequence: 2, expectedSessionVersion: 1 }); assert.equal(r.status, 200);
|
||||||
|
r = await request('GET', `/app-api/education/practice-session/get?id=${s.id}`, a2); assert.equal(r.status, 404);
|
||||||
|
r = await request('POST', '/app-api/education/favorite/create', a1, { targetType: 'QUESTION', targetId: 'q-a-1' }); assert.equal(r.status, 200);
|
||||||
|
r = await request('GET', '/app-api/education/favorite/page', b1); assert.equal(r.body.data.total, 0);
|
||||||
|
r = await request('POST', '/app-api/education/practice-session/submit', a1, { sessionId: s.id, idempotencyKey: 'submit-1', expectedSessionVersion: 2 }); assert.equal(r.status, 200); assert.equal(r.body.data.details[0].answer, 'A');
|
||||||
|
r = await request('POST', '/app-api/education/practice-session/submit', a1, { sessionId: s.id, idempotencyKey: 'submit-1', expectedSessionVersion: 2 }); assert.equal(r.status, 200);
|
||||||
|
r = await request('PUT', '/app-api/education/practice-session/answer', a1, { sessionId: s.id, questionSequence: 1, selectedAnswer: 'C', idempotencyKey: 'ans-3', clientSequence: 3, expectedSessionVersion: 3 }); assert.equal(r.status, 409);
|
||||||
|
r = await request('GET', '/app-api/education/wrong-question/page', a1); assert.equal(r.body.data.total, 2);
|
||||||
|
server.close(); process.stdout.write('education student harness contract tests passed\n');
|
||||||
|
}
|
||||||
|
run().catch(err => { if (server) server.close(); console.error(err); process.exitCode = 1; });
|
||||||
@@ -24,6 +24,26 @@
|
|||||||
|
|
||||||
在 `application.yaml` 或对应 profile 中配置:
|
在 `application.yaml` 或对应 profile 中配置:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
yudao:
|
||||||
|
education:
|
||||||
|
enabled: true
|
||||||
|
# 题库目录与题目读取开关;关闭不会删除已有练习、报告、错题或收藏
|
||||||
|
catalog-read-enabled: true
|
||||||
|
# 练习创建、答案保存、交卷写入开关;关闭后历史会话与报告仍可读取
|
||||||
|
practice-write-enabled: true
|
||||||
|
# Pilot 灰度租户;空列表表示不限制,生产 Pilot 应显式配置目标租户 ID
|
||||||
|
pilot-tenant-ids: [1024]
|
||||||
|
catalog-mode: SCALAR_READ
|
||||||
|
```
|
||||||
|
|
||||||
|
灰度与回滚约束:
|
||||||
|
|
||||||
|
- `enabled=false`:移除 Education HTTP 能力,不执行任何数据删除。
|
||||||
|
- `catalog-read-enabled=false`:停止 Scalar 题库读取;已有会话、报告、错题和收藏仍保存在 MySQL。
|
||||||
|
- `practice-write-enabled=false`:拒绝新建练习、保存答案和交卷;会话恢复、报告与历史查询保持可用。
|
||||||
|
- `pilot-tenant-ids`:非空时仅允许列表内租户使用题库和练习写入能力。
|
||||||
|
- 应用回滚只回滚应用版本或开关;不得执行 `*-rollback.sql`。SQL 回滚脚本仅用于明确的数据销毁场景。
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,21 @@ public class EducationProperties {
|
|||||||
*/
|
*/
|
||||||
private CatalogProviderMode catalogMode = CatalogProviderMode.SCALAR_READ;
|
private CatalogProviderMode catalogMode = CatalogProviderMode.SCALAR_READ;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否允许读取题库目录和题目。关闭后不影响已持久化的练习、报告、错题和收藏数据。
|
||||||
|
*/
|
||||||
|
private boolean catalogReadEnabled = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否允许创建练习、保存答案和交卷。关闭后仍允许读取已有会话和历史报告。
|
||||||
|
*/
|
||||||
|
private boolean practiceWriteEnabled = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Education Pilot 租户 ID 列表。为空表示不限制租户;配置后仅列表内租户可使用学生端能力。
|
||||||
|
*/
|
||||||
|
private List<Long> pilotTenantIds = List.of();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 精确主机名到租户名的映射,用于 DNS 与 system_tenant.websites 不一致的场景。
|
* 精确主机名到租户名的映射,用于 DNS 与 system_tenant.websites 不一致的场景。
|
||||||
* key = 标准化后的主机名(小写、无端口),value = 租户名。
|
* key = 标准化后的主机名(小写、无端口),value = 租户名。
|
||||||
|
|||||||
@@ -37,6 +37,9 @@ public class EducationCapabilityController {
|
|||||||
.version(educationProperties.getVersion())
|
.version(educationProperties.getVersion())
|
||||||
.capabilities(List.of("shell", "catalog", "questions", "practice-preview",
|
.capabilities(List.of("shell", "catalog", "questions", "practice-preview",
|
||||||
"answer-save", "session-submit", "practice-report"))
|
"answer-save", "session-submit", "practice-report"))
|
||||||
|
.catalogReadEnabled(educationProperties.isCatalogReadEnabled())
|
||||||
|
.practiceWriteEnabled(educationProperties.isPracticeWriteEnabled())
|
||||||
|
.pilotTenantCount(educationProperties.getPilotTenantIds().size())
|
||||||
.build();
|
.build();
|
||||||
return success(resp);
|
return success(resp);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,4 +27,13 @@ public class EducationCapabilityRespVO {
|
|||||||
@Schema(description = "支持的能力列表")
|
@Schema(description = "支持的能力列表")
|
||||||
private List<String> capabilities;
|
private List<String> capabilities;
|
||||||
|
|
||||||
|
@Schema(description = "题库读取是否开放", example = "true")
|
||||||
|
private boolean catalogReadEnabled;
|
||||||
|
|
||||||
|
@Schema(description = "练习写入是否开放", example = "true")
|
||||||
|
private boolean practiceWriteEnabled;
|
||||||
|
|
||||||
|
@Schema(description = "Pilot 租户数量;0 表示不限制租户", example = "1")
|
||||||
|
private int pilotTenantCount;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package cn.iocoder.yudao.module.education.controller.app.catalog;
|
package cn.iocoder.yudao.module.education.controller.app.catalog;
|
||||||
|
|
||||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||||
|
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.catalog.vo.*;
|
import cn.iocoder.yudao.module.education.controller.app.catalog.vo.*;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogService;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
@@ -35,6 +37,9 @@ public class CatalogController {
|
|||||||
@Resource
|
@Resource
|
||||||
private CatalogService catalogService;
|
private CatalogService catalogService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private EducationAccessService educationAccessService;
|
||||||
|
|
||||||
@GetMapping("/regions")
|
@GetMapping("/regions")
|
||||||
@Operation(summary = "查询可用地区列表")
|
@Operation(summary = "查询可用地区列表")
|
||||||
public CommonResult<List<CatalogRegionRespVO>> listRegions() {
|
public CommonResult<List<CatalogRegionRespVO>> listRegions() {
|
||||||
@@ -108,12 +113,14 @@ public class CatalogController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 断言当前请求已认证。不从请求参数取值,完全由安全上下文派生。
|
* 校验当前学生的租户上下文和题库读取灰度开关。
|
||||||
*/
|
*/
|
||||||
private void assertAuthenticated() {
|
private void assertAuthenticated() {
|
||||||
if (SecurityFrameworkUtils.getLoginUserId() == null) {
|
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
|
||||||
|
if (loginUser == null || loginUser.getId() == null || loginUser.getTenantId() == null) {
|
||||||
throw exception(UNAUTHORIZED);
|
throw exception(UNAUTHORIZED);
|
||||||
}
|
}
|
||||||
|
educationAccessService.assertCatalogReadAllowed(loginUser.getTenantId());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSess
|
|||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSessionRespVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSessionRespVO;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitReqVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitReqVO;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitRespVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitRespVO;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
@@ -44,6 +45,9 @@ public class PracticeSessionController {
|
|||||||
@Resource
|
@Resource
|
||||||
private PracticeSessionService practiceSessionService;
|
private PracticeSessionService practiceSessionService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private EducationAccessService educationAccessService;
|
||||||
|
|
||||||
// ========== 会话管理 ==========
|
// ========== 会话管理 ==========
|
||||||
|
|
||||||
@PostMapping("/practice-session/create")
|
@PostMapping("/practice-session/create")
|
||||||
@@ -51,7 +55,9 @@ public class PracticeSessionController {
|
|||||||
description = "根据练习配置创建一次持久化练习。同一 clientSessionId 重复调用返回已有会话。"
|
description = "根据练习配置创建一次持久化练习。同一 clientSessionId 重复调用返回已有会话。"
|
||||||
+ "题目顺序由服务端固定,选项不含答案标记。")
|
+ "题目顺序由服务端固定,选项不含答案标记。")
|
||||||
public CommonResult<PracticeSessionRespVO> createSession(@Valid @RequestBody PracticeSessionCreateReqVO reqVO) {
|
public CommonResult<PracticeSessionRespVO> createSession(@Valid @RequestBody PracticeSessionCreateReqVO reqVO) {
|
||||||
return success(practiceSessionService.createPracticeSession(reqVO, getUserId(), getTenantId()));
|
Long tenantId = getTenantId();
|
||||||
|
educationAccessService.assertPracticeWriteAllowed(tenantId);
|
||||||
|
return success(practiceSessionService.createPracticeSession(reqVO, getUserId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/practice-session/current")
|
@GetMapping("/practice-session/current")
|
||||||
@@ -77,7 +83,9 @@ public class PracticeSessionController {
|
|||||||
+ "旧 clientSequence 或旧 expectedSessionVersion 拒绝覆盖。"
|
+ "旧 clientSequence 或旧 expectedSessionVersion 拒绝覆盖。"
|
||||||
+ "客户端根据响应中的 serverVersion 和 acceptedSequence 更新本地状态。")
|
+ "客户端根据响应中的 serverVersion 和 acceptedSequence 更新本地状态。")
|
||||||
public CommonResult<PracticeAnswerRespVO> submitAnswer(@Valid @RequestBody PracticeAnswerReqVO reqVO) {
|
public CommonResult<PracticeAnswerRespVO> submitAnswer(@Valid @RequestBody PracticeAnswerReqVO reqVO) {
|
||||||
return success(practiceSessionService.submitAnswer(reqVO, getUserId(), getTenantId()));
|
Long tenantId = getTenantId();
|
||||||
|
educationAccessService.assertPracticeWriteAllowed(tenantId);
|
||||||
|
return success(practiceSessionService.submitAnswer(reqVO, getUserId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== 交卷提交 ==========
|
// ========== 交卷提交 ==========
|
||||||
@@ -88,7 +96,9 @@ public class PracticeSessionController {
|
|||||||
+ "同一 idempotencyKey + 相同载荷返回首次评分报告(超时重试安全)。"
|
+ "同一 idempotencyKey + 相同载荷返回首次评分报告(超时重试安全)。"
|
||||||
+ "交卷后不可再修改答案。")
|
+ "交卷后不可再修改答案。")
|
||||||
public CommonResult<PracticeSubmitRespVO> submitSession(@Valid @RequestBody PracticeSubmitReqVO reqVO) {
|
public CommonResult<PracticeSubmitRespVO> submitSession(@Valid @RequestBody PracticeSubmitReqVO reqVO) {
|
||||||
return success(practiceSessionService.submitSession(reqVO, getUserId(), getTenantId()));
|
Long tenantId = getTenantId();
|
||||||
|
educationAccessService.assertPracticeWriteAllowed(tenantId);
|
||||||
|
return success(practiceSessionService.submitSession(reqVO, getUserId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== 报告查看 ==========
|
// ========== 报告查看 ==========
|
||||||
@@ -125,7 +135,11 @@ public class PracticeSessionController {
|
|||||||
if (loginUser == null) {
|
if (loginUser == null) {
|
||||||
throw exception(UNAUTHORIZED);
|
throw exception(UNAUTHORIZED);
|
||||||
}
|
}
|
||||||
return loginUser.getTenantId();
|
Long tenantId = loginUser.getTenantId();
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw exception(UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
return tenantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package cn.iocoder.yudao.module.education.controller.app.question;
|
|||||||
|
|
||||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||||
|
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.question.vo.*;
|
import cn.iocoder.yudao.module.education.controller.app.question.vo.*;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogService;
|
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
@@ -38,6 +40,9 @@ public class QuestionController {
|
|||||||
@Resource
|
@Resource
|
||||||
private QuestionCatalogService questionCatalogService;
|
private QuestionCatalogService questionCatalogService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private EducationAccessService educationAccessService;
|
||||||
|
|
||||||
// ========== 题目浏览 ==========
|
// ========== 题目浏览 ==========
|
||||||
|
|
||||||
@GetMapping("/questions/page")
|
@GetMapping("/questions/page")
|
||||||
@@ -98,12 +103,14 @@ public class QuestionController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 断言当前请求已认证。不从请求参数取值,完全由安全上下文派生。
|
* 校验当前学生的租户上下文和题库读取灰度开关。
|
||||||
*/
|
*/
|
||||||
private void assertAuthenticated() {
|
private void assertAuthenticated() {
|
||||||
if (SecurityFrameworkUtils.getLoginUserId() == null) {
|
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
|
||||||
|
if (loginUser == null || loginUser.getId() == null || loginUser.getTenantId() == null) {
|
||||||
throw exception(UNAUTHORIZED);
|
throw exception(UNAUTHORIZED);
|
||||||
}
|
}
|
||||||
|
educationAccessService.assertCatalogReadAllowed(loginUser.getTenantId());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,6 +107,10 @@ public class WrongQuestionController {
|
|||||||
if (loginUser == null) {
|
if (loginUser == null) {
|
||||||
throw exception(UNAUTHORIZED);
|
throw exception(UNAUTHORIZED);
|
||||||
}
|
}
|
||||||
return loginUser.getTenantId();
|
Long tenantId = loginUser.getTenantId();
|
||||||
|
if (tenantId == null) {
|
||||||
|
throw exception(UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
return tenantId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -139,11 +139,20 @@ public interface EducationFavoriteMapper extends BaseMapperX<EducationFavoriteDO
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按 ID 更新 available 标记。
|
* 按 ID、租户和用户更新可用标记,避免调用方遗漏所有权边界。
|
||||||
*
|
*/
|
||||||
* @param id 记录 ID
|
default int updateAvailableByIdAndTenantAndUser(Long id, Long tenantId, Long userId, Boolean available) {
|
||||||
* @param available 源资源是否可用
|
return update(null,
|
||||||
* @return 受影响行数
|
new LambdaUpdateWrapper<EducationFavoriteDO>()
|
||||||
|
.eq(EducationFavoriteDO::getId, id)
|
||||||
|
.eq(EducationFavoriteDO::getTenantId, tenantId)
|
||||||
|
.eq(EducationFavoriteDO::getUserId, userId)
|
||||||
|
.eq(EducationFavoriteDO::getDeleted, false)
|
||||||
|
.set(EducationFavoriteDO::getAvailable, available));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 兼容旧调用方;业务服务应使用带租户和用户的重载。
|
||||||
*/
|
*/
|
||||||
default int updateAvailable(Long id, Boolean available) {
|
default int updateAvailable(Long id, Boolean available) {
|
||||||
return update(null,
|
return update(null,
|
||||||
@@ -151,6 +160,4 @@ public interface EducationFavoriteMapper extends BaseMapperX<EducationFavoriteDO
|
|||||||
.eq(EducationFavoriteDO::getId, id)
|
.eq(EducationFavoriteDO::getId, id)
|
||||||
.set(EducationFavoriteDO::getAvailable, available));
|
.set(EducationFavoriteDO::getAvailable, available));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,8 +16,26 @@ import java.util.List;
|
|||||||
@Mapper
|
@Mapper
|
||||||
public interface PracticeQuestionMapper extends BaseMapperX<PracticeQuestionDO> {
|
public interface PracticeQuestionMapper extends BaseMapperX<PracticeQuestionDO> {
|
||||||
|
|
||||||
|
default List<PracticeQuestionDO> selectBySessionIdAndTenantIdOrderBySequence(Long sessionId, Long tenantId) {
|
||||||
|
return selectList(new LambdaQueryWrapperX<PracticeQuestionDO>()
|
||||||
|
.eq(PracticeQuestionDO::getSessionId, sessionId)
|
||||||
|
.eq(PracticeQuestionDO::getTenantId, tenantId)
|
||||||
|
.orderByAsc(PracticeQuestionDO::getSequence));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按会话 ID 和序号查询题目快照列表,按 sequence 升序。
|
* 按 tenant、会话 ID 和序号查询题目快照。
|
||||||
|
*/
|
||||||
|
default PracticeQuestionDO selectBySessionIdAndTenantIdAndSequence(Long sessionId, Long tenantId,
|
||||||
|
Integer sequence) {
|
||||||
|
return selectOne(new LambdaQueryWrapperX<PracticeQuestionDO>()
|
||||||
|
.eq(PracticeQuestionDO::getSessionId, sessionId)
|
||||||
|
.eq(PracticeQuestionDO::getTenantId, tenantId)
|
||||||
|
.eq(PracticeQuestionDO::getSequence, sequence));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 兼容内部测试和迁移查询;业务服务优先使用带 tenantId 的方法。
|
||||||
*/
|
*/
|
||||||
default List<PracticeQuestionDO> selectBySessionIdOrderBySequence(Long sessionId) {
|
default List<PracticeQuestionDO> selectBySessionIdOrderBySequence(Long sessionId) {
|
||||||
return selectList(new LambdaQueryWrapperX<PracticeQuestionDO>()
|
return selectList(new LambdaQueryWrapperX<PracticeQuestionDO>()
|
||||||
@@ -26,7 +44,7 @@ public interface PracticeQuestionMapper extends BaseMapperX<PracticeQuestionDO>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按会话 ID 和题目序号查找单题快照。
|
* 兼容内部测试和迁移查询;业务服务优先使用带 tenantId 的方法。
|
||||||
*/
|
*/
|
||||||
default PracticeQuestionDO selectBySessionIdAndSequence(Long sessionId, Integer sequence) {
|
default PracticeQuestionDO selectBySessionIdAndSequence(Long sessionId, Integer sequence) {
|
||||||
return selectOne(new LambdaQueryWrapperX<PracticeQuestionDO>()
|
return selectOne(new LambdaQueryWrapperX<PracticeQuestionDO>()
|
||||||
@@ -35,8 +53,25 @@ public interface PracticeQuestionMapper extends BaseMapperX<PracticeQuestionDO>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CAS 条件更新题目答案。仅当 tenant 匹配且当前 clientSequence 小于传入值(或为 NULL)
|
* CAS 条件更新题目答案。仅当指定租户、会话和题目匹配,且当前 clientSequence
|
||||||
* 时才执行更新。返回受影响行数(1 = 成功,0 = 序列过期或租户不匹配)。
|
* 小于传入值(或为 NULL)时才执行更新。
|
||||||
|
*/
|
||||||
|
default int updateAnswerIfNewer(Long questionId, Long sessionId, Long tenantId, String selectedAnswer,
|
||||||
|
Boolean isAnswered, Integer clientSequence) {
|
||||||
|
return update(null,
|
||||||
|
new LambdaUpdateWrapper<PracticeQuestionDO>()
|
||||||
|
.eq(PracticeQuestionDO::getId, questionId)
|
||||||
|
.eq(PracticeQuestionDO::getSessionId, sessionId)
|
||||||
|
.eq(PracticeQuestionDO::getTenantId, tenantId)
|
||||||
|
.and(w -> w.isNull(PracticeQuestionDO::getClientSequence)
|
||||||
|
.or().lt(PracticeQuestionDO::getClientSequence, clientSequence))
|
||||||
|
.set(PracticeQuestionDO::getSelectedAnswer, selectedAnswer)
|
||||||
|
.set(PracticeQuestionDO::getIsAnswered, isAnswered)
|
||||||
|
.set(PracticeQuestionDO::getClientSequence, clientSequence));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 兼容旧调用方;业务服务应使用包含 sessionId 的重载。
|
||||||
*/
|
*/
|
||||||
default int updateAnswerIfNewer(Long questionId, Long tenantId, String selectedAnswer,
|
default int updateAnswerIfNewer(Long questionId, Long tenantId, String selectedAnswer,
|
||||||
Boolean isAnswered, Integer clientSequence) {
|
Boolean isAnswered, Integer clientSequence) {
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ public interface ErrorCodeConstants {
|
|||||||
ErrorCode EDUCATION_TENANT_DISABLED = new ErrorCode(1_005_001_002, "租户已被禁用");
|
ErrorCode EDUCATION_TENANT_DISABLED = new ErrorCode(1_005_001_002, "租户已被禁用");
|
||||||
ErrorCode EDUCATION_TENANT_RESOLVE_FAILED = new ErrorCode(1_005_001_003, "租户识别失败:{}");
|
ErrorCode EDUCATION_TENANT_RESOLVE_FAILED = new ErrorCode(1_005_001_003, "租户识别失败:{}");
|
||||||
ErrorCode EDUCATION_TENANT_NOT_ACTIVE = new ErrorCode(1_005_001_004, "当前租户不可用,请联系管理员");
|
ErrorCode EDUCATION_TENANT_NOT_ACTIVE = new ErrorCode(1_005_001_004, "当前租户不可用,请联系管理员");
|
||||||
|
ErrorCode EDUCATION_TENANT_NOT_IN_PILOT = new ErrorCode(1_005_001_005, "当前租户尚未开放教育 Pilot 能力");
|
||||||
|
ErrorCode EDUCATION_CATALOG_READ_DISABLED = new ErrorCode(1_005_001_006, "题库读取能力已关闭,请稍后重试");
|
||||||
|
ErrorCode EDUCATION_PRACTICE_WRITE_DISABLED = new ErrorCode(1_005_001_007, "练习写入能力已关闭,历史数据仍可查看");
|
||||||
|
|
||||||
// ========== Catalog 目录 1-005-002-000 ~ 1-005-002-009 ==========
|
// ========== Catalog 目录 1-005-002-000 ~ 1-005-002-009 ==========
|
||||||
ErrorCode CATALOG_DATA_SOURCE_DISABLED = new ErrorCode(1_005_002_000, "题库数据源未启用,请联系管理员");
|
ErrorCode CATALOG_DATA_SOURCE_DISABLED = new ErrorCode(1_005_002_000, "题库数据源未启用,请联系管理员");
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.iocoder.yudao.module.education.service.access;
|
||||||
|
|
||||||
|
import cn.iocoder.yudao.module.education.config.EducationProperties;
|
||||||
|
import jakarta.annotation.Resource;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_CATALOG_READ_DISABLED;
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_PRACTICE_WRITE_DISABLED;
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_TENANT_NOT_IN_PILOT;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Education 灰度访问控制。
|
||||||
|
*
|
||||||
|
* 仅控制新请求是否进入对应能力,不修改或删除任何学生历史数据。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class EducationAccessService {
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private EducationProperties properties;
|
||||||
|
|
||||||
|
public void assertCatalogReadAllowed(Long tenantId) {
|
||||||
|
assertPilotTenant(tenantId);
|
||||||
|
if (!properties.isCatalogReadEnabled()) {
|
||||||
|
throw exception(EDUCATION_CATALOG_READ_DISABLED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void assertPracticeWriteAllowed(Long tenantId) {
|
||||||
|
assertPilotTenant(tenantId);
|
||||||
|
if (!properties.isPracticeWriteEnabled()) {
|
||||||
|
throw exception(EDUCATION_PRACTICE_WRITE_DISABLED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void assertPilotTenant(Long tenantId) {
|
||||||
|
if (!properties.getPilotTenantIds().isEmpty() && !properties.getPilotTenantIds().contains(tenantId)) {
|
||||||
|
throw exception(EDUCATION_TENANT_NOT_IN_PILOT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -161,7 +161,7 @@ public class FavoriteServiceImpl implements FavoriteService {
|
|||||||
tenantId, userId, reqVO.getTargetType());
|
tenantId, userId, reqVO.getTargetType());
|
||||||
|
|
||||||
// 2. Refresh availability for the returned favorites
|
// 2. Refresh availability for the returned favorites
|
||||||
refreshAvailability(page.getRecords());
|
refreshAvailability(page.getRecords(), userId, tenantId);
|
||||||
|
|
||||||
List<FavoritePageItemRespVO> list = page.getRecords().stream()
|
List<FavoritePageItemRespVO> list = page.getRecords().stream()
|
||||||
.map(this::toPageItem)
|
.map(this::toPageItem)
|
||||||
@@ -257,7 +257,7 @@ public class FavoriteServiceImpl implements FavoriteService {
|
|||||||
* 如果题目恢复可见,将 available 标记为 true 并持久化。
|
* 如果题目恢复可见,将 available 标记为 true 并持久化。
|
||||||
* 其他上游异常(网络错误、超时等)直接传播,不静默标记为不可用。</p>
|
* 其他上游异常(网络错误、超时等)直接传播,不静默标记为不可用。</p>
|
||||||
*/
|
*/
|
||||||
private void refreshAvailability(List<EducationFavoriteDO> favorites) {
|
private void refreshAvailability(List<EducationFavoriteDO> favorites, Long userId, Long tenantId) {
|
||||||
if (favorites == null || favorites.isEmpty()) {
|
if (favorites == null || favorites.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -286,7 +286,8 @@ public class FavoriteServiceImpl implements FavoriteService {
|
|||||||
.filter(f -> targetId.equals(f.getTargetId())
|
.filter(f -> targetId.equals(f.getTargetId())
|
||||||
&& !Objects.equals(finalAvailable, f.getAvailable()))
|
&& !Objects.equals(finalAvailable, f.getAvailable()))
|
||||||
.forEach(f -> {
|
.forEach(f -> {
|
||||||
favoriteMapper.updateAvailable(f.getId(), finalAvailable);
|
favoriteMapper.updateAvailableByIdAndTenantAndUser(
|
||||||
|
f.getId(), tenantId, userId, finalAvailable);
|
||||||
f.setAvailable(finalAvailable);
|
f.setAvailable(finalAvailable);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
if (!isSameFingerprint(existing, reqVO)) {
|
if (!isSameFingerprint(existing, reqVO)) {
|
||||||
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
||||||
}
|
}
|
||||||
return buildSessionResp(existing, questionMapper.selectBySessionIdOrderBySequence(existing.getId()));
|
return buildSessionResp(existing, questionMapper.selectBySessionIdAndTenantIdOrderBySequence(existing.getId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Fetch eligible questions — provider returns visible-only per contract
|
// 2. Fetch eligible questions — provider returns visible-only per contract
|
||||||
@@ -113,7 +113,7 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
if (!isSameFingerprint(winner, reqVO)) {
|
if (!isSameFingerprint(winner, reqVO)) {
|
||||||
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
||||||
}
|
}
|
||||||
return buildSessionResp(winner, questionMapper.selectBySessionIdOrderBySequence(winner.getId()));
|
return buildSessionResp(winner, questionMapper.selectBySessionIdAndTenantIdOrderBySequence(winner.getId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Create question snapshots with protected answer key
|
// 4. Create question snapshots with protected answer key
|
||||||
@@ -147,7 +147,7 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
if (session == null) {
|
if (session == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
List<PracticeQuestionDO> questions = questionMapper.selectBySessionIdOrderBySequence(session.getId());
|
List<PracticeQuestionDO> questions = questionMapper.selectBySessionIdAndTenantIdOrderBySequence(session.getId(), tenantId);
|
||||||
return buildSessionResp(session, questions);
|
return buildSessionResp(session, questions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,7 +160,7 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
if (!Objects.equals(session.getUserId(), userId)) {
|
if (!Objects.equals(session.getUserId(), userId)) {
|
||||||
throw exception(SESSION_NOT_OWN);
|
throw exception(SESSION_NOT_OWN);
|
||||||
}
|
}
|
||||||
List<PracticeQuestionDO> questions = questionMapper.selectBySessionIdOrderBySequence(session.getId());
|
List<PracticeQuestionDO> questions = questionMapper.selectBySessionIdAndTenantIdOrderBySequence(session.getId(), tenantId);
|
||||||
return buildSessionResp(session, questions);
|
return buildSessionResp(session, questions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,8 +228,8 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Load question and validate
|
// 3. Load question and validate
|
||||||
PracticeQuestionDO question = questionMapper.selectBySessionIdAndSequence(
|
PracticeQuestionDO question = questionMapper.selectBySessionIdAndTenantIdAndSequence(
|
||||||
reqVO.getSessionId(), reqVO.getQuestionSequence());
|
reqVO.getSessionId(), tenantId, reqVO.getQuestionSequence());
|
||||||
if (question == null) {
|
if (question == null) {
|
||||||
throw exception(ANSWER_QUESTION_NOT_IN_SESSION);
|
throw exception(ANSWER_QUESTION_NOT_IN_SESSION);
|
||||||
}
|
}
|
||||||
@@ -269,7 +269,7 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 6. Update question answer with clientSequence guard
|
// 6. Update question answer with clientSequence guard
|
||||||
int updated = questionMapper.updateAnswerIfNewer(question.getId(), tenantId,
|
int updated = questionMapper.updateAnswerIfNewer(question.getId(), reqVO.getSessionId(), tenantId,
|
||||||
reqVO.getSelectedAnswer(),
|
reqVO.getSelectedAnswer(),
|
||||||
reqVO.getSelectedAnswer() != null && !reqVO.getSelectedAnswer().isEmpty(),
|
reqVO.getSelectedAnswer() != null && !reqVO.getSelectedAnswer().isEmpty(),
|
||||||
reqVO.getClientSequence());
|
reqVO.getClientSequence());
|
||||||
@@ -337,7 +337,7 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4. Load question snapshots and score
|
// 4. Load question snapshots and score
|
||||||
List<PracticeQuestionDO> questions = questionMapper.selectBySessionIdOrderBySequence(session.getId());
|
List<PracticeQuestionDO> questions = questionMapper.selectBySessionIdAndTenantIdOrderBySequence(session.getId(), tenantId);
|
||||||
int score = computeScore(questions);
|
int score = computeScore(questions);
|
||||||
int answeredCount = (int) questions.stream().filter(q -> q.getIsAnswered() != null && q.getIsAnswered()).count();
|
int answeredCount = (int) questions.stream().filter(q -> q.getIsAnswered() != null && q.getIsAnswered()).count();
|
||||||
int unansweredCount = questions.size() - answeredCount;
|
int unansweredCount = questions.size() - answeredCount;
|
||||||
@@ -527,12 +527,11 @@ public class PracticeSessionServiceImpl implements PracticeSessionService {
|
|||||||
throw exception(INSUFFICIENT_ELIGIBLE_QUESTIONS, 0, count);
|
throw exception(INSUFFICIENT_ELIGIBLE_QUESTIONS, 0, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
allQuestions.sort(Comparator.comparing(CatalogQuestionDTO::getId, Comparator.nullsLast(String::compareTo))
|
||||||
|
.thenComparing(CatalogQuestionDTO::getContentVersion, Comparator.nullsLast(String::compareTo)));
|
||||||
if (allQuestions.size() > count) {
|
if (allQuestions.size() > count) {
|
||||||
allQuestions = allQuestions.subList(0, count);
|
allQuestions = allQuestions.subList(0, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
allQuestions.sort(Comparator.comparing(CatalogQuestionDTO::getId, Comparator.nullsLast(String::compareTo))
|
|
||||||
.thenComparing(CatalogQuestionDTO::getContentVersion, Comparator.nullsLast(String::compareTo)));
|
|
||||||
return allQuestions;
|
return allQuestions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ public class QuestionCatalogServiceImpl implements QuestionCatalogService {
|
|||||||
pageNo, pageSize);
|
pageNo, pageSize);
|
||||||
|
|
||||||
if (pageResult == null || pageResult.getItems() == null) {
|
if (pageResult == null || pageResult.getItems() == null) {
|
||||||
return new PageResult<>(Collections.emptyList(), 0L);
|
throw exception(CATALOG_UPSTREAM_UNAVAILABLE);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fail-closed: provider contract guarantees visible-only items.
|
// Fail-closed: provider contract guarantees visible-only items.
|
||||||
@@ -89,7 +89,7 @@ public class QuestionCatalogServiceImpl implements QuestionCatalogService {
|
|||||||
collectionId, type, difficulty, pageNo, pageSize);
|
collectionId, type, difficulty, pageNo, pageSize);
|
||||||
|
|
||||||
if (pageResult == null || pageResult.getItems() == null) {
|
if (pageResult == null || pageResult.getItems() == null) {
|
||||||
return new PageResult<>(Collections.emptyList(), 0L);
|
throw exception(CATALOG_UPSTREAM_UNAVAILABLE);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fail-closed: provider contract guarantees visible-only items.
|
// Fail-closed: provider contract guarantees visible-only items.
|
||||||
@@ -123,25 +123,30 @@ public class QuestionCatalogServiceImpl implements QuestionCatalogService {
|
|||||||
int minQ = blueprint.getMinQuestions() != null ? blueprint.getMinQuestions() : 1;
|
int minQ = blueprint.getMinQuestions() != null ? blueprint.getMinQuestions() : 1;
|
||||||
|
|
||||||
// If requested exceeds eligible, reject with INSUFFICIENT
|
// If requested exceeds eligible, reject with INSUFFICIENT
|
||||||
if (eligible == 0 || requestedCount > eligible) {
|
if (eligible == 0 || requestedCount > eligible || eligible < minQ) {
|
||||||
throw exception(INSUFFICIENT_ELIGIBLE_QUESTIONS, eligible, requestedCount);
|
throw exception(INSUFFICIENT_ELIGIBLE_QUESTIONS, eligible, requestedCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normalize within min/max bounds
|
int effectiveMax = Math.min(maxQ, eligible);
|
||||||
int normalized = Math.max(minQ, Math.min(requestedCount, maxQ));
|
int effectiveMin = minQ;
|
||||||
|
if (effectiveMax <= 0 || effectiveMin <= 0 || effectiveMin > effectiveMax) {
|
||||||
|
throw exception(INSUFFICIENT_ELIGIBLE_QUESTIONS, eligible, requestedCount);
|
||||||
|
}
|
||||||
|
|
||||||
// countWithinRange is true only if requested fits within [minQ, maxQ] AND <= eligible
|
// Normalize within the provider bounds and the actual eligible count.
|
||||||
boolean withinRange = requestedCount >= minQ
|
int normalized = Math.max(effectiveMin, Math.min(requestedCount, effectiveMax));
|
||||||
&& requestedCount <= maxQ
|
|
||||||
&& requestedCount <= eligible;
|
// countWithinRange is true only if requested fits within the effective bounds.
|
||||||
|
boolean withinRange = requestedCount >= effectiveMin
|
||||||
|
&& requestedCount <= effectiveMax;
|
||||||
|
|
||||||
return PracticeConfigPreviewRespVO.builder()
|
return PracticeConfigPreviewRespVO.builder()
|
||||||
.eligibleCount(eligible)
|
.eligibleCount(eligible)
|
||||||
.totalCount(blueprint.getTotalCount())
|
.totalCount(blueprint.getTotalCount())
|
||||||
.availableTypes(blueprint.getAvailableTypes())
|
.availableTypes(blueprint.getAvailableTypes())
|
||||||
.availableDifficulties(blueprint.getAvailableDifficulties())
|
.availableDifficulties(blueprint.getAvailableDifficulties())
|
||||||
.minQuestions(minQ)
|
.minQuestions(effectiveMin)
|
||||||
.maxQuestions(maxQ)
|
.maxQuestions(effectiveMax)
|
||||||
.suggestedCount(blueprint.getSuggestedCount())
|
.suggestedCount(blueprint.getSuggestedCount())
|
||||||
.normalizedCount(normalized)
|
.normalizedCount(normalized)
|
||||||
.countWithinRange(withinRange)
|
.countWithinRange(withinRange)
|
||||||
|
|||||||
@@ -148,7 +148,7 @@ public class WrongQuestionServiceImpl implements WrongQuestionService {
|
|||||||
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
||||||
}
|
}
|
||||||
// Same tenant + clientSessionId + user + fingerprint → replay
|
// Same tenant + clientSessionId + user + fingerprint → replay
|
||||||
return buildSessionResp(existing, questionMapper.selectBySessionIdOrderBySequence(existing.getId()));
|
return buildSessionResp(existing, questionMapper.selectBySessionIdAndTenantIdOrderBySequence(existing.getId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Load all wrong questions by ID, verify ownership
|
// 3. Load all wrong questions by ID, verify ownership
|
||||||
@@ -184,7 +184,7 @@ public class WrongQuestionServiceImpl implements WrongQuestionService {
|
|||||||
if (!Objects.equals(winner.getReviewFingerprint(), fingerprint)) {
|
if (!Objects.equals(winner.getReviewFingerprint(), fingerprint)) {
|
||||||
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
throw exception(SESSION_IDEMPOTENCY_MISMATCH);
|
||||||
}
|
}
|
||||||
return buildSessionResp(winner, questionMapper.selectBySessionIdOrderBySequence(winner.getId()));
|
return buildSessionResp(winner, questionMapper.selectBySessionIdAndTenantIdOrderBySequence(winner.getId(), tenantId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Create question snapshots from wrong question data (NO correct answer exposed pre-submit)
|
// 4. Create question snapshots from wrong question data (NO correct answer exposed pre-submit)
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ public class EducationPropertiesTest {
|
|||||||
EducationProperties defaults = new EducationProperties();
|
EducationProperties defaults = new EducationProperties();
|
||||||
assertFalse(defaults.isEnabled(), "默认应禁用");
|
assertFalse(defaults.isEnabled(), "默认应禁用");
|
||||||
assertEquals("1.0.0", defaults.getVersion(), "默认版本应为 1.0.0");
|
assertEquals("1.0.0", defaults.getVersion(), "默认版本应为 1.0.0");
|
||||||
|
assertTrue(defaults.isCatalogReadEnabled(), "模块启用后题库读取默认开放");
|
||||||
|
assertTrue(defaults.isPracticeWriteEnabled(), "模块启用后练习写入默认开放");
|
||||||
|
assertTrue(defaults.getPilotTenantIds().isEmpty(), "Pilot 租户为空时不限制租户");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
|||||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogProvider;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogProvider;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogService;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogService;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogServiceImpl;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogServiceImpl;
|
||||||
@@ -49,6 +50,9 @@ class CatalogControllerHttpTest {
|
|||||||
var field = CatalogController.class.getDeclaredField("catalogService");
|
var field = CatalogController.class.getDeclaredField("catalogService");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
field.set(controller, catalogService);
|
field.set(controller, catalogService);
|
||||||
|
var accessField = CatalogController.class.getDeclaredField("educationAccessService");
|
||||||
|
accessField.setAccessible(true);
|
||||||
|
accessField.set(controller, mock(EducationAccessService.class));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package cn.iocoder.yudao.module.education.controller.app.catalog;
|
|||||||
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
|
import cn.iocoder.yudao.module.education.config.EducationProperties;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogProvider;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogProvider;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogService;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogService;
|
||||||
import cn.iocoder.yudao.module.education.service.catalog.CatalogServiceImpl;
|
import cn.iocoder.yudao.module.education.service.catalog.CatalogServiceImpl;
|
||||||
@@ -31,7 +33,9 @@ import static org.mockito.Mockito.when;
|
|||||||
@SpringBootTest(
|
@SpringBootTest(
|
||||||
classes = {
|
classes = {
|
||||||
CatalogController.class,
|
CatalogController.class,
|
||||||
CatalogServiceImpl.class
|
CatalogServiceImpl.class,
|
||||||
|
EducationAccessService.class,
|
||||||
|
EducationProperties.class
|
||||||
},
|
},
|
||||||
properties = {
|
properties = {
|
||||||
"yudao.education.enabled=true",
|
"yudao.education.enabled=true",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import cn.iocoder.yudao.framework.security.core.LoginUser;
|
|||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeAnswerReqVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeAnswerReqVO;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeAnswerRespVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeAnswerRespVO;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
@@ -50,6 +51,9 @@ class PracticeAnswerControllerHttpTest {
|
|||||||
var field = PracticeSessionController.class.getDeclaredField("practiceSessionService");
|
var field = PracticeSessionController.class.getDeclaredField("practiceSessionService");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
field.set(controller, service);
|
field.set(controller, service);
|
||||||
|
var accessField = PracticeSessionController.class.getDeclaredField("educationAccessService");
|
||||||
|
accessField.setAccessible(true);
|
||||||
|
accessField.set(controller, mock(EducationAccessService.class));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
|||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeQuestionRespVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeQuestionRespVO;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSessionCreateReqVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSessionCreateReqVO;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSessionRespVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSessionRespVO;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
||||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
@@ -55,6 +56,9 @@ class PracticeSessionControllerHttpTest {
|
|||||||
var field = PracticeSessionController.class.getDeclaredField("practiceSessionService");
|
var field = PracticeSessionController.class.getDeclaredField("practiceSessionService");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
field.set(controller, service);
|
field.set(controller, service);
|
||||||
|
var accessField = PracticeSessionController.class.getDeclaredField("educationAccessService");
|
||||||
|
accessField.setAccessible(true);
|
||||||
|
accessField.set(controller, mock(EducationAccessService.class));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
|||||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.*;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.*;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
import cn.iocoder.yudao.module.education.service.practice.PracticeSessionService;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
@@ -53,6 +54,9 @@ class PracticeSessionControllerSubmitHttpTest {
|
|||||||
var field = PracticeSessionController.class.getDeclaredField("practiceSessionService");
|
var field = PracticeSessionController.class.getDeclaredField("practiceSessionService");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
field.set(controller, service);
|
field.set(controller, service);
|
||||||
|
var accessField = PracticeSessionController.class.getDeclaredField("educationAccessService");
|
||||||
|
accessField.setAccessible(true);
|
||||||
|
accessField.set(controller, mock(EducationAccessService.class));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
|
|||||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.question.vo.*;
|
import cn.iocoder.yudao.module.education.controller.app.question.vo.*;
|
||||||
|
import cn.iocoder.yudao.module.education.service.access.EducationAccessService;
|
||||||
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogProvider;
|
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogProvider;
|
||||||
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogService;
|
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogService;
|
||||||
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogServiceImpl;
|
import cn.iocoder.yudao.module.education.service.question.QuestionCatalogServiceImpl;
|
||||||
@@ -55,6 +56,9 @@ class QuestionControllerHttpTest {
|
|||||||
var field = QuestionController.class.getDeclaredField("questionCatalogService");
|
var field = QuestionController.class.getDeclaredField("questionCatalogService");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
field.set(controller, service);
|
field.set(controller, service);
|
||||||
|
var accessField = QuestionController.class.getDeclaredField("educationAccessService");
|
||||||
|
accessField.setAccessible(true);
|
||||||
|
accessField.set(controller, mock(EducationAccessService.class));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package cn.iocoder.yudao.module.education.service.access;
|
||||||
|
|
||||||
|
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||||
|
import cn.iocoder.yudao.module.education.config.EducationProperties;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_CATALOG_READ_DISABLED;
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_PRACTICE_WRITE_DISABLED;
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_TENANT_NOT_IN_PILOT;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class EducationAccessServiceTest {
|
||||||
|
|
||||||
|
private EducationProperties properties;
|
||||||
|
private EducationAccessService accessService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws Exception {
|
||||||
|
properties = new EducationProperties();
|
||||||
|
accessService = new EducationAccessService();
|
||||||
|
Field field = EducationAccessService.class.getDeclaredField("properties");
|
||||||
|
field.setAccessible(true);
|
||||||
|
field.set(accessService, properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAllowAllTenantsWhenPilotListEmpty() {
|
||||||
|
assertDoesNotThrow(() -> accessService.assertCatalogReadAllowed(100L));
|
||||||
|
assertDoesNotThrow(() -> accessService.assertPracticeWriteAllowed(100L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRejectTenantOutsidePilot() {
|
||||||
|
properties.setPilotTenantIds(List.of(100L));
|
||||||
|
|
||||||
|
ServiceException ex = assertThrows(ServiceException.class,
|
||||||
|
() -> accessService.assertCatalogReadAllowed(200L));
|
||||||
|
|
||||||
|
assertEquals(EDUCATION_TENANT_NOT_IN_PILOT.getCode(), ex.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldDisableCatalogWithoutDisablingHistoryReads() {
|
||||||
|
properties.setCatalogReadEnabled(false);
|
||||||
|
|
||||||
|
ServiceException ex = assertThrows(ServiceException.class,
|
||||||
|
() -> accessService.assertCatalogReadAllowed(100L));
|
||||||
|
|
||||||
|
assertEquals(EDUCATION_CATALOG_READ_DISABLED.getCode(), ex.getCode());
|
||||||
|
assertDoesNotThrow(() -> accessService.assertPilotTenant(100L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldDisablePracticeWritesIndependently() {
|
||||||
|
properties.setPracticeWriteEnabled(false);
|
||||||
|
|
||||||
|
ServiceException ex = assertThrows(ServiceException.class,
|
||||||
|
() -> accessService.assertPracticeWriteAllowed(100L));
|
||||||
|
|
||||||
|
assertEquals(EDUCATION_PRACTICE_WRITE_DISABLED.getCode(), ex.getCode());
|
||||||
|
assertDoesNotThrow(() -> accessService.assertCatalogReadAllowed(100L));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package cn.iocoder.yudao.module.education.service.practice;
|
package cn.iocoder.yudao.module.education.service.practice;
|
||||||
|
|
||||||
|
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||||
|
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitReqVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitReqVO;
|
||||||
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitRespVO;
|
import cn.iocoder.yudao.module.education.controller.app.practice.vo.PracticeSubmitRespVO;
|
||||||
@@ -14,6 +16,8 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.REPORT_NOT_OWN;
|
||||||
|
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.SESSION_NOT_FOUND;
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -58,9 +62,14 @@ public class PracticeSubmitProjectionIntegrationTest extends BaseDbUnitTest {
|
|||||||
private record SessionFixture(Long sessionId, List<PracticeQuestionDO> questions, Integer version) {}
|
private record SessionFixture(Long sessionId, List<PracticeQuestionDO> questions, Integer version) {}
|
||||||
|
|
||||||
private SessionFixture createSessionWithQuestions(String clientSessionId, int questionCount, String correctAnswer) {
|
private SessionFixture createSessionWithQuestions(String clientSessionId, int questionCount, String correctAnswer) {
|
||||||
|
return createSessionWithQuestions(clientSessionId, questionCount, correctAnswer, tenantId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private SessionFixture createSessionWithQuestions(String clientSessionId, int questionCount, String correctAnswer,
|
||||||
|
Long fixtureTenantId, Long fixtureUserId) {
|
||||||
PracticeSessionDO session = new PracticeSessionDO();
|
PracticeSessionDO session = new PracticeSessionDO();
|
||||||
session.setTenantId(tenantId);
|
session.setTenantId(fixtureTenantId);
|
||||||
session.setUserId(userId);
|
session.setUserId(fixtureUserId);
|
||||||
session.setClientSessionId(clientSessionId);
|
session.setClientSessionId(clientSessionId);
|
||||||
session.setStatus("ACTIVE");
|
session.setStatus("ACTIVE");
|
||||||
session.setQuestionCount(questionCount);
|
session.setQuestionCount(questionCount);
|
||||||
@@ -71,10 +80,12 @@ public class PracticeSubmitProjectionIntegrationTest extends BaseDbUnitTest {
|
|||||||
List<PracticeQuestionDO> questions = new java.util.ArrayList<>();
|
List<PracticeQuestionDO> questions = new java.util.ArrayList<>();
|
||||||
for (int i = 0; i < questionCount; i++) {
|
for (int i = 0; i < questionCount; i++) {
|
||||||
PracticeQuestionDO q = new PracticeQuestionDO();
|
PracticeQuestionDO q = new PracticeQuestionDO();
|
||||||
q.setTenantId(tenantId);
|
q.setTenantId(fixtureTenantId);
|
||||||
q.setSessionId(session.getId());
|
q.setSessionId(session.getId());
|
||||||
q.setSequence(i + 1);
|
q.setSequence(i + 1);
|
||||||
q.setQuestionId("q-" + String.format("%03d", i + 1));
|
String questionPrefix = fixtureTenantId.equals(tenantId) && fixtureUserId.equals(userId)
|
||||||
|
? "q-" : "q-" + fixtureTenantId + "-" + fixtureUserId + "-";
|
||||||
|
q.setQuestionId(questionPrefix + String.format("%03d", i + 1));
|
||||||
q.setContentVersion("v1");
|
q.setContentVersion("v1");
|
||||||
q.setStem("Question " + (i + 1));
|
q.setStem("Question " + (i + 1));
|
||||||
q.setType("choice");
|
q.setType("choice");
|
||||||
@@ -233,6 +244,65 @@ public class PracticeSubmitProjectionIntegrationTest extends BaseDbUnitTest {
|
|||||||
assertEquals(1, wqs.get(0).getWrongCount());
|
assertEquals(1, wqs.get(0).getWrongCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldIsolateSessionsReportsAndWrongQuestionsAcrossTwoTenantsAndStudents() {
|
||||||
|
Long[][] owners = {{11L, 101L}, {11L, 102L}, {22L, 201L}, {22L, 202L}};
|
||||||
|
java.util.Map<String, SessionFixture> fixtures = new java.util.LinkedHashMap<>();
|
||||||
|
java.util.Map<String, PracticeSubmitRespVO> reports = new java.util.LinkedHashMap<>();
|
||||||
|
|
||||||
|
for (Long[] owner : owners) {
|
||||||
|
Long fixtureTenantId = owner[0];
|
||||||
|
Long fixtureUserId = owner[1];
|
||||||
|
String key = fixtureTenantId + ":" + fixtureUserId;
|
||||||
|
SessionFixture fixture = createSessionWithQuestions(
|
||||||
|
"isolation-" + key, 1, "B", fixtureTenantId, fixtureUserId);
|
||||||
|
answerQuestion(fixture.questions().get(0).getId(), "A");
|
||||||
|
PracticeSubmitRespVO report = service.submitSession(
|
||||||
|
createSubmitReq(fixture.sessionId(), "submit-" + key, 1),
|
||||||
|
fixtureUserId, fixtureTenantId);
|
||||||
|
fixtures.put(key, fixture);
|
||||||
|
reports.put(key, report);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(4, reports.values().stream().map(PracticeSubmitRespVO::getReportId).distinct().count());
|
||||||
|
assertEquals(4, wrongQuestionMapper.selectList().size());
|
||||||
|
|
||||||
|
for (Long[] owner : owners) {
|
||||||
|
Long fixtureTenantId = owner[0];
|
||||||
|
Long fixtureUserId = owner[1];
|
||||||
|
String key = fixtureTenantId + ":" + fixtureUserId;
|
||||||
|
SessionFixture fixture = fixtures.get(key);
|
||||||
|
PracticeSubmitRespVO report = reports.get(key);
|
||||||
|
|
||||||
|
assertEquals(report.getReportId(),
|
||||||
|
service.getReport(fixture.sessionId(), fixtureUserId, fixtureTenantId).getReportId());
|
||||||
|
PageResult<PracticeSubmitRespVO> history =
|
||||||
|
service.getReportHistory(fixtureUserId, fixtureTenantId, 1, 10);
|
||||||
|
assertEquals(1L, history.getTotal());
|
||||||
|
assertEquals(fixture.sessionId(), history.getList().get(0).getSessionId());
|
||||||
|
|
||||||
|
List<WrongQuestionDO> ownWrongQuestions = wrongQuestionMapper.selectList().stream()
|
||||||
|
.filter(wq -> fixtureTenantId.equals(wq.getTenantId()) && fixtureUserId.equals(wq.getUserId()))
|
||||||
|
.toList();
|
||||||
|
assertEquals(1, ownWrongQuestions.size());
|
||||||
|
WrongQuestionDO wrongQuestion = ownWrongQuestions.get(0);
|
||||||
|
assertEquals(fixture.sessionId(), wrongQuestion.getLastSessionId());
|
||||||
|
assertEquals(report.getReportId(), wrongQuestion.getLastReportId());
|
||||||
|
|
||||||
|
Long otherUserSameTenant = java.util.Arrays.stream(owners)
|
||||||
|
.filter(candidate -> fixtureTenantId.equals(candidate[0]) && !fixtureUserId.equals(candidate[1]))
|
||||||
|
.findFirst().orElseThrow()[1];
|
||||||
|
ServiceException crossStudent = assertThrows(ServiceException.class,
|
||||||
|
() -> service.getReport(fixture.sessionId(), otherUserSameTenant, fixtureTenantId));
|
||||||
|
assertEquals(REPORT_NOT_OWN.getCode(), crossStudent.getCode());
|
||||||
|
|
||||||
|
Long otherTenant = fixtureTenantId.equals(11L) ? 22L : 11L;
|
||||||
|
ServiceException crossTenant = assertThrows(ServiceException.class,
|
||||||
|
() -> service.getReport(fixture.sessionId(), fixtureUserId, otherTenant));
|
||||||
|
assertEquals(SESSION_NOT_FOUND.getCode(), crossTenant.getCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ========== wrong_question_id populated in idempotency guard ==========
|
// ========== wrong_question_id populated in idempotency guard ==========
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -300,7 +300,26 @@ class QuestionCatalogServiceImplTest {
|
|||||||
assertEquals(3L, result.getTotal());
|
assertEquals(3L, result.getTotal());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== Practice config validation ==========
|
@Test
|
||||||
|
void shouldCapPracticeBoundsByEligibleCount() {
|
||||||
|
CatalogPracticeBlueprintDTO bp = CatalogPracticeBlueprintDTO.builder()
|
||||||
|
.eligibleCount(5)
|
||||||
|
.totalCount(5)
|
||||||
|
.minQuestions(10)
|
||||||
|
.maxQuestions(100)
|
||||||
|
.suggestedCount(10)
|
||||||
|
.build();
|
||||||
|
when(provider.getPracticeBlueprint(eq("col1"), isNull(), isNull(), isNull())).thenReturn(bp);
|
||||||
|
|
||||||
|
PracticeConfigPreviewReqVO req = new PracticeConfigPreviewReqVO();
|
||||||
|
req.setCollectionId("col1");
|
||||||
|
req.setQuestionCount(1);
|
||||||
|
|
||||||
|
ServiceException ex = assertThrows(ServiceException.class,
|
||||||
|
() -> service.previewPracticeConfig(req));
|
||||||
|
assertEquals(INSUFFICIENT_ELIGIBLE_QUESTIONS.getCode(), ex.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldReturnNormalizedPracticePreview() {
|
void shouldReturnNormalizedPracticePreview() {
|
||||||
@@ -446,10 +465,8 @@ class QuestionCatalogServiceImplTest {
|
|||||||
assertEquals(QUESTION_NOT_FOUND.getCode(), ex.getCode());
|
assertEquals(QUESTION_NOT_FOUND.getCode(), ex.getCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== Fix #8: null list/page result handling ==========
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldHandleNullPageResult() {
|
void shouldRejectNullPageResult() {
|
||||||
when(provider.listQuestions(any(), any(), any(), any(), eq(1), eq(20)))
|
when(provider.listQuestions(any(), any(), any(), any(), eq(1), eq(20)))
|
||||||
.thenReturn(null);
|
.thenReturn(null);
|
||||||
|
|
||||||
@@ -457,14 +474,12 @@ class QuestionCatalogServiceImplTest {
|
|||||||
req.setPageNo(1);
|
req.setPageNo(1);
|
||||||
req.setPageSize(20);
|
req.setPageSize(20);
|
||||||
|
|
||||||
PageResult<SafeQuestionRespVO> result = service.pageQuestions(req);
|
ServiceException ex = assertThrows(ServiceException.class, () -> service.pageQuestions(req));
|
||||||
assertNotNull(result);
|
assertEquals(CATALOG_UPSTREAM_UNAVAILABLE.getCode(), ex.getCode());
|
||||||
assertTrue(result.getList().isEmpty());
|
|
||||||
assertEquals(0L, result.getTotal());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldHandleNullPageResultItems() {
|
void shouldRejectNullPageResultItems() {
|
||||||
when(provider.listQuestions(any(), any(), any(), any(), eq(1), eq(20)))
|
when(provider.listQuestions(any(), any(), any(), any(), eq(1), eq(20)))
|
||||||
.thenReturn(CatalogQuestionPageResult.builder()
|
.thenReturn(CatalogQuestionPageResult.builder()
|
||||||
.items(null)
|
.items(null)
|
||||||
@@ -475,9 +490,8 @@ class QuestionCatalogServiceImplTest {
|
|||||||
req.setPageNo(1);
|
req.setPageNo(1);
|
||||||
req.setPageSize(20);
|
req.setPageSize(20);
|
||||||
|
|
||||||
PageResult<SafeQuestionRespVO> result = service.pageQuestions(req);
|
ServiceException ex = assertThrows(ServiceException.class, () -> service.pageQuestions(req));
|
||||||
assertNotNull(result);
|
assertEquals(CATALOG_UPSTREAM_UNAVAILABLE.getCode(), ex.getCode());
|
||||||
assertTrue(result.getList().isEmpty());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== Two tenant contexts ==========
|
// ========== Two tenant contexts ==========
|
||||||
|
|||||||
Reference in New Issue
Block a user