Compare commits
16 Commits
main
...
f22bab6586
| Author | SHA1 | Date | |
|---|---|---|---|
| f22bab6586 | |||
| 7ceb73d802 | |||
| f7b3cc450f | |||
| 9c9d231ad9 | |||
| 7d0e010483 | |||
| 4edf83de94 | |||
| ce02f8acb4 | |||
| 93f02df68c | |||
| 12676dfbec | |||
| 4cb18b844a | |||
| 046bb4efee | |||
| a43a58513a | |||
| 73b2a8edcc | |||
| 478d3d65b7 | |||
| 0f846fdaf5 | |||
| 11e9cc6854 |
115
.claude/skills/flyway-postgresql/SKILL.md
Normal file
115
.claude/skills/flyway-postgresql/SKILL.md
Normal file
@@ -0,0 +1,115 @@
|
||||
---
|
||||
name: flyway-postgresql
|
||||
description: Flyway PostgreSQL migrations for this project. Use when adding or changing database schema, indexes, constraints, required seed data, migration baselines, or Flyway configuration.
|
||||
---
|
||||
|
||||
# Flyway PostgreSQL migrations
|
||||
|
||||
Use a **forward-only** migration process. Treat `flyway_schema_history` as immutable release history.
|
||||
|
||||
## 1. Inspect the migration state
|
||||
|
||||
Before editing:
|
||||
|
||||
1. Read `CLAUDE.md` PostgreSQL and Flyway rules.
|
||||
2. Inspect `yudao-server/src/main/resources/application-{local,dev}.yaml` and `yudao-server/pom.xml` when configuration is involved.
|
||||
3. List every `db/migration` directory and versioned migration across active modules.
|
||||
4. Inspect the target table DO, Mapper, service use, and relevant PostgreSQL DDL.
|
||||
5. Check the working tree so existing uncommitted work is preserved.
|
||||
|
||||
**Complete when:** the active Flyway locations, baseline, highest migration version, affected database objects, and pending user changes are known.
|
||||
|
||||
## 2. Choose the migration branch
|
||||
|
||||
### New schema change
|
||||
|
||||
Create a new versioned SQL migration under:
|
||||
|
||||
```text
|
||||
<module>/src/main/resources/db/migration/<module>/
|
||||
```
|
||||
|
||||
Use the next unused project-wide version after `V4010`. Leave gaps of 10 for normal changes when practical:
|
||||
|
||||
```text
|
||||
V4020__add_student_progress.sql
|
||||
V4030__add_practice_report_index.sql
|
||||
```
|
||||
|
||||
### Fix an executed migration
|
||||
|
||||
Create a higher version that repairs or reverses the prior change. Preserve the executed file byte-for-byte.
|
||||
|
||||
### Existing database adoption
|
||||
|
||||
The current baseline is `4009`; `V4010__initialize_education_flyway.sql` is the first managed migration. Keep `baseline-on-migrate` only while existing environments are being adopted. After every existing environment has a baseline record, change it to `false` in a separate reviewed change.
|
||||
|
||||
### Configuration change
|
||||
|
||||
Flyway must target the dynamic datasource `master`, never `slave`. Keep these safeguards enabled:
|
||||
|
||||
```yaml
|
||||
validate-on-migrate: true
|
||||
clean-disabled: true
|
||||
out-of-order: false
|
||||
```
|
||||
|
||||
Allow `FLYWAY_URL`, `FLYWAY_USER`, and `FLYWAY_PASSWORD` to override master credentials.
|
||||
|
||||
**Complete when:** exactly one branch is selected and its version/configuration does not conflict with the current repository state.
|
||||
|
||||
## 3. Write PostgreSQL-native SQL
|
||||
|
||||
Follow these project conventions:
|
||||
|
||||
- Identity primary key: `BIGINT GENERATED BY DEFAULT AS IDENTITY`.
|
||||
- Time: `TIMESTAMP`; use `CURRENT_TIMESTAMP` for defaults.
|
||||
- Boolean: `BOOLEAN NOT NULL DEFAULT false` where appropriate.
|
||||
- Idempotency/upsert: `ON CONFLICT ... DO NOTHING` or `DO UPDATE SET ... EXCLUDED.column`.
|
||||
- Null fallback: `COALESCE`.
|
||||
- Date formatting: `TO_CHAR`; date parts: `EXTRACT`.
|
||||
- Bounded delete: delete by IDs selected in an ordered, limited subquery or CTE.
|
||||
- Add comments for business tables and non-obvious columns.
|
||||
- Add indexes from observed query and conflict targets, not speculation.
|
||||
- Required seed data must be deterministic and idempotent.
|
||||
- Put `CREATE INDEX CONCURRENTLY` in its own non-transactional migration; otherwise prefer transactional PostgreSQL DDL.
|
||||
|
||||
Keep verification queries in comments when useful. Put rollback notes in the change description or a separate operational document; production recovery is another forward migration.
|
||||
|
||||
**Complete when:** every affected object, data backfill, constraint, index, and application assumption is represented in PostgreSQL-native SQL.
|
||||
|
||||
## 4. Align application code
|
||||
|
||||
Update all affected DOs, Mappers, services, tests, and fixtures. Search Java annotations and MyBatis XML for stale column names and incompatible SQL. For a new identity/sequence-backed DO, follow the surrounding project’s `@TableId` and `@KeySequence` pattern.
|
||||
|
||||
**Complete when:** every code reference agrees with the post-migration schema and no active runtime SQL depends on the previous shape.
|
||||
|
||||
## 5. Verify
|
||||
|
||||
Run, in order:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
Confirm each migration is present under the owning module’s `target/classes/db/migration/...` after compilation. If an authorized disposable PostgreSQL database is available, run Flyway against it and inspect:
|
||||
|
||||
```sql
|
||||
SELECT installed_rank, version, description, script, checksum, success
|
||||
FROM flyway_schema_history
|
||||
ORDER BY installed_rank;
|
||||
```
|
||||
|
||||
Run focused tests for the affected module. Report any skipped database execution separately from compilation success.
|
||||
|
||||
**Complete when:** formatting and compilation pass, migration packaging is confirmed, focused tests pass or their exact blocker is reported, and any real-database migration status is stated truthfully.
|
||||
|
||||
## Release rules
|
||||
|
||||
- Version numbers are project-wide across every Flyway location.
|
||||
- One committed migration version has one immutable meaning.
|
||||
- Production migrations move forward; recovery is a higher version.
|
||||
- `clean` remains disabled.
|
||||
- Demo/test seed data lives outside production migrations.
|
||||
- Do not copy the legacy `sql/postgresql/ruoyi-vue-pro.sql` dump into a versioned runtime migration; it contains destructive bootstrap statements and embedded transactions. Use it only to initialize a disposable empty database or to establish the pre-Flyway baseline.
|
||||
88
CLAUDE.md
Normal file
88
CLAUDE.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# CLAUDE.md — 恭学教育
|
||||
|
||||
## 项目定位
|
||||
|
||||
恭学教育是基于 RuoYi-Vue-Pro 的教育 SaaS 平台,后端技术栈为 Spring Boot 4、MyBatis-Plus、PostgreSQL、Redis。
|
||||
|
||||
主要开发入口:
|
||||
|
||||
- `yudao-module-education/`:教育业务模块
|
||||
- `yudao-server/`:应用启动模块,默认端口 `48080`
|
||||
- `sql/postgresql/`:PostgreSQL 初始化与历史 SQL
|
||||
- `tools/education-student-harness/`:学生端 Playwright E2E 测试
|
||||
|
||||
分支、工作区状态、运行中的容器和临时任务属于动态信息;执行任务时从 Git、配置文件和运行环境读取,不在本文档固化。
|
||||
|
||||
## 工作方式
|
||||
|
||||
### Serena 优先
|
||||
|
||||
编码任务开始前调用 Serena `initial_instructions` 并激活项目。优先使用 Serena 完成符号检索、引用分析和结构化编辑;Serena 不可用或不适合时再使用通用文件与命令工具。互不依赖的查询或编辑应批量调用。
|
||||
|
||||
### 遵循现有代码
|
||||
|
||||
- 修改前检查工作区,保留用户已有的未提交修改。
|
||||
- 代码风格、命名、注释密度和分层方式与相邻代码保持一致。
|
||||
- 优先复用框架现有能力,避免为单一场景建立平行抽象。
|
||||
- 只修改当前任务需要的文件;发现相邻问题时先判断是否影响本次交付。
|
||||
|
||||
### Gitea 与仓库操作
|
||||
|
||||
项目托管在自建 Gitea。远程仓库、Issue 和 Pull Request 操作统一使用 `tea` CLI,不使用 GitHub CLI(`gh`)。执行创建或查看 Pull Request 等操作前,从当前 Git remote 与 `tea` 登录配置读取仓库和实例信息。
|
||||
|
||||
### Skills
|
||||
|
||||
项目级 Skills 位于 `.claude/skills/`,已有规范索引见 `.claude/skills/index.yaml`。
|
||||
|
||||
数据库结构、索引、约束、数据回填、必要种子数据、基线或 Flyway 配置发生变化时,使用项目 Skill:
|
||||
|
||||
```text
|
||||
/flyway-postgresql
|
||||
```
|
||||
|
||||
Flyway 的版本分配、接管策略、验证步骤以 `.claude/skills/flyway-postgresql/SKILL.md` 为唯一事实来源。
|
||||
|
||||
## 架构约束
|
||||
|
||||
### Education 模块
|
||||
|
||||
- `yudao.education.catalog-mode` 控制目录数据源:
|
||||
- `SCALAR_READ`:通过 `ScalarCatalogProvider` 访问 HTTP 数据源。
|
||||
- `JAVA_READ`:通过 `JavaCatalogProvider` 直连 PostgreSQL。
|
||||
- `QuestionCatalogServiceImpl` 返回前端前必须剥离答案与解析等敏感字段。
|
||||
- 题目不可见或数据源不可用时采用 fail-closed,不进行静默降级。
|
||||
- 多租户业务 DO 继承 `TenantBaseDO`,由 MyBatis-Plus 注入 `tenant_id`。
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
项目运行数据库为 PostgreSQL。Java 注解 SQL、MyBatis XML、测试 SQL 和运行配置均使用 PostgreSQL 方言。
|
||||
|
||||
- 主键:`BIGINT GENERATED BY DEFAULT AS IDENTITY`。
|
||||
- 时间:`TIMESTAMP`,默认当前时间使用 `CURRENT_TIMESTAMP`。
|
||||
- 布尔:`BOOLEAN`,按需使用 `NOT NULL DEFAULT false`。
|
||||
- 幂等插入:`ON CONFLICT ... DO NOTHING`。
|
||||
- Upsert:`ON CONFLICT (...) DO UPDATE SET ... EXCLUDED.column`。
|
||||
- 空值兜底:`COALESCE`;时间格式化:`TO_CHAR`;日期字段提取:`EXTRACT`。
|
||||
- 有界删除使用有序、限量的主键子查询或 CTE。
|
||||
- DO 主键遵循项目既有的 `@TableId`、`@KeySequence("{table}_seq")` 模式。
|
||||
|
||||
### Flyway
|
||||
|
||||
运行时 migration 放在所属模块:
|
||||
|
||||
```text
|
||||
<module>/src/main/resources/db/migration/<module>/
|
||||
```
|
||||
|
||||
已在共享环境执行的 migration 是不可变发布历史。数据库修复通过更高版本的向前 migration 完成,生产环境保持 `clean-disabled: true`。
|
||||
|
||||
## 验证
|
||||
|
||||
按改动范围执行最小充分验证。后端主链路至少运行:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
涉及行为变化时运行对应模块的聚焦测试;涉及数据库 migration 时还要确认脚本被打包到模块的 `target/classes/db/migration/`。只有实际执行过 PostgreSQL migration,才能报告数据库迁移成功;否则明确说明仅完成静态检查或编译验证。
|
||||
11
CONTEXT-MAP.md
Normal file
11
CONTEXT-MAP.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Context Map
|
||||
|
||||
## Contexts
|
||||
|
||||
- [Education](./yudao-module-education/CONTEXT.md) — owns education content, practice, assessment, and learning-state language.
|
||||
|
||||
## Relationships
|
||||
|
||||
- **Education → Member**: Education references the authenticated Member user as the student identity; it does not own credentials or generic user accounts.
|
||||
- **Education → System**: Education consumes tenant and authorization capabilities; it does not own generic tenants or RBAC.
|
||||
- **Education → Infra**: Education composes file, job, messaging, and audit capabilities for education workflows.
|
||||
38
docs/education/migration/00-current-state.md
Normal file
38
docs/education/migration/00-current-state.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Current State
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
## Executive summary
|
||||
|
||||
Phase 0 remains a read-only architecture assessment, not an implementation claim. Verified evidence shows the target is on feature/education-core-loop with a heavily dirty worktree, while the source checkout has no local or remote feature/education-core-loop ref and is main at 033701a. The target contains a meaningful committed core-loop slice (ce02f8a) plus substantial dirty provider/catalog/session work, so all roadmap status must distinguish committed, dirty, absent, and runtime-unverified behavior. EDU-003 has now decided public tenant resolution: Origin/Referer are forgeable browser-context claims rather than trusted identity; headless lookup uses the constrained System-name Public Tenant Handle; successful lookup accepts tenant-existence disclosure while unknown/disabled/expired failures are identical; exact wire errors, canonical host-only websites, a secure-default local flag, and abuse controls are assigned to EDU-004. This is distinct from the already verified authenticated tenant mismatch rejection in TenantSecurityWebFilter; /education/context still requires EDU-004 Member/UserType enforcement. The most reliable core-loop slice remains provider-neutral fail-closed question content handling across the active default Scalar path, conditional Java path, safe catalog projection, and persisted session restoration. Core-loop schema is not proven to be in active Flyway: V4010 is a placeholder, V4020 is catalog-only, and practice/report/idempotency DDL is untracked manual SQL. Native reads are an intentional explicit-scope bypass requiring mapper audit, while schema foreign keys do not enforce tenant-consistent graphs. Phase 0 coverage must also add first-class Auth/Profile/extended Learning, granular tenant-admin, and granular platform-admin groups. Paid access, provider authority, option schema, public graph semantics, and source baseline remain product/architecture decisions.
|
||||
|
||||
## Verified program decisions
|
||||
|
||||
- Verified source provenance is limited: /Users/tiku1/code/tiku-backend has only main and origin/main at 033701a785c7012139e7f86995eea6041225592e; no local or remote feature/education-core-loop ref exists. Use main/033701a provisionally only, or obtain explicit approval for that baseline.
|
||||
- Verified target branch is feature/education-core-loop and its worktree is dirty. Current read-only inventory reports 65 modified tracked files and 97 untracked entries; preserve all, and do not rely on an older 21-untracked count.
|
||||
- Classify target behavior as committed-and-tested, committed-but-not-runtime-verified, dirty/uncommitted, or absent before scheduling work. ce02f8a is committed core-loop evidence; native provider/catalog and much of the schema are dirty.
|
||||
- Verified V4010 is SELECT 1 and V4020 is native catalog only. Practice/report/idempotency/wrong/favorite DDL in sql/postgresql/education is untracked/manual and not proven active Flyway. Convert required DDL to immutable module-owned PostgreSQL Flyway migrations before claiming schema delivery; never modify published migrations.
|
||||
- Keep PostgreSQL/Flyway as the only new schema delivery mechanism. Historical MySQL files and root SQL are not active delivery unless explicitly labeled archival/manual and removed from operational runbooks.
|
||||
- Treat public tenant resolution origin-binding absence as a P0 correction, not merely a richer-legacy gap. Separately acknowledge that TenantSecurityWebFilter already rejects authenticated tenant/header mismatch; the remaining principal issue is missing Member/UserType enforcement in /education/context.
|
||||
- Treat hostname port handling as a verified internal contradiction requiring alignment across implementation, properties, API documentation, System lookup normalization, and tests.
|
||||
- Treat native catalog isolation as an intentional TenantUtils.executeIgnore/manual-scope boundary, not evidence of a current leak. Make mapper audit and tenant/scope-consistent graph constraints concrete blockers before authoring.
|
||||
- Make the first slice provider-neutral or cover both providers because SCALAR_READ is the verified default and Java provider is conditional. The slice must include fresh browsing and persisted session restoration, with a common option-schema contract and fail-closed behavior.
|
||||
- Do not treat submit idempotency as complete: check-then-insert is not an atomic claim. Reserve keys atomically and define crash recovery before the submit slice.
|
||||
- Add first-class Auth/Profile/extended Learning, tenant appearance/integrations/secrets/codes, and granular platform-admin capability groups so every required legacy cluster has a disposition.
|
||||
- Do not expose paid/private practice until entitlement semantics and public target contracts are decided.
|
||||
- No tests, builds, PostgreSQL connections, Flyway execution, or runtime verification were performed; all conclusions are static repository evidence unless explicitly marked otherwise.
|
||||
|
||||
## Unknowns
|
||||
|
||||
- EDU-003 decided the public resolver threat model and contract. Browser headers are forgeable context claims; a constrained Public Tenant Handle supports headless clients; success discloses tenant existence; unknown/disabled/expired failures are identical; exact errors, canonical websites, local activation, Member-only context, and abuse controls are assigned to EDU-004.
|
||||
- Whether a future System-owned immutable Tenant Code or authenticated/signed locator is required beyond the accepted public-handle contract.
|
||||
- The valid option schema for each question type, including whether absent options are legal; whether malformed published content is omitted or produces a controlled source failure.
|
||||
- Whether PUBLIC tenant_id=0 rows may reference only PUBLIC parents, whether tenant-owned rows may reference global rows, and the precise composite constraint/trigger strategy.
|
||||
- Whether untracked /Users/tiku1/code/ruoyi-vue-pro/sql/postgresql/education files are intended for promotion into Flyway or are design/manual artifacts.
|
||||
- Whether V4010/V4020 or any manual core-loop DDL has ever run successfully in PostgreSQL; no runtime migration evidence exists.
|
||||
- Whether target test H2 MODE=MYSQL is test-only and compatible with PostgreSQL-only delivery.
|
||||
- Which Auth/Profile/extended Learning semantics are replaced by Member/System/Infra versus Education-owned, including vocabulary, leaderboard, stats, trend, feedback, exam dates, notifications, points, and badges.
|
||||
- Whether tenant appearance, domains, payment accounts, auth providers, secrets, activation codes, coupons, integrations, marketing, public-bank grants, and sync are in scope or explicitly retired.
|
||||
- Whether legacy assets are migrated, re-uploaded, re-scanned, or retired, and who owns ClamAV/scanner integration.
|
||||
- Which legacy RLS, triggers, functions, grants, seeds, queue leases, retry behavior, and operational semantics are contractual and need Java/constraint/event/job reproduction.
|
||||
- Whether the ten required Phase 0 artifacts must be committed files or may remain in reviewed scratch form during discovery.
|
||||
17
docs/education/migration/01-capability-matrix.md
Normal file
17
docs/education/migration/01-capability-matrix.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Capability Migration Matrix
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
Statuses are restricted to the Goal vocabulary. Evidence marked as verified is static repository evidence.
|
||||
|
||||
| Legacy capability | Legacy code location | Legacy database objects | Business value | Target module | Existing capability to reuse | Education gap | Other-module change | Priority | Risk | Verification | Status | Evidence | Open decision |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Tenant resolution, identity, and student context | /Users/tiku1/code/tiku-backend/apps/api/src/nest/auth.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/features/tenant/locator.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/features/tenant/resolver.ts | System tenant and website/domain records are authoritative.<br>Legacy tenant, domain, branding, identity, membership, and RLS objects are reference-only and must not be copied mechanically. | Resolves the pre-login tenant and authenticated student context needed to route users into the correct education tenant without trusting client identity. | System + Member + framework tenant support with an Education context adapter | System TenantCommonApi/TenantApiImpl, TenantContextHolder, TenantSecurityWebFilter, Member/System authentication and UserTypeEnum, framework tenant injection and tenant-ignore only for explicitly authorized platform operations. | Verified: EducationTenantController currently accepts caller-supplied hostname or tenantName under @PermitAll. EDU-003 establishes that Origin/Referer are forgeable browser-context claims rather than trusted identity, success discloses available-tenant existence, and legacy tenantName is unsupported. Verified: TenantSecurityWebFilter already rejects authenticated LoginUser/request-tenant mismatches and requires a tenant on non-ignored URLs. Verified: EducationContextController checks login presence and tenant validity but not LoginUser.userType. Verified: hostname documentation says no port while implementation preserves legal ports and tests expect port preservation. Decision: EDU-004 must implement the exact Public Tenant Handle, canonical website, secure local flag, wire-error, Member-principal, redaction, and abuse-control contract. | System/framework tenant and security boundaries remain authoritative; Education adapts them. EDU-003 retained generic System lookup APIs and selected Member-only context enforcement. | P0 | High: wrong pre-login tenant selection, tenant discovery, or treating an admin ID as a Member ID can cross security boundaries. | Add exact Origin/Referer claim, forged-header threat-model, requested-host conflict, explicit handle, legacy tenantName rejection, lifecycle-indistinguishability, canonical website, local-flag, normalization, anonymous, missing-tenant, mismatch, Member/admin-principal, redaction, and abuse-control tests. Static audit is not runtime proof. | partially migrated | Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/controller/app/tenant/EducationTenantController.java:51-63,109-132,159-177.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/security/TenantSecurityWebFilter.java:66-105.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/controller/app/EducationContextController.java:43-57.<br>Verified source baseline /Users/tiku1/code/tiku-backend/apps/api/src/features/tenant/locator.ts:90-151 requires production origin/request-host checks.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/test/java/cn/iocoder/yudao/module/education/controller/app/tenant/EducationTenantResolveIntegrationTest.java:80-89. | EDU-003 accepted: Origin/Referer are forgeable browser-context claims; headless lookup uses the constrained System-name Public Tenant Handle; successful lookup discloses existence while unknown/disabled/expired are indistinguishable; host identity and canonical stored websites are host-only; local fallback has a secure-default flag; context is Member-only. Future signed locator or immutable System Tenant Code remains optional later scope. Source feature ref remains unavailable. |
|
||||
| Student core learning loop | /Users/tiku1/code/tiku-backend/apps/api/src/nest/learning.module.ts:23-113<br>/Users/tiku1/code/tiku-backend/apps/api/src/features/learning/use-cases.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/features/learning/access.ts | Education catalog and practice/report/idempotency/wrong-question/favorite tables.<br>Verified: native catalog V4020 is a dirty module resource; practice/report/idempotency DDL is currently in untracked sql/postgresql/education files rather than proven active Flyway history. | Provides the student loop from published catalog browsing through practice creation, answer saving, restore, submission, report, wrong questions, and favorites. | Education | Education provider/adapter boundary, Member/System identity, database uniqueness and transactions, framework locks/idempotency only as supplements—not replacements—for atomic database claims. | Verified: commit ce02f8a contains committed access/core controllers, safe projections, and focused tests, while native provider/catalog and additional core-loop work are dirty; these statuses must be separated. Verified: native and Scalar providers disagree on malformed/absent options; QuestionCatalogService and SessionResponseAssembler can emit apparently valid empty options. Verified: submit idempotency performs check-then-insert rather than atomic initial reservation. Inference: core-loop completion and concurrency guarantees are not established. | Education owns education-domain state and orchestration; Member/System context is reused. Paid/private access remains blocked on an entitlement decision. | P0 | High: corrupt assessment content, mode-dependent behavior, duplicate state transitions, answer leakage, or unauthorized access. | Provider-neutral tests across Scalar and Java, browsing/collection/practice-create/restore safe projections, malformed/unavailable/unpublished fail-closed cases, cross-tenant cases, and PostgreSQL concurrent same-key/different-key submit tests. | partially migrated | Verified ce02f8a, target repository, for committed EducationAccessService, core controllers/services, projections, and HTTP/service tests.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/config/EducationProperties.java:34-36 defaults to SCALAR_READ.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/integration/scalar/config/ScalarAutoConfiguration.java:30-35 selects Scalar for SCALAR_READ/missing mode.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/catalog/provider/JavaCatalogProvider.java:397-417, ScalarCatalogProvider.java:736-751, QuestionCatalogServiceImpl.java:182-202, SessionResponseAssembler.java:69-89.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/practice/PracticeSessionServiceImpl.java:294-307,397-409.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/sql/postgresql/education/009-education-idempotency-unified.sql:81, but no execution evidence. | Select the pilot-authoritative provider or require a provider-neutral contract; define valid option structure by question type and absent-option semantics; define atomic submit claim/crash recovery; decide entitlement contract before paid/private practice. |
|
||||
| Education catalog and question content | /Users/tiku1/code/tiku-backend/apps/api/src/nest/catalog.module.ts:74-138<br>/Users/tiku1/code/tiku-backend/apps/nest/tenant-content.module.ts | V4020 native catalog tables for regions, schools, majors, subjects, categories, banks, questions, versions, content, collections, blueprints, and bindings.<br>Legacy catalog/question/content/asset tables, constraints, functions, triggers, grants, and RLS are reference objects requiring semantic mapping. | Supplies reusable published catalog, question, classification, and content reads for student and future admin workflows. | Education | Education Provider boundary, explicit CatalogScopeQuery, framework tenant context, Infra File public API for future assets. | Verified: current native reads intentionally run inside TenantUtils.executeIgnore and apply explicit scope predicates; this is a controlled manual-isolation boundary, not proof of a current leak. Verified: V4020 uses ordinary single-column foreign keys, so tenant-owned/public graph consistency is not enforced. Inference: every mapper needs audit and content admission needs composite constraints or equivalent enforcement. | Education owns domain reads; Infra File may later provide asset transport. No provider expansion should occur before provider authority and graph-integrity rules are decided. | P0 | High if manual scope is bypassed or invalid cross-tenant/public relationships are admitted. | Inventory every mapper, provider contract tests, invalid graph insert tests, malformed/unpublished tests, PostgreSQL Flyway syntax/resource-packaging checks, and runtime migration evidence only when executed. | partially migrated | Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/catalog/provider/JavaCatalogProvider.java:82-89.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/dal/mysql/catalog/CatalogScopeQuery.java:12-20.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/resources/db/migration/education/V4020__create_native_catalog.sql:38-123,133-152,160-265,324-386.<br>Verified /Users/tiku1/code/tiku-backend/supabase/migrations/202606210008_content_navigation_practice.sql:3-178. | Choose Scalar-only, native PostgreSQL, or explicit coexistence; define tenant_id=0 PUBLIC graph semantics and composite-key strategy; decide whether source RLS/functions/triggers are contractual. |
|
||||
| Auth, student profile, and extended learning | /Users/tiku1/code/tiku-backend/apps/api/src/nest/auth.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/profile.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/learning.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/features/profile/ | Legacy auth/session/verification/OAuth/phone-binding objects.<br>Legacy profile/check-in/points/tasks/exchange/notifications/badges/feedback/exam-countdown objects.<br>Legacy leaderboard/history/report/stats/trend/vocabulary progress/review/favorites/stats objects. | Covers broader student learning and profile experiences beyond the core loop, preserving discoverable legacy behavior and its disposition. | Member + System + Education, with Infra composition | Member/System auth and profile primitives, System/Infra notifications, Member points/levels where semantics match, Education-specific projections and authorization. | Verified source inventory shows these are distinct required Phase 0 domains, not merely generic context or secondary engagement. Target ownership and compatibility are not established. Inference: the definition-of-done is unsupported until each endpoint/state family is classified. | Member/System own authentication and generic membership; Education owns education-specific profile/progress projections. System/Infra may own notifications, while product owners must decide points, badges, feedback, exams, and vocabulary ownership. | P1 | High for auth compatibility and medium for omitted student progress/profile behavior. | Endpoint/API mapping, principal and tenant tests, profile redaction, progress/report compatibility, vocabulary state transitions, and explicit retired/product-decision checks. | pending migration | Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/auth.module.ts:31-56.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/profile.module.ts:38-87.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/learning.module.ts:23-60,70-113.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/docs/education/migration/GOAL.md:126-141,393-405. | For every Auth/Profile/extended Learning family, assign Member/System/Education/Infra ownership, compatibility requirement, data disposition, and phase; decide vocabulary, analytics, feedback, exam dates, notifications, points, and badges. |
|
||||
| Tenant education operations, appearance, integrations, secrets, and codes | /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-classes.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-appearance.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-integrations.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-secrets.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-codes.module.ts | Legacy classes, student relationships, supervision, roles/configuration, branding/settings/themes, domains, payment accounts, auth-provider configuration, tenant secrets, activation codes, coupons/redemptions, integrations, and marketing objects. | Enables tenant administrators to operate education organizations while preserving separate security and ownership boundaries. | Education + System + Member + Mall/Pay + Infra | System Tenant/RBAC/DataPermission/AdminUserApi, Member relationships, Mall/Pay/Member APIs, Infra secret/file/message/audit facilities. | Verified: classes/supervision were only part of the source tenant-admin surface. Appearance/theme lifecycle, domains/payment/auth integrations, secret rotation, and codes/coupons are separate migration/security surfaces with no verified target equivalent. Inference: collapsing them into one row would hide authorization and secret-handling decisions. | System RBAC/DataPermission and tenant configuration are reused; Mall/Pay/Member own commercial primitives; Infra owns secrets/messaging/files where applicable; Education owns only domain relationships and configuration extensions. | P1 | High: admin scope, secret leakage, payment configuration, and code redemption errors. | Permission matrix, row-scope negatives, secret redaction/rotation, integration authorization, code/coupon idempotency, audit, and cross-tenant tests. | pending migration | Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-appearance.module.ts:17-41.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-integrations.module.ts:18-42.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-secrets.module.ts:13-21.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-codes.module.ts:12-31.<br>Verified /Users/tiku1/code/tiku-backend/supabase/migrations/202606290002_tenant_classes.sql.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/annotation/DataPermission.java:12-32. | Define class/student/teacher scope semantics and separately decide appearance, domain, payment/auth integration, secret, activation-code, coupon, public-bank grant, and marketing ownership or retirement. |
|
||||
| Platform administration and governance | /Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-overview.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-permissions.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-*.module.ts | Legacy platform staff, tenant lifecycle/billing profiles, public question-bank grant/sync, SaaS plan/invoice/usage/overage/dunning, audit/export/alert/notification-channel, and permission objects. | Provides platform staff and governance over tenants, staff lifecycle, public-bank grants, SaaS plans, billing, usage, dunning, audits, alerts, and permissions. | System + Pay + Mall + Infra + CRM with Education extensions | System RBAC/DataPermission/AdminUserApi, authorized tenant-ignore mechanisms, Pay/Mall/Infra/CRM public APIs, audit/logging. | Verified source surface is broader than one aggregated platform-admin row. Target seams exist, but object-level ownership, data scopes, and cross-tenant operation policy remain incomplete. | System, Pay, Mall, Infra, CRM, and Education-specific extension permissions; Education must not duplicate platform ledgers or generic administration. | P1 | High access-control and financial-governance risk. | Permission matrix, platform-admin integration, cross-tenant negative, audit-redaction, billing/usage reconciliation, and alert/export tests. | pending migration | Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-overview.module.ts.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-permissions.module.ts.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/api/permission/PermissionApi.java:12-20.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/service/SecurityFrameworkService.java:7-57. | Define separate Student App, Tenant Admin, Platform Admin, public, and internal policies; map each platform surface to System/Pay/Mall/Infra/CRM/Education or explicit retirement. |
|
||||
| Commercialization and growth | /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-orders.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-payments.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/referral-growth.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/referral-crm.module.ts | Legacy product/order/payment/event/entitlement/coupon/refund/reconciliation/commission/referral/points/dunning objects.<br>Target Mall/Pay/Member tables remain authoritative; Education may add minimal binding records. | Supports paid products, fulfillment, entitlements, refunds, reconciliation, commissions, referrals, and CRM conversion without recreating platform ledgers. | Mall + Pay + Member + CRM with Education binding | Mall/Pay DTO APIs, Member identity/entitlement/points, CRM services, Infra Job/MQ/audit. | Verified target Pay/Mall APIs expose core seams, but scoped entitlement issuance/revocation, activation codes, reconciliation, commissions, dunning, and referral semantics are not proven. One prior evidence path was malformed; corrected source location is /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts. | Mall Trade/Product, Pay, Member entitlement/points, CRM, Infra jobs/events/audit; Education owns product-to-education bindings and fulfillment orchestration only. | P2 | High financial and authorization risk. | Callback/idempotency/amount/refund, entitlement lifecycle, reconciliation, and education fulfillment contract tests. | product decision required | Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/api/order/PayOrderApi.java:13-38.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/api/refund/PayRefundApi.java:12-30.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/api/order/TradeOrderApi.java:12-38.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-orders.module.ts:15-70 and /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/docs/education/migration/GOAL.md:36-40,226-228. | Choose entitlement/activation-code/coupon model and confirm issuance, revocation, callback, refund, reconciliation, commission, and referral contracts before paid practice. |
|
||||
| Background processing, assets, and operational platform | /Users/tiku1/code/tiku-backend/apps/worker/src/worker-jobs.ts<br>/Users/tiku1/code/tiku-backend/apps/worker/src/jobs/imports.ts<br>/Users/tiku1/code/tiku-backend/apps/worker/src/jobs/exports.ts<br>/Users/tiku1/code/tiku-backend/apps/asset-scanner/src/ | Legacy worker queues, leases, retries/dead letters, imports/exports, reconciliation, notification/audit, usage, and security scan state.<br>Target owns business state in domain modules and uses platform execution primitives; do not copy queue tables wholesale. | Preserves operational reliability for imports, exports, payments, CRM, scanning, notifications, retries, and audit while removing dependence on NestJS workers. | Infra platform plus owning domain modules | Infra Job, Redis MQ, File, locks, idempotency, logging, tracing, Excel utilities, tenant propagation. | Verified target primitives exist, but durable claim/lease/heartbeat/retry and malware-scanner equivalence are not proven. Education import/export business state is absent or not verified. | Infra Job/MQ/File/logging/observability plus owning Education/Pay/Mall/CRM handlers; scanner deployment or adapter ownership must be decided. | P1 | High operational and security risk. | Concurrent claim/lease/recovery, retries/dead letters, scan fail-closed, file access, tenant propagation, audit, and deployment smoke tests. | partially migrated | Verified /Users/tiku1/code/tiku-backend/apps/worker/src/worker-jobs.ts:24-220 and /Users/tiku1/code/tiku-backend/apps/worker/src/jobs/imports.ts:87-260.<br>Verified /Users/tiku1/code/tiku-backend/apps/asset-scanner/src/scanner.service.ts:23-50.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-mq/src/main/java/cn/iocoder/yudao/framework/mq/redis/core/RedisMQTemplate.java.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-job/src/main/java/cn/iocoder/yudao/framework/quartz/core/handler/JobHandler.java. | Confirm Infra claim/lease semantics and scanner ownership, file privacy/retention, legacy asset migration/re-scan, and duplicate-safe at-least-once processing. |
|
||||
| Secondary learning, media, AI, and engagement | /Users/tiku1/code/tiku-backend/apps/api/src/nest/scoreline.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/video.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/nest/ai.module.ts<br>/Users/tiku1/code/tiku-backend/apps/api/src/features/profile/ | Legacy scoreline, vocabulary, handbook, video entitlement/progress, recommendation, notification, badge, exam-date, and analytics objects. | Delivers selected recommendation, scoreline, vocabulary, handbook, video, AI, notification, badge, exam-date, and engagement experiences after ownership and priority are explicit. | Education plus AI/Infra/Member/System | AI services, Infra File/notifications, Member points/levels, Education authorization/projections. | Verified legacy capabilities exist, but target equivalence and priority are not established. These cannot remain an undifferentiated P3 bucket if Phase 0 must give every capability a disposition. | AI, Infra File/messaging, Member growth primitives, System notifications, and Education extensions. | P3 | Medium-to-high due to entitlement, media access, sensitive reporting, and unclear scope. | Per-capability contract, authorization, entitlement, export/redaction, and migration compatibility tests. | product decision required | Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/scoreline.module.ts:207-226.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/video.module.ts:431-464.<br>Verified /Users/tiku1/code/tiku-backend/apps/api/src/nest/ai.module.ts:120-139.<br>Verified /Users/tiku1/code/tiku-backend/supabase/migrations/202606210009_content_import_vocabulary_handbook.sql.<br>Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-ai/src/main/java/cn/iocoder/yudao/module/ai/service/chat/AiChatMessageService.java. | For each capability, assign Education, existing platform ownership, explicit retirement, or later product scope; decide entitlement and safe export/redaction requirements. |
|
||||
110
docs/education/migration/02-api-mapping.md
Normal file
110
docs/education/migration/02-api-mapping.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# Legacy API Mapping
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
This Phase 0 artifact maps API families rather than all 342 operations. Endpoint-level method/path/request/response mapping remains required before implementing each family.
|
||||
|
||||
## Tenant resolution, identity, and student context
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/auth.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/features/tenant/locator.ts, /Users/tiku1/code/tiku-backend/apps/api/src/features/tenant/resolver.ts
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** System + Member + framework tenant support with an Education context adapter
|
||||
- **Reuse:** System TenantCommonApi/TenantApiImpl, TenantContextHolder, TenantSecurityWebFilter, Member/System authentication and UserTypeEnum, framework tenant injection and tenant-ignore only for explicitly authorized platform operations.
|
||||
- **Migration conclusion:** decision complete; implementation pending EDU-004
|
||||
- **Selected contract:** Public inputs are **Tenant Locator Claims**, not authenticated identity. Production browser routing derives a host-only claim from valid HTTP(S) `Origin`, falling back to `Referer`; both are forgeable by non-browser callers and provide browser UX consistency only. A supplied hostname may confirm that claim, and disagreement is a conflict. Headless clients use `tenantHandle`, explicitly defined as the target's unique System tenant `name` under a case-sensitive constrained public contract because no distinct stable Tenant Code exists. Legacy public `tenantName` is rejected rather than silently aliased.
|
||||
- **Threat model:** Successful resolution returns tenant ID/display name and therefore permits available-tenant existence probing. Only unknown, disabled, and expired tenants are indistinguishable. Reuse public throttling/ingress controls and structured abuse metrics; a deployment requiring spoof resistance needs a future authenticated/signed locator, not trust in Origin/Referer or forwarding-header controls.
|
||||
- **Normalization and compatibility:** Host identity is lowercase, trimmed, trailing-dot-free, bracket-free for IPv6, and independent of all ports. DNS hosts, IPv4, and IPv6 are accepted when valid; credentials, paths, multi-value input, malformed authorities, and unsupported schemes are rejected. Canonical `system_tenant.websites` values for this resolver are host-only. Scheme/path/port-bearing stored values do not silently normalize or match; configuration correction is required, or a separate Flyway/data ticket if automated correction is later approved.
|
||||
- **Local activation:** Only `yudao.education.tenant-resolution.local-development-enabled=true` enables local/request-host fallback; default and absence are false, and profiles are not authoritative. With the flag true, code-less configured local-host resolution is allowed and an explicit handle takes precedence.
|
||||
- **Authenticated context:** `/education/context` accepts only a Student Principal: an authenticated `LoginUser` with `userType == UserTypeEnum.MEMBER`. User and tenant IDs remain security/tenant-context derived. `TenantSecurityWebFilter` already fills a missing tenant from the authenticated principal, rejects principal/request-tenant mismatch, requires a tenant for non-ignored URLs, and validates tenant availability; EDU-004 preserves rather than duplicates these checks.
|
||||
- **Ownership and seam:** Login-method metadata belongs to Member authentication, not System tenant metadata or Education. EDU-004 removes/deprecates Education `loginMethods` unless a minimal Member-owned interface is proven necessary. Retain generic System-owned `TenantCommonApi`; make lookup methods required and add focused `TenantApiImpl` contract tests. `EducationTenantController` remains the public claim-consistency/redaction adapter.
|
||||
- **Exact public wire contract:** Framework business responses remain HTTP 200. Invalid/malformed/missing/local-forbidden claim is code `1005001003`, message `租户识别请求无效`, null data. Domain/handle or requested-host conflict is code `1005001008`, message `租户识别信息冲突`, null data. Unknown/disabled/expired is code `1005001004`, message `当前租户不可用`, null data, with identical shape. Success is code 0 and data contains only `tenantId` and `displayName`; never expose or echo handle, websites, expiry, package, status, private config, or login methods.
|
||||
- **Required EDU-004 verification:** Education HTTP tests cover Origin resolution, Referer fallback, forged-header threat-model naming, malformed Origin, Origin/requested-host conflict, untrusted arbitrary hostname, explicit handle, legacy tenantName rejection, unavailable-state exact wire equivalence, host normalization, canonical/non-canonical website behavior, local flag false/true and precedence, domain/handle conflict, anonymous/ADMIN/MEMBER context, redaction, and abuse-control attachment/metrics where a reusable seam exists. System owns adapter contract tests; framework owns existing missing-tenant and authenticated mismatch tests.
|
||||
- **Decision evidence:** [`issues/EDU-003-tenant-resolution-decision.md`](issues/EDU-003-tenant-resolution-decision.md). Static only; no production or database change was made.
|
||||
|
||||
## Student core learning loop
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/learning.module.ts:23-113, /Users/tiku1/code/tiku-backend/apps/api/src/features/learning/use-cases.ts, /Users/tiku1/code/tiku-backend/apps/api/src/features/learning/access.ts
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Education
|
||||
- **Reuse:** Education provider/adapter boundary, Member/System identity, database uniqueness and transactions, framework locks/idempotency only as supplements—not replacements—for atomic database claims.
|
||||
- **Migration conclusion:** partially migrated
|
||||
- **Contract gap:** Verified: commit ce02f8a contains committed access/core controllers, safe projections, and focused tests, while native provider/catalog and additional core-loop work are dirty; these statuses must be separated. Verified: native and Scalar providers disagree on malformed/absent options; QuestionCatalogService and SessionResponseAssembler can emit apparently valid empty options. Verified: submit idempotency performs check-then-insert rather than atomic initial reservation. Inference: core-loop completion and concurrency guarantees are not established.
|
||||
- **Required verification:** Provider-neutral tests across Scalar and Java, browsing/collection/practice-create/restore safe projections, malformed/unavailable/unpublished fail-closed cases, cross-tenant cases, and PostgreSQL concurrent same-key/different-key submit tests.
|
||||
- **Open decision:** Select the pilot-authoritative provider or require a provider-neutral contract; define valid option structure by question type and absent-option semantics; define atomic submit claim/crash recovery; decide entitlement contract before paid/private practice.
|
||||
|
||||
## Education catalog and question content
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/catalog.module.ts:74-138, /Users/tiku1/code/tiku-backend/apps/nest/tenant-content.module.ts
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Education
|
||||
- **Reuse:** Education Provider boundary, explicit CatalogScopeQuery, framework tenant context, Infra File public API for future assets.
|
||||
- **Migration conclusion:** partially migrated
|
||||
- **Contract gap:** Verified: current native reads intentionally run inside TenantUtils.executeIgnore and apply explicit scope predicates; this is a controlled manual-isolation boundary, not proof of a current leak. Verified: V4020 uses ordinary single-column foreign keys, so tenant-owned/public graph consistency is not enforced. Inference: every mapper needs audit and content admission needs composite constraints or equivalent enforcement.
|
||||
- **Required verification:** Inventory every mapper, provider contract tests, invalid graph insert tests, malformed/unpublished tests, PostgreSQL Flyway syntax/resource-packaging checks, and runtime migration evidence only when executed.
|
||||
- **Open decision:** Choose Scalar-only, native PostgreSQL, or explicit coexistence; define tenant_id=0 PUBLIC graph semantics and composite-key strategy; decide whether source RLS/functions/triggers are contractual.
|
||||
|
||||
## Auth, student profile, and extended learning
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/auth.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/profile.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/learning.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/features/profile/
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Member + System + Education, with Infra composition
|
||||
- **Reuse:** Member/System auth and profile primitives, System/Infra notifications, Member points/levels where semantics match, Education-specific projections and authorization.
|
||||
- **Migration conclusion:** pending migration
|
||||
- **Contract gap:** Verified source inventory shows these are distinct required Phase 0 domains, not merely generic context or secondary engagement. Target ownership and compatibility are not established. Inference: the definition-of-done is unsupported until each endpoint/state family is classified.
|
||||
- **Required verification:** Endpoint/API mapping, principal and tenant tests, profile redaction, progress/report compatibility, vocabulary state transitions, and explicit retired/product-decision checks.
|
||||
- **Open decision:** For every Auth/Profile/extended Learning family, assign Member/System/Education/Infra ownership, compatibility requirement, data disposition, and phase; decide vocabulary, analytics, feedback, exam dates, notifications, points, and badges.
|
||||
|
||||
## Tenant education operations, appearance, integrations, secrets, and codes
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-classes.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-appearance.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-integrations.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-secrets.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/tenant-admin-codes.module.ts
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Education + System + Member + Mall/Pay + Infra
|
||||
- **Reuse:** System Tenant/RBAC/DataPermission/AdminUserApi, Member relationships, Mall/Pay/Member APIs, Infra secret/file/message/audit facilities.
|
||||
- **Migration conclusion:** pending migration
|
||||
- **Contract gap:** Verified: classes/supervision were only part of the source tenant-admin surface. Appearance/theme lifecycle, domains/payment/auth integrations, secret rotation, and codes/coupons are separate migration/security surfaces with no verified target equivalent. Inference: collapsing them into one row would hide authorization and secret-handling decisions.
|
||||
- **Required verification:** Permission matrix, row-scope negatives, secret redaction/rotation, integration authorization, code/coupon idempotency, audit, and cross-tenant tests.
|
||||
- **Open decision:** Define class/student/teacher scope semantics and separately decide appearance, domain, payment/auth integration, secret, activation-code, coupon, public-bank grant, and marketing ownership or retirement.
|
||||
|
||||
## Platform administration and governance
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-overview.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-permissions.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/platform-admin-*.module.ts
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** System + Pay + Mall + Infra + CRM with Education extensions
|
||||
- **Reuse:** System RBAC/DataPermission/AdminUserApi, authorized tenant-ignore mechanisms, Pay/Mall/Infra/CRM public APIs, audit/logging.
|
||||
- **Migration conclusion:** pending migration
|
||||
- **Contract gap:** Verified source surface is broader than one aggregated platform-admin row. Target seams exist, but object-level ownership, data scopes, and cross-tenant operation policy remain incomplete.
|
||||
- **Required verification:** Permission matrix, platform-admin integration, cross-tenant negative, audit-redaction, billing/usage reconciliation, and alert/export tests.
|
||||
- **Open decision:** Define separate Student App, Tenant Admin, Platform Admin, public, and internal policies; map each platform surface to System/Pay/Mall/Infra/CRM/Education or explicit retirement.
|
||||
|
||||
## Commercialization and growth
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-orders.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-payments.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/referral-growth.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/referral-crm.module.ts
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Mall + Pay + Member + CRM with Education binding
|
||||
- **Reuse:** Mall/Pay DTO APIs, Member identity/entitlement/points, CRM services, Infra Job/MQ/audit.
|
||||
- **Migration conclusion:** product decision required
|
||||
- **Contract gap:** Verified target Pay/Mall APIs expose core seams, but scoped entitlement issuance/revocation, activation codes, reconciliation, commissions, dunning, and referral semantics are not proven. One prior evidence path was malformed; corrected source location is /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts.
|
||||
- **Required verification:** Callback/idempotency/amount/refund, entitlement lifecycle, reconciliation, and education fulfillment contract tests.
|
||||
- **Open decision:** Choose entitlement/activation-code/coupon model and confirm issuance, revocation, callback, refund, reconciliation, commission, and referral contracts before paid practice.
|
||||
|
||||
## Background processing, assets, and operational platform
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/worker/src/worker-jobs.ts, /Users/tiku1/code/tiku-backend/apps/worker/src/jobs/imports.ts, /Users/tiku1/code/tiku-backend/apps/worker/src/jobs/exports.ts, /Users/tiku1/code/tiku-backend/apps/asset-scanner/src/
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Infra platform plus owning domain modules
|
||||
- **Reuse:** Infra Job, Redis MQ, File, locks, idempotency, logging, tracing, Excel utilities, tenant propagation.
|
||||
- **Migration conclusion:** partially migrated
|
||||
- **Contract gap:** Verified target primitives exist, but durable claim/lease/heartbeat/retry and malware-scanner equivalence are not proven. Education import/export business state is absent or not verified.
|
||||
- **Required verification:** Concurrent claim/lease/recovery, retries/dead letters, scan fail-closed, file access, tenant propagation, audit, and deployment smoke tests.
|
||||
- **Open decision:** Confirm Infra claim/lease semantics and scanner ownership, file privacy/retention, legacy asset migration/re-scan, and duplicate-safe at-least-once processing.
|
||||
|
||||
## Secondary learning, media, AI, and engagement
|
||||
|
||||
- **Legacy locations:** /Users/tiku1/code/tiku-backend/apps/api/src/nest/scoreline.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/video.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/nest/ai.module.ts, /Users/tiku1/code/tiku-backend/apps/api/src/features/profile/
|
||||
- **Legacy authorization semantics to preserve:** tenant boundary, principal type, visibility, idempotency, state transitions, and redaction as applicable.
|
||||
- **Target:** Education plus AI/Infra/Member/System
|
||||
- **Reuse:** AI services, Infra File/notifications, Member points/levels, Education authorization/projections.
|
||||
- **Migration conclusion:** product decision required
|
||||
- **Contract gap:** Verified legacy capabilities exist, but target equivalence and priority are not established. These cannot remain an undifferentiated P3 bucket if Phase 0 must give every capability a disposition.
|
||||
- **Required verification:** Per-capability contract, authorization, entitlement, export/redaction, and migration compatibility tests.
|
||||
- **Open decision:** For each capability, assign Education, existing platform ownership, explicit retirement, or later product scope; decide entitlement and safe export/redaction requirements.
|
||||
145
docs/education/migration/03-database-object-mapping.md
Normal file
145
docs/education/migration/03-database-object-mapping.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# Database Object Mapping
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
## Global disposition rules
|
||||
|
||||
- Ordinary education tables and constraints become immutable module-owned PostgreSQL Flyway migrations.
|
||||
- Supabase RLS maps primarily to framework tenant isolation and application authorization, not copied RLS.
|
||||
- RPCs/functions map to Java services unless database execution is demonstrably the better boundary.
|
||||
- Triggers map to transactions, events, jobs, or audit facilities unless database enforcement is required.
|
||||
- Storage maps to Infra File; auth schema maps to Member/System.
|
||||
- Current manual SQL is not considered executed or active Flyway history without runtime evidence.
|
||||
|
||||
## Tenant resolution, identity, and student context
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- System tenant and website/domain records are authoritative.
|
||||
- Legacy tenant, domain, branding, identity, membership, and RLS objects are reference-only and must not be copied mechanically.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** System + Member + framework tenant support with an Education context adapter
|
||||
- **Current status:** partially migrated
|
||||
- **Required cross-module treatment:** System/framework tenant and security boundaries remain authoritative; Education adapts them. EDU-003 retains generic required `TenantCommonApi` lookup methods and assigns Member-only context enforcement to EDU-004.
|
||||
- **Risk:** High: the unauthenticated resolver permits available-tenant existence probing, while wrong authenticated principal/tenant handling can cross security boundaries.
|
||||
- **Accepted decision:** Browser headers are forgeable context claims; headless clients use the constrained System-name Public Tenant Handle; unknown/disabled/expired failures are identical. Canonical website values for Public Tenant Resolution are normalized host-only strings. Scheme/path/port-bearing stored values are not silently normalized and require configuration correction. If automated correction is later required, create a separate Flyway/data ticket and invoke `flyway-postgresql`; EDU-003/EDU-004 authorize no database change.
|
||||
|
||||
## Student core learning loop
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Education catalog and practice/report/idempotency/wrong-question/favorite tables.
|
||||
- Verified: native catalog V4020 is a dirty module resource; practice/report/idempotency DDL is currently in untracked sql/postgresql/education files rather than proven active Flyway history.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Education
|
||||
- **Current status:** partially migrated
|
||||
- **Required cross-module treatment:** Education owns education-domain state and orchestration; Member/System context is reused. Paid/private access remains blocked on an entitlement decision.
|
||||
- **Risk:** High: corrupt assessment content, mode-dependent behavior, duplicate state transitions, answer leakage, or unauthorized access.
|
||||
- **Decision still required:** Select the pilot-authoritative provider or require a provider-neutral contract; define valid option structure by question type and absent-option semantics; define atomic submit claim/crash recovery; decide entitlement contract before paid/private practice.
|
||||
|
||||
## Education catalog and question content
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- V4020 native catalog tables for regions, schools, majors, subjects, categories, banks, questions, versions, content, collections, blueprints, and bindings.
|
||||
- Legacy catalog/question/content/asset tables, constraints, functions, triggers, grants, and RLS are reference objects requiring semantic mapping.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Education
|
||||
- **Current status:** partially migrated
|
||||
- **Required cross-module treatment:** Education owns domain reads; Infra File may later provide asset transport. No provider expansion should occur before provider authority and graph-integrity rules are decided.
|
||||
- **Risk:** High if manual scope is bypassed or invalid cross-tenant/public relationships are admitted.
|
||||
- **Decision still required:** Choose Scalar-only, native PostgreSQL, or explicit coexistence; define tenant_id=0 PUBLIC graph semantics and composite-key strategy; decide whether source RLS/functions/triggers are contractual.
|
||||
|
||||
## Auth, student profile, and extended learning
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Legacy auth/session/verification/OAuth/phone-binding objects.
|
||||
- Legacy profile/check-in/points/tasks/exchange/notifications/badges/feedback/exam-countdown objects.
|
||||
- Legacy leaderboard/history/report/stats/trend/vocabulary progress/review/favorites/stats objects.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Member + System + Education, with Infra composition
|
||||
- **Current status:** pending migration
|
||||
- **Required cross-module treatment:** Member/System own authentication and generic membership; Education owns education-specific profile/progress projections. System/Infra may own notifications, while product owners must decide points, badges, feedback, exams, and vocabulary ownership.
|
||||
- **Risk:** High for auth compatibility and medium for omitted student progress/profile behavior.
|
||||
- **Decision still required:** For every Auth/Profile/extended Learning family, assign Member/System/Education/Infra ownership, compatibility requirement, data disposition, and phase; decide vocabulary, analytics, feedback, exam dates, notifications, points, and badges.
|
||||
|
||||
## Tenant education operations, appearance, integrations, secrets, and codes
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Legacy classes, student relationships, supervision, roles/configuration, branding/settings/themes, domains, payment accounts, auth-provider configuration, tenant secrets, activation codes, coupons/redemptions, integrations, and marketing objects.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Education + System + Member + Mall/Pay + Infra
|
||||
- **Current status:** pending migration
|
||||
- **Required cross-module treatment:** System RBAC/DataPermission and tenant configuration are reused; Mall/Pay/Member own commercial primitives; Infra owns secrets/messaging/files where applicable; Education owns only domain relationships and configuration extensions.
|
||||
- **Risk:** High: admin scope, secret leakage, payment configuration, and code redemption errors.
|
||||
- **Decision still required:** Define class/student/teacher scope semantics and separately decide appearance, domain, payment/auth integration, secret, activation-code, coupon, public-bank grant, and marketing ownership or retirement.
|
||||
|
||||
## Platform administration and governance
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Legacy platform staff, tenant lifecycle/billing profiles, public question-bank grant/sync, SaaS plan/invoice/usage/overage/dunning, audit/export/alert/notification-channel, and permission objects.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** System + Pay + Mall + Infra + CRM with Education extensions
|
||||
- **Current status:** pending migration
|
||||
- **Required cross-module treatment:** System, Pay, Mall, Infra, CRM, and Education-specific extension permissions; Education must not duplicate platform ledgers or generic administration.
|
||||
- **Risk:** High access-control and financial-governance risk.
|
||||
- **Decision still required:** Define separate Student App, Tenant Admin, Platform Admin, public, and internal policies; map each platform surface to System/Pay/Mall/Infra/CRM/Education or explicit retirement.
|
||||
|
||||
## Commercialization and growth
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Legacy product/order/payment/event/entitlement/coupon/refund/reconciliation/commission/referral/points/dunning objects.
|
||||
- Target Mall/Pay/Member tables remain authoritative; Education may add minimal binding records.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Mall + Pay + Member + CRM with Education binding
|
||||
- **Current status:** product decision required
|
||||
- **Required cross-module treatment:** Mall Trade/Product, Pay, Member entitlement/points, CRM, Infra jobs/events/audit; Education owns product-to-education bindings and fulfillment orchestration only.
|
||||
- **Risk:** High financial and authorization risk.
|
||||
- **Decision still required:** Choose entitlement/activation-code/coupon model and confirm issuance, revocation, callback, refund, reconciliation, commission, and referral contracts before paid practice.
|
||||
|
||||
## Background processing, assets, and operational platform
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Legacy worker queues, leases, retries/dead letters, imports/exports, reconciliation, notification/audit, usage, and security scan state.
|
||||
- Target owns business state in domain modules and uses platform execution primitives; do not copy queue tables wholesale.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Infra platform plus owning domain modules
|
||||
- **Current status:** partially migrated
|
||||
- **Required cross-module treatment:** Infra Job/MQ/File/logging/observability plus owning Education/Pay/Mall/CRM handlers; scanner deployment or adapter ownership must be decided.
|
||||
- **Risk:** High operational and security risk.
|
||||
- **Decision still required:** Confirm Infra claim/lease semantics and scanner ownership, file privacy/retention, legacy asset migration/re-scan, and duplicate-safe at-least-once processing.
|
||||
|
||||
## Secondary learning, media, AI, and engagement
|
||||
|
||||
### Source and target objects
|
||||
|
||||
- Legacy scoreline, vocabulary, handbook, video entitlement/progress, recommendation, notification, badge, exam-date, and analytics objects.
|
||||
|
||||
### Disposition
|
||||
|
||||
- **Target owner:** Education plus AI/Infra/Member/System
|
||||
- **Current status:** product decision required
|
||||
- **Required cross-module treatment:** AI, Infra File/messaging, Member growth primitives, System notifications, and Education extensions.
|
||||
- **Risk:** Medium-to-high due to entitlement, media access, sensitive reporting, and unclear scope.
|
||||
- **Decision still required:** For each capability, assign Education, existing platform ownership, explicit retirement, or later product scope; decide entitlement and safe export/redaction requirements.
|
||||
68
docs/education/migration/04-module-reuse-map.md
Normal file
68
docs/education/migration/04-module-reuse-map.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Module Reuse Map
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
Education must call public APIs, framework extension points, or events. It must not depend on another module's internal ServiceImpl, Mapper, or DO.
|
||||
|
||||
## Tenant resolution, identity, and student context
|
||||
|
||||
- **Target owner:** System + Member + framework tenant support with an Education context adapter
|
||||
- **Public/framework capability to reuse:** System TenantCommonApi/TenantApiImpl, TenantContextHolder, TenantSecurityWebFilter, Member/System authentication and UserTypeEnum, framework tenant injection and tenant-ignore only for explicitly authorized platform operations.
|
||||
- **Education-owned gap:** Verified: EducationTenantController accepts caller-supplied hostname or tenantName under @PermitAll and does not enforce the source resolver's production Origin/Referer/request-host binding. Verified: TenantSecurityWebFilter already rejects authenticated LoginUser/request-tenant mismatches and requires a tenant on non-ignored URLs. Verified: EducationContextController checks login presence and tenant validity but not LoginUser.userType. Verified: hostname documentation says no port while implementation preserves legal ports and tests expect port preservation. Inference: arbitrary tenant discovery, admin-principal acceptance, and port inconsistency are P0/P1 trust-boundary risks until policy is fixed.
|
||||
- **Allowed external-module change:** System/framework tenant and security boundaries remain authoritative; Education should only adapt them. A generic tenant lookup contract and possibly Member-only context policy require explicit decisions.
|
||||
|
||||
## Student core learning loop
|
||||
|
||||
- **Target owner:** Education
|
||||
- **Public/framework capability to reuse:** Education provider/adapter boundary, Member/System identity, database uniqueness and transactions, framework locks/idempotency only as supplements—not replacements—for atomic database claims.
|
||||
- **Education-owned gap:** Verified: commit ce02f8a contains committed access/core controllers, safe projections, and focused tests, while native provider/catalog and additional core-loop work are dirty; these statuses must be separated. Verified: native and Scalar providers disagree on malformed/absent options; QuestionCatalogService and SessionResponseAssembler can emit apparently valid empty options. Verified: submit idempotency performs check-then-insert rather than atomic initial reservation. Inference: core-loop completion and concurrency guarantees are not established.
|
||||
- **Allowed external-module change:** Education owns education-domain state and orchestration; Member/System context is reused. Paid/private access remains blocked on an entitlement decision.
|
||||
|
||||
## Education catalog and question content
|
||||
|
||||
- **Target owner:** Education
|
||||
- **Public/framework capability to reuse:** Education Provider boundary, explicit CatalogScopeQuery, framework tenant context, Infra File public API for future assets.
|
||||
- **Education-owned gap:** Verified: current native reads intentionally run inside TenantUtils.executeIgnore and apply explicit scope predicates; this is a controlled manual-isolation boundary, not proof of a current leak. Verified: V4020 uses ordinary single-column foreign keys, so tenant-owned/public graph consistency is not enforced. Inference: every mapper needs audit and content admission needs composite constraints or equivalent enforcement.
|
||||
- **Allowed external-module change:** Education owns domain reads; Infra File may later provide asset transport. No provider expansion should occur before provider authority and graph-integrity rules are decided.
|
||||
|
||||
## Auth, student profile, and extended learning
|
||||
|
||||
- **Target owner:** Member + System + Education, with Infra composition
|
||||
- **Public/framework capability to reuse:** Member/System auth and profile primitives, System/Infra notifications, Member points/levels where semantics match, Education-specific projections and authorization.
|
||||
- **Education-owned gap:** Verified source inventory shows these are distinct required Phase 0 domains, not merely generic context or secondary engagement. Target ownership and compatibility are not established. Inference: the definition-of-done is unsupported until each endpoint/state family is classified.
|
||||
- **Allowed external-module change:** Member/System own authentication and generic membership; Education owns education-specific profile/progress projections. System/Infra may own notifications, while product owners must decide points, badges, feedback, exams, and vocabulary ownership.
|
||||
|
||||
## Tenant education operations, appearance, integrations, secrets, and codes
|
||||
|
||||
- **Target owner:** Education + System + Member + Mall/Pay + Infra
|
||||
- **Public/framework capability to reuse:** System Tenant/RBAC/DataPermission/AdminUserApi, Member relationships, Mall/Pay/Member APIs, Infra secret/file/message/audit facilities.
|
||||
- **Education-owned gap:** Verified: classes/supervision were only part of the source tenant-admin surface. Appearance/theme lifecycle, domains/payment/auth integrations, secret rotation, and codes/coupons are separate migration/security surfaces with no verified target equivalent. Inference: collapsing them into one row would hide authorization and secret-handling decisions.
|
||||
- **Allowed external-module change:** System RBAC/DataPermission and tenant configuration are reused; Mall/Pay/Member own commercial primitives; Infra owns secrets/messaging/files where applicable; Education owns only domain relationships and configuration extensions.
|
||||
|
||||
## Platform administration and governance
|
||||
|
||||
- **Target owner:** System + Pay + Mall + Infra + CRM with Education extensions
|
||||
- **Public/framework capability to reuse:** System RBAC/DataPermission/AdminUserApi, authorized tenant-ignore mechanisms, Pay/Mall/Infra/CRM public APIs, audit/logging.
|
||||
- **Education-owned gap:** Verified source surface is broader than one aggregated platform-admin row. Target seams exist, but object-level ownership, data scopes, and cross-tenant operation policy remain incomplete.
|
||||
- **Allowed external-module change:** System, Pay, Mall, Infra, CRM, and Education-specific extension permissions; Education must not duplicate platform ledgers or generic administration.
|
||||
|
||||
## Commercialization and growth
|
||||
|
||||
- **Target owner:** Mall + Pay + Member + CRM with Education binding
|
||||
- **Public/framework capability to reuse:** Mall/Pay DTO APIs, Member identity/entitlement/points, CRM services, Infra Job/MQ/audit.
|
||||
- **Education-owned gap:** Verified target Pay/Mall APIs expose core seams, but scoped entitlement issuance/revocation, activation codes, reconciliation, commissions, dunning, and referral semantics are not proven. One prior evidence path was malformed; corrected source location is /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts.
|
||||
- **Allowed external-module change:** Mall Trade/Product, Pay, Member entitlement/points, CRM, Infra jobs/events/audit; Education owns product-to-education bindings and fulfillment orchestration only.
|
||||
|
||||
## Background processing, assets, and operational platform
|
||||
|
||||
- **Target owner:** Infra platform plus owning domain modules
|
||||
- **Public/framework capability to reuse:** Infra Job, Redis MQ, File, locks, idempotency, logging, tracing, Excel utilities, tenant propagation.
|
||||
- **Education-owned gap:** Verified target primitives exist, but durable claim/lease/heartbeat/retry and malware-scanner equivalence are not proven. Education import/export business state is absent or not verified.
|
||||
- **Allowed external-module change:** Infra Job/MQ/File/logging/observability plus owning Education/Pay/Mall/CRM handlers; scanner deployment or adapter ownership must be decided.
|
||||
|
||||
## Secondary learning, media, AI, and engagement
|
||||
|
||||
- **Target owner:** Education plus AI/Infra/Member/System
|
||||
- **Public/framework capability to reuse:** AI services, Infra File/notifications, Member points/levels, Education authorization/projections.
|
||||
- **Education-owned gap:** Verified legacy capabilities exist, but target equivalence and priority are not established. These cannot remain an undifferentiated P3 bucket if Phase 0 must give every capability a disposition.
|
||||
- **Allowed external-module change:** AI, Infra File/messaging, Member growth primitives, System notifications, and Education extensions.
|
||||
34
docs/education/migration/05-commit-review-11e9cc6.md
Normal file
34
docs/education/migration/05-commit-review-11e9cc6.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Commit Review: 11e9cc68547cf271b9d5de60bf41b3f71899d1db (11e9cc6), target repository
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
## Retain
|
||||
|
||||
- Education reactor registration, Member/server activation, Education server dependency, allocated error-code range, and XML correction unless later evidence disproves necessity.
|
||||
|
||||
## Adjust
|
||||
|
||||
- Treat historical MySQL schema/seed/rollback as archival or explicitly manual only; it is not a PostgreSQL/Flyway delivery path.
|
||||
- If global menu entries 6800/6801 remain required, replace them with an approved Education-owned PostgreSQL Flyway seed migration.
|
||||
- Remove operational documentation that invokes mysql or destructive rollback scripts; use forward correction and audited administrative procedures.
|
||||
|
||||
## Replace
|
||||
|
||||
- Required seed behavior with higher-version immutable PostgreSQL Flyway migration.
|
||||
|
||||
## Remove by forward correction
|
||||
|
||||
- README/runbook claims of MySQL active delivery and destructive rollback.
|
||||
- The MySQL menu seed as active delivery after approved Flyway replacement.
|
||||
|
||||
## Pending decisions
|
||||
|
||||
- Whether menu entries 6800/6801 remain product scope.
|
||||
- Whether historical sql/mysql/education artifacts remain labeled archival/manual material.
|
||||
|
||||
## Evidence
|
||||
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/pom.xml:18-19.
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-server/pom.xml:35-47.
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/exception/enums/ServiceErrorCodeRange.java:31-46.
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/sql/mysql/education/000-education-schema.sql:1-5, 000-education-seed.sql:1-15, 000-education-rollback.sql:1-8.
|
||||
37
docs/education/migration/06-commit-review-0f846fd.md
Normal file
37
docs/education/migration/06-commit-review-0f846fd.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Commit Review: 0f846fdaf5377f00347b05b9950b53f92e4dc6df (0f846fd), target repository
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
## Retain
|
||||
|
||||
- TenantApiImpl public-service dependency, @PermitAll/@TenantIgnore pre-login route subject to security tests, and context derived from framework state rather than request tenant/user IDs.
|
||||
|
||||
## Adjust
|
||||
|
||||
- Retain TenantCommonApi/TenantApiImpl as a candidate generic lookup seam, but add contract tests and resolve DTO/null/serialization compatibility.
|
||||
- Replace unsupported default methods with abstract methods or a separate optional capability interface unless compatibility evidence requires them.
|
||||
- Make public resolution origin-binding, principal policy, port policy, and loginMethods ownership explicit.
|
||||
- Correct contradictory hostname documentation and test filter-chain/API behavior.
|
||||
|
||||
## Replace
|
||||
|
||||
- Unsupported default-method expansion with the selected interface design.
|
||||
|
||||
## Remove by forward correction
|
||||
|
||||
- Contradictory hostname/loginMethods documentation after policy decision.
|
||||
|
||||
## Pending decisions
|
||||
|
||||
- Public origin-binding versus intentionally public lookup.
|
||||
- Member-only context versus System/admin support.
|
||||
- Host-only versus authority-with-port identity.
|
||||
- Platform ownership of loginMethods and public error taxonomy.
|
||||
|
||||
## Evidence
|
||||
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/biz/system/tenant/TenantCommonApi.java:28-56.
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/biz/system/tenant/dto/TenantRespDTO.java:14-42.
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java:19-49.
|
||||
- Verified /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/controller/app/tenant/EducationTenantController.java:51-177 and /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/controller/app/EducationContextController.java:43-57.
|
||||
- Verified mismatch rejection in /Users/tiku1/code/ruoyi-vue-pro/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/security/TenantSecurityWebFilter.java:66-105.
|
||||
67
docs/education/migration/07-decisions.md
Normal file
67
docs/education/migration/07-decisions.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# Architecture and Product Decisions
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
## Decisions and constraints established by static evidence
|
||||
|
||||
### EDU-003 accepted decision — tenant resolution and student principal
|
||||
|
||||
The durable rationale, threat model, exact wire contract, compatibility policy, and EDU-004 test matrix are recorded in [`issues/EDU-003-tenant-resolution-decision.md`](issues/EDU-003-tenant-resolution-decision.md).
|
||||
|
||||
1. A **Tenant Locator Claim** is unauthenticated input, not identity. Browser `Origin` then `Referer` provides browser-context consistency evidence but is forgeable by non-browser callers.
|
||||
2. A supplied hostname may only confirm browser-context evidence; disagreement is a conflict. Preserving browser headers or rejecting forwarding-header forgery does not authenticate `Origin`/`Referer`.
|
||||
3. Headless clients use `tenantHandle`. The target currently has no distinct stable Tenant Code, so this is explicitly the unique System tenant `name` under a case-sensitive `^[A-Za-z0-9._-]{2,64}$`, operationally immutable public contract. Legacy public `tenantName` is rejected rather than aliased.
|
||||
4. Public resolution discloses tenant existence on success. The guarantee is only that unknown, disabled, and expired tenants share one response. Reuse public throttling/ingress controls and emit structured probing metrics; spoof-resistant deployments require a future signed/authenticated locator.
|
||||
5. Host identity is lowercase, trimmed, trailing-dot-free, bracket-free for IPv6, and port-independent. Canonical System website entries for this resolver are host-only; non-canonical scheme/path/port entries do not match and require configuration correction or a separately scoped Flyway/data ticket.
|
||||
6. Local fallback is enabled only by `yudao.education.tenant-resolution.local-development-enabled`, default `false`; profiles do not enable it. With the flag true, code-less configured local-host resolution is permitted, while an explicit handle takes precedence.
|
||||
7. `/education/context` is Member-only, obtains the full `LoginUser`, and continues deriving IDs only from security and tenant contexts. `TenantSecurityWebFilter` remains responsible for authenticated missing-tenant, mismatch, and availability checks.
|
||||
8. Login-method metadata belongs to Member authentication. EDU-004 removes/deprecates Education `loginMethods` unless a minimal Member-owned interface is first proven necessary.
|
||||
9. Exact public business failures use HTTP 200/CommonResult: invalid locator `1005001003` / `租户识别请求无效`; conflict `1005001008` / `租户识别信息冲突`; unknown/disabled/expired `1005001004` / `当前租户不可用`; all have null data and redacted detail. Success is code 0 and only `tenantId` plus `displayName`.
|
||||
10. Retain `TenantCommonApi` as the generic System-owned seam. EDU-004 makes lookup methods required and adds System-owned `TenantApiImpl` contract tests; no Education locator concept enters System.
|
||||
11. EDU-003 made no production, database, or Flyway change; verification is static only.
|
||||
|
||||
### EDU-005 accepted decision — PostgreSQL/Flyway takeover
|
||||
|
||||
The durable artifact classification, adoption matrix, version allocation, backfill policy, documentation corrections, and real-PostgreSQL verification gates are recorded in [`issues/EDU-005-flyway-takeover-decision.md`](issues/EDU-005-flyway-takeover-decision.md).
|
||||
|
||||
1. Education schema delivery is exclusively module-owned PostgreSQL Flyway under `yudao-module-education/src/main/resources/db/migration/education/`; root PostgreSQL scripts are manual bootstrap/design history and MySQL scripts are obsolete archives.
|
||||
2. V4010 (`SELECT 1`) and V4020 (native catalog) remain byte-for-byte frozen because execution outside the inspected environment is unverified. The next planned project-wide version is V4030, subject to a fresh version scan at implementation time.
|
||||
3. V4030 owns the final Practice core-loop schema, including sessions/questions, reports/details, wrong questions, favorites, and unified `education_idempotency`. Fresh schema does not create legacy answer/submit idempotency tables.
|
||||
4. Existing manually bootstrapped databases require explicit schema comparison and adoption. A verified V4020-equivalent catalog may use an environment-specific 4020 baseline; incompatible environments require a higher-version correction, never falsified history.
|
||||
5. Legacy idempotency data is backfilled into the unified table before any later forward cleanup. Legacy tables are preserved during initial adoption.
|
||||
6. The Education capability menu seed is a separate conditional V4040 owner only if the administrator endpoint remains approved; role assignment is not seeded.
|
||||
7. Docker/manual SQL initialization and MySQL rollback runbooks must be removed from active operations when EDU-006 lands. EDU-016's temporary test bridge becomes Flyway-driven after equivalence is proven.
|
||||
8. The inspected local disposable `postgresdb` had no Flyway history and no Education tables. EDU-005 ran no migration and makes no migration-success claim.
|
||||
|
||||
### Other established constraints
|
||||
|
||||
1. Verified source provenance is limited: /Users/tiku1/code/tiku-backend has only main and origin/main at 033701a785c7012139e7f86995eea6041225592e; no local or remote feature/education-core-loop ref exists. Use main/033701a provisionally only, or obtain explicit approval for that baseline.
|
||||
2. Verified target branch is feature/education-core-loop and its worktree is dirty. Preserve all existing changes and classify current state at execution time.
|
||||
3. Classify target behavior as committed-and-tested, committed-but-not-runtime-verified, dirty/uncommitted, or absent before scheduling work. ce02f8a is committed core-loop evidence; native provider/catalog and much of the schema are dirty.
|
||||
4. Verified V4010 is SELECT 1 and V4020 is native catalog only. Practice/report/idempotency/wrong/favorite DDL in sql/postgresql/education is untracked/manual and not proven active Flyway. Convert required DDL to immutable module-owned PostgreSQL Flyway migrations before claiming schema delivery; never modify published migrations.
|
||||
5. Keep PostgreSQL/Flyway as the only new schema delivery mechanism. Historical MySQL files and root SQL are not active delivery unless explicitly labeled archival/manual and removed from operational runbooks.
|
||||
6. Treat public tenant resolution as an unauthenticated disclosure surface requiring exact redaction and abuse controls. Separately preserve `TenantSecurityWebFilter` authenticated mismatch checks; the remaining principal issue is Member/UserType enforcement in `/education/context`.
|
||||
7. Treat hostname port and stored-website representation as verified contradictions requiring alignment across implementation, properties, API documentation, System lookup behavior, configuration, and tests.
|
||||
8. Treat native catalog isolation as an intentional TenantUtils.executeIgnore/manual-scope boundary, not evidence of a current leak. Make mapper audit and tenant/scope-consistent graph constraints concrete blockers before authoring.
|
||||
9. Make the first slice provider-neutral or cover both providers because SCALAR_READ is the verified default and Java provider is conditional. The slice must include fresh browsing and persisted session restoration, with a common option-schema contract and fail-closed behavior.
|
||||
10. Do not treat submit idempotency as complete: check-then-insert is not an atomic claim. Reserve keys atomically and define crash recovery before the submit slice.
|
||||
11. Add first-class Auth/Profile/extended Learning, tenant appearance/integrations/secrets/codes, and granular platform-admin capability groups so every required legacy cluster has a disposition.
|
||||
12. Do not expose paid/private practice until entitlement semantics and public target contracts are decided.
|
||||
13. No tests, builds, PostgreSQL connections, Flyway execution, or runtime verification were performed by the Phase 0 assessment unless a later ticket explicitly records otherwise.
|
||||
|
||||
## Unresolved decisions
|
||||
|
||||
1. The valid option schema for each question type, including whether absent options are legal; whether malformed published content is omitted or produces a controlled source failure.
|
||||
2. Whether PUBLIC tenant_id=0 rows may reference only PUBLIC parents, whether tenant-owned rows may reference global rows, and the precise composite constraint/trigger strategy.
|
||||
3. Whether untracked /Users/tiku1/code/ruoyi-vue-pro/sql/postgresql/education files are intended for promotion into Flyway or are design/manual artifacts.
|
||||
4. Whether V4010/V4020 or any manual core-loop DDL has ever run successfully in PostgreSQL; no runtime migration evidence exists.
|
||||
5. Which Auth/Profile/extended Learning semantics are replaced by Member/System/Infra versus Education-owned, including vocabulary, leaderboard, stats, trend, feedback, exam dates, notifications, points, and badges.
|
||||
6. Whether tenant appearance, domains, payment accounts, auth providers, secrets, activation codes, coupons, integrations, marketing, public-bank grants, and sync are in scope or explicitly retired.
|
||||
7. Whether legacy assets are migrated, re-uploaded, re-scanned, or retired, and who owns ClamAV/scanner integration.
|
||||
8. Which legacy RLS, triggers, functions, grants, seeds, queue leases, retry behavior, and operational semantics are contractual and need Java/constraint/event/job reproduction.
|
||||
9. Whether the ten required Phase 0 artifacts must be committed files or may remain in reviewed scratch form during discovery.
|
||||
10. Whether a future System-owned immutable Tenant Code or signed bootstrap locator is required beyond the accepted public-handle/existence-disclosure contract.
|
||||
|
||||
## Decision rule
|
||||
|
||||
Questions answerable from code, Git history, configuration, tests, or documentation must be investigated. Only genuine product choices should be escalated. Hard-to-reverse decisions should become ADRs before dependent implementation begins.
|
||||
165
docs/education/migration/08-slice-roadmap.md
Normal file
165
docs/education/migration/08-slice-roadmap.md
Normal file
@@ -0,0 +1,165 @@
|
||||
# Vertical Slice Roadmap
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
Tickets are vertical behaviors, not technical layers. Work blockers first and use a fresh implementation context per ticket.
|
||||
|
||||
## EDU-P0-S0 — Baseline, completeness, and architecture decision gate
|
||||
|
||||
- **Outcome:** Verified baseline, capability/API/database/module-reuse maps, commit reviews, decision register, corrected documentation plan, and bounded first-slice specification.
|
||||
- **Risk:** High provenance and operational risk; no implementation should begin from an unclassified dirty baseline.
|
||||
- **Blockers:**
|
||||
- Obtain or explicitly approve source baseline main/033701a because no source feature/education-core-loop ref exists.
|
||||
- Record current target status and preserve all 65 modified tracked and 97 untracked entries.
|
||||
- Complete the ten GOAL.md Phase 0 artifact dispositions and separate committed, dirty, absent, and runtime-unverified behavior.
|
||||
- Decide tenant origin-binding, principal policy, provider authority, option schema, and PUBLIC graph semantics.
|
||||
- **Verification:**
|
||||
- Read GOAL.md and target/source rules and module documentation.
|
||||
- Record both Git statuses, histories, and refs without destructive commands.
|
||||
- Review 11e9cc6, 0f846fd, and committed core-loop evidence ce02f8a.
|
||||
- Confirm no tests, builds, PostgreSQL connections, Flyway migrations, or runtime flows were executed.
|
||||
- Inventory Auth/Profile/extended Learning, granular tenant-admin, platform-admin, worker/scanner, and database object surfaces.
|
||||
|
||||
## EDU-P0-S1 — Provider-neutral safe question and session restoration
|
||||
|
||||
- **Outcome:** Both provider modes and restored sessions fail closed for malformed/unavailable published question content while preserving tenant scope and safe projections.
|
||||
- **Risk:** Medium implementation risk and high assessment-integrity/security risk if any alternate path remains fail-open.
|
||||
- **Blockers:**
|
||||
- EDU-P0-S0 provider and option-contract decisions.
|
||||
- Existing dirty provider/session files must be separated from unrelated work.
|
||||
- Safe response and question-type option semantics must be fixed.
|
||||
- **Verification:**
|
||||
- Provider contract tests for Scalar and Java.
|
||||
- Browsing, collection, practice-create/restore, malformed, unavailable, unpublished, cross-tenant, PUBLIC, and sensitive-field tests.
|
||||
- Run focused tests/compile/diff checks only after authorization and report exact results.
|
||||
|
||||
## EDU-P2-S2 — Create and restore practice
|
||||
|
||||
- **Outcome:** A student creates and restores a tenant-scoped practice session from valid published content without client-supplied identity or tenant IDs.
|
||||
- **Risk:** Medium; session ownership, graph scope, and schema packaging require negative tests.
|
||||
- **Blockers:**
|
||||
- EDU-P0-S1 safe-content contract.
|
||||
- Core-loop schema must be promoted into active module-owned Flyway history.
|
||||
- Provider authority and existing dirty session implementation classification.
|
||||
- **Verification:**
|
||||
- Tenant/user context and Member-principal tests.
|
||||
- Restore ownership, cross-tenant denial, PUBLIC-scope tests.
|
||||
- PostgreSQL uniqueness, transaction, packaging, and migration execution checks if schema changes are approved.
|
||||
|
||||
## EDU-P2-S3 — Idempotent answer save
|
||||
|
||||
- **Outcome:** A student saves one answer idempotently with explicit duplicate/conflicting-payload semantics and no sensitive-field exposure.
|
||||
- **Risk:** Medium-to-high due to concurrent writes, stale versions, and answer leakage.
|
||||
- **Blockers:**
|
||||
- EDU-P2-S2 session state.
|
||||
- Existing answer/idempotency schema and option snapshot contract.
|
||||
- Entitlement decision for non-public/private content.
|
||||
- **Verification:**
|
||||
- Same-payload duplicate and conflicting-payload tests.
|
||||
- Concurrent PostgreSQL uniqueness/transaction tests.
|
||||
- Tenant isolation, stale-version, safe-response, and malformed-snapshot tests.
|
||||
|
||||
## EDU-P2-S4 — Atomic submit, report, wrong questions, and favorites
|
||||
|
||||
- **Outcome:** A student atomically claims and submits a session, reads an immutable report, and receives consistent wrong-question/favorite projections.
|
||||
- **Risk:** High; current check-then-insert submit idempotency is not sufficient.
|
||||
- **Blockers:**
|
||||
- EDU-P2-S3 answer state.
|
||||
- Atomic submit-key reservation and crash recovery design.
|
||||
- Scoring/report immutability and entitlement decisions.
|
||||
- **Verification:**
|
||||
- ON CONFLICT/atomic claim concurrency tests.
|
||||
- Processing-row crash recovery and retry semantics.
|
||||
- Immutable report/scoring, duplicate submission, wrong-question/favorite idempotency, sensitive-field, tenant, and unauthorized tests.
|
||||
|
||||
## EDU-P3-S5 — Tenant content publication and graph integrity
|
||||
|
||||
- **Outcome:** Tenant administrators author, classify, publish, and safely retire question content with tenant-consistent graph integrity.
|
||||
- **Risk:** High due to publication, admin scope, public graph, and student-read consistency.
|
||||
- **Blockers:**
|
||||
- Core loop verified.
|
||||
- Provider and education content model decisions.
|
||||
- System RBAC/DataPermission policy.
|
||||
- **Verification:**
|
||||
- Admin permission/row-scope tests.
|
||||
- Composite tenant/scope relationship constraint or equivalent enforcement tests.
|
||||
- Publication visibility/provider consistency and safe-projection regression tests.
|
||||
|
||||
## EDU-P3-S6 — Content imports, exports, assets, and scanning
|
||||
|
||||
- **Outcome:** Tenant administrators import/export education content with durable business state, leases, retries, duplicate-safe processing, file security, and audit.
|
||||
- **Risk:** High operational and security risk.
|
||||
- **Blockers:**
|
||||
- Publication model.
|
||||
- Infra File contract and scanner ownership.
|
||||
- Infra Job/MQ durable claim/lease semantics.
|
||||
- **Verification:**
|
||||
- Preview/execute state machine.
|
||||
- Atomic claim/lease/heartbeat/expiry/retry/dead-letter tests.
|
||||
- MIME/size/object-key/scan fail-closed tests.
|
||||
- Tenant propagation, audit redaction, and partial-failure tests.
|
||||
|
||||
## EDU-P4-S7 — Classes and education relationships
|
||||
|
||||
- **Outcome:** Tenant administrators manage classes, education student relationships, invitations, supervision, and education operations with explicit scope.
|
||||
- **Risk:** High authorization risk.
|
||||
- **Blockers:**
|
||||
- Education relationship model.
|
||||
- System RBAC/DataPermission scope rules.
|
||||
- Member relationship contract and CRM supervision decision.
|
||||
- **Verification:**
|
||||
- Student/teacher/class permission matrix.
|
||||
- Cross-class/cross-tenant negative and duplicate invitation tests.
|
||||
- Audit redaction and operation-log tests.
|
||||
|
||||
## EDU-P4-S8 — Tenant configuration, integrations, and access operations
|
||||
|
||||
- **Outcome:** Selected tenant appearance, integrations, secrets, activation codes, coupons, and public-bank access capabilities have explicit owners and safe contracts.
|
||||
- **Risk:** High because secret, payment configuration, redemption, and public-bank synchronization boundaries differ.
|
||||
- **Blockers:**
|
||||
- Appearance/domain/integration/secrets/codes ownership decisions.
|
||||
- System tenant configuration and secret APIs.
|
||||
- Mall/Pay/Member entitlement and code contracts.
|
||||
- **Verification:**
|
||||
- Secret redaction/rotation and authorization tests.
|
||||
- Domain/auth-provider/payment-account configuration tests.
|
||||
- Code/coupon redemption idempotency and audit tests.
|
||||
- Public-bank grant/sync and cross-tenant tests.
|
||||
|
||||
## EDU-P5-S9 — Education commercialization binding
|
||||
|
||||
- **Outcome:** Education products bind to commerce purchases and Member entitlements without duplicated financial ledgers.
|
||||
- **Risk:** High financial and authorization risk.
|
||||
- **Blockers:**
|
||||
- Product binding model.
|
||||
- Mall/Pay public APIs.
|
||||
- Member entitlement decision and callback/refund semantics.
|
||||
- **Verification:**
|
||||
- Order/payment/refund callback contracts.
|
||||
- Entitlement issuance/revocation/expiry and idempotent fulfillment.
|
||||
- Reconciliation, commission/referral, authorization, and audit tests.
|
||||
|
||||
## EDU-P5-S10 — Extended student and secondary learning waves
|
||||
|
||||
- **Outcome:** Selected Auth/Profile/extended Learning/scoreline/vocabulary/video/AI/notification/badge/exam capabilities are migrated, replaced, retired, or deferred with traceable decisions.
|
||||
- **Risk:** Medium-to-high due to omitted student contracts, media entitlement, and unclear ownership.
|
||||
- **Blockers:**
|
||||
- Explicit scope for each secondary capability.
|
||||
- AI/File/Member/System/Infra contracts and entitlement model.
|
||||
- **Verification:**
|
||||
- Per-capability endpoint/data/authorization contract tests.
|
||||
- Progress/report/vocabulary state tests.
|
||||
- Media entitlement, safe export/redaction, tenant isolation, and retirement compatibility tests.
|
||||
|
||||
## EDU-P6-S11 — Operational independence and legacy exit
|
||||
|
||||
- **Outcome:** Background and platform operations run independently of NestJS with documented retries, scanning, audit, notifications, observability, and deployment evidence.
|
||||
- **Risk:** High deployment and reliability risk.
|
||||
- **Blockers:**
|
||||
- All owner and contract decisions.
|
||||
- Operational deployment, scanner, observability, and legacy exit plan.
|
||||
- **Verification:**
|
||||
- Worker/job deployment smoke tests.
|
||||
- At-least-once duplicate/dead-letter and scanner health/security tests.
|
||||
- PostgreSQL migration execution evidence.
|
||||
- Runbook and documentation consistency review.
|
||||
51
docs/education/migration/09-first-slice.md
Normal file
51
docs/education/migration/09-first-slice.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# First Recommended Slice: EDU-P0-S1
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
## Provider-neutral fail-closed safe question browsing and session restoration
|
||||
|
||||
### Rationale
|
||||
|
||||
The initial native-only slice was corrected because SCALAR_READ is the verified default and JavaCatalogProvider is conditional. A provider-neutral safe-content contract is the smallest observable correction that addresses both active and optional paths, avoids provider-authority assumptions, protects the dirty worktree, and covers the second fail-open path in restored sessions.
|
||||
|
||||
### Scope
|
||||
|
||||
- Define and document the common option validity contract, including whether absent options are legal for each question type; invalid published question payloads must be omitted or return a controlled failure, never an apparently valid empty-options question.
|
||||
- Apply and test the contract for both ScalarCatalogProvider and JavaCatalogProvider, despite SCALAR_READ being the current default, so provider mode cannot change safety behavior.
|
||||
- Apply and test safe projection for single-question browsing and collection/catalog browsing paths.
|
||||
- Make SessionResponseAssembler reject, mark unavailable, or otherwise fail closed on malformed persisted snapshots; do not silently convert parse failure to an empty list.
|
||||
- Verify publication/status/visibility and unavailable-provider fail-closed behavior at the service boundary.
|
||||
- Add cross-tenant and PUBLIC-scope negative tests, while recording that current native reads use an intentional TenantUtils.executeIgnore/manual predicate boundary.
|
||||
- Separate committed behavior from dirty behavior in the implementation report; do not claim runtime verification.
|
||||
- Critical files for implementation: /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/catalog/provider/JavaCatalogProvider.java; /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/catalog/ScalarCatalogProvider.java; /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/question/QuestionCatalogServiceImpl.java; /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/practice/SessionResponseAssembler.java; /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/test/java/cn/iocoder/yudao/module/education/service/catalog/CatalogServiceImplTest.java.
|
||||
|
||||
### Reuse boundaries
|
||||
|
||||
- Reuse /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/service/catalog/CatalogProvider.java and existing provider selection; do not choose a new provider in this slice.
|
||||
- Reuse existing safe question DTO/assembler boundaries in QuestionCatalogServiceImpl; never return DOs, answers, explanations, correctness flags, or admin metadata.
|
||||
- Apply one shared, provider-neutral option validation contract at the provider-to-safe-question/session-snapshot boundary; do not duplicate divergent validation rules.
|
||||
- Reuse framework TenantContextHolder and the existing explicit CatalogScopeQuery predicate. Do not broaden TenantUtils.executeIgnore or add a custom tenant bypass.
|
||||
- Keep changes inside Education unless a proven public contract gap requires a minimal separately owned interface; do not alter System, Member, Scalar infrastructure, or database schema speculatively.
|
||||
- Preserve and classify the existing dirty tree; implementation must be serial and must not overwrite unrelated files.
|
||||
|
||||
### Database change
|
||||
|
||||
No database change for the bounded correctness slice. Do not modify V4010 or V4020. Do not promote untracked SQL during this slice. If later graph-integrity or core-loop schema work is approved, create new immutable module-owned PostgreSQL Flyway migrations under /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/resources/db/migration/education/ after schema review; never claim execution without a real PostgreSQL run.
|
||||
|
||||
### Test plan
|
||||
|
||||
- Focused unit/provider contract tests for null, absent, empty, malformed, structurally invalid, blank-label, duplicate/order-invalid options, and valid question-type-specific payloads.
|
||||
- Service tests proving malformed published content cannot produce a student-visible apparently valid safe question.
|
||||
- Session create/restore tests proving malformed persisted snapshots fail closed and valid snapshots retain safe fields only.
|
||||
- Tests for single browse, collection browse, unpublished/invisible content, unavailable provider, disabled feature, cross-tenant access, and tenant_id=0 PUBLIC scope.
|
||||
- If both providers cannot yet share a concrete contract, add contract tests parameterized over each implementation and record the remaining provider decision rather than silently selecting one.
|
||||
- No concurrency test is required for this read-only slice, but atomic submit-idempotency reservation and crash recovery must block the later submit slice.
|
||||
- After implementation authorization only: run focused Education tests, git diff --check, and mvn -pl yudao-server -am -DskipTests clean compile; if schema files remain unchanged, do not claim Flyway execution.
|
||||
|
||||
### Rollback
|
||||
|
||||
Application-level rollback is configuration/provider disablement or restoration of the prior provider behavior after review, without destructive Git or database rollback. No database rollback applies because this slice has no schema change. If malformed persisted snapshots are encountered, fail closed with a controlled unavailable/corrupt-content outcome rather than silently restoring an empty-options question.
|
||||
|
||||
### Authorization gate
|
||||
|
||||
This document selects and specifies the first slice; it does not authorize broad implementation. Before editing, re-read the dirty working tree, isolate existing user changes, state the exact files to touch, and execute the slice test-first.
|
||||
15
docs/education/migration/10-documentation-corrections.md
Normal file
15
docs/education/migration/10-documentation-corrections.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Documentation Corrections
|
||||
|
||||
> Phase 0 static assessment generated on 2026-07-29. No build, test, application startup, PostgreSQL connection, or Flyway migration was executed during this assessment.
|
||||
|
||||
These corrections are identified but not applied by the read-only discovery workflow.
|
||||
|
||||
- Correct /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/README.md:4-20,171-192,393-401 to separate committed versus dirty work, remove MySQL/rollback delivery claims, document PostgreSQL/Flyway forward-only operations, and state that V4010/V4020 and core-loop schema execution are unverified.
|
||||
- Correct /Users/tiku1/code/ruoyi-vue-pro/docs/education/student-core-learning-loop-prd.md:20-26,142-143,200-201 so it does not claim RuoYi/MySQL, ordered reversible SQL, or absent Flyway.
|
||||
- Correct /Users/tiku1/code/ruoyi-vue-pro/docs/education/pilot-acceptance-runbook.md:29-37,63-68,78-85 to require actual PostgreSQL/Flyway execution evidence and forward correction rather than MySQL rollback.
|
||||
- Align /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/controller/app/tenant/EducationTenantController.java:55-59 documentation, /Users/tiku1/code/ruoyi-vue-pro/yudao-module-education/src/main/java/cn/iocoder/yudao/module/education/config/EducationProperties.java:53-59, implementation, System website normalization, and tests on port policy.
|
||||
- Document the provider-neutral malformed-option contract across JavaCatalogProvider, ScalarCatalogProvider, QuestionCatalogServiceImpl, and SessionResponseAssembler, including question-type-specific absent-option policy.
|
||||
- Document that native catalog scope is a deliberate TenantUtils.executeIgnore/manual predicate boundary and add mapper-audit plus graph-integrity design notes.
|
||||
- Label /Users/tiku1/code/ruoyi-vue-pro/sql/mysql/education/ and /Users/tiku1/code/ruoyi-vue-pro/sql/postgresql/education/ according to actual operational status; do not present either as active delivery until the latter is promoted into Flyway.
|
||||
- Correct the commercialization legacy path to /Users/tiku1/code/tiku-backend/apps/api/src/nest/commerce-reconciliation.module.ts.
|
||||
- Create or maintain the ten required Phase 0 artifacts named by /Users/tiku1/code/ruoyi-vue-pro/docs/education/migration/GOAL.md:147-160, without claiming they exist unless verified.
|
||||
174
docs/education/migration/11-question-content-safety-contract.md
Normal file
174
docs/education/migration/11-question-content-safety-contract.md
Normal file
@@ -0,0 +1,174 @@
|
||||
# Provider-neutral question content safety contract
|
||||
|
||||
> Status: proposed for EDU-P0-S1
|
||||
>
|
||||
> Evidence basis: current Education providers and services plus the legacy question import and learning rules. This document defines the implementation contract; it does not report tests as executed.
|
||||
|
||||
## Decision
|
||||
|
||||
Student-visible question content is validated by one provider-neutral contract before it is projected as a safe question or persisted/restored as a practice snapshot. Provider-specific parsing may reject malformed transport data earlier, but switching between Scalar and Java must not change whether the same logical question is considered safe.
|
||||
|
||||
Invalid or unsupported content fails closed. It must not be normalized into an apparently valid question with an empty option list.
|
||||
|
||||
## Question-type families
|
||||
|
||||
Type matching is case-insensitive after trimming. Persisted and returned canonical values remain an implementation concern; validation uses the following families.
|
||||
|
||||
### Option-backed
|
||||
|
||||
```text
|
||||
choice
|
||||
multi
|
||||
multi_choice
|
||||
judge
|
||||
image
|
||||
```
|
||||
|
||||
An option-backed question requires:
|
||||
|
||||
- at least two options;
|
||||
- every option object to be non-null;
|
||||
- a non-blank string `label`;
|
||||
- a non-blank string `content`;
|
||||
- labels unique after trimming;
|
||||
- each `order`, when present, to be a finite number;
|
||||
- no duplicate non-null order value;
|
||||
- no answer-bearing field in the student-safe projection or snapshot.
|
||||
|
||||
Options are emitted in deterministic order: numeric `order` first, preserving source order only when order is absent. This slice does not infer or repair missing labels, contents, or order values.
|
||||
|
||||
### Optionless
|
||||
|
||||
```text
|
||||
fill
|
||||
text
|
||||
terms
|
||||
short_answer
|
||||
composition
|
||||
discuss
|
||||
translation
|
||||
case_analysis
|
||||
brief_analysis
|
||||
calculation
|
||||
analysis_design
|
||||
combination
|
||||
solution
|
||||
```
|
||||
|
||||
An optionless question may have null or empty options. If options are supplied, the content is inconsistent with its type and fails closed rather than silently discarding them.
|
||||
|
||||
This slice only establishes safe display and snapshot behavior. It does not add text-answer submission or scoring semantics. Existing answer-saving behavior must not pretend an optionless question is option-backed.
|
||||
|
||||
### Composite
|
||||
|
||||
```text
|
||||
reading
|
||||
```
|
||||
|
||||
A composite question requires sub-questions in the legacy model. The current target `CatalogQuestionDTO`, safe response, and practice snapshot do not carry a supported sub-question contract. Therefore a top-level `reading` question is unsupported by EDU-P0-S1 and fails closed rather than appearing as an optionless standalone question.
|
||||
|
||||
Supporting composite questions requires a later explicit model and API contract.
|
||||
|
||||
### Unknown or missing type
|
||||
|
||||
A null, blank, or unknown type fails closed. The target must not default unknown content to `choice`, because doing so can turn malformed content into a different assessment.
|
||||
|
||||
## Common option shape
|
||||
|
||||
The provider-neutral safe option shape is:
|
||||
|
||||
```text
|
||||
label: non-blank string, unique after trim
|
||||
content: non-blank string
|
||||
order: optional finite number, unique when present
|
||||
```
|
||||
|
||||
Provider DTOs may temporarily contain `isCorrect` for internal scoring or migration needs, but that field and all answer-bearing fields are discarded before creation of a Safe Question or the student-visible Question Snapshot JSON. A separately stored Protected Answer Key may retain correctness and explanation data for stable server-side scoring, but it is never part of the safe snapshot projection or a pre-submit response.
|
||||
|
||||
The safety validator must not require `isCorrect`, because safe restored snapshots intentionally do not store it. Correct-answer completeness is a content-authoring/scoring concern and is outside this read-only display contract.
|
||||
|
||||
## Failure semantics
|
||||
|
||||
### Fresh provider content
|
||||
|
||||
Any of the following makes the provider result unsafe:
|
||||
|
||||
- malformed options transport or JSON;
|
||||
- null option element;
|
||||
- wrong field types;
|
||||
- fewer than two options for an option-backed question;
|
||||
- options on an optionless question;
|
||||
- blank or duplicate labels;
|
||||
- blank content;
|
||||
- non-finite or duplicate explicit order;
|
||||
- unsupported composite content;
|
||||
- null, blank, or unknown type.
|
||||
|
||||
A single-question request returns the existing controlled unsafe/malformed content error. Page and collection requests fail the response closed rather than silently changing totals or returning a partial assessment set.
|
||||
|
||||
### Persisted practice snapshot
|
||||
|
||||
A null/empty options value is valid only for an optionless type. Malformed JSON or a shape that violates the type family makes the snapshot unavailable. Session restoration must return a controlled error for the session/question; it must not convert parse failure into `[]`.
|
||||
|
||||
No automatic repair is performed during read or restore. Historical repair, quarantine, or backfill requires a separately reviewed migration or administrative process.
|
||||
|
||||
## Boundary placement
|
||||
|
||||
The contract is applied at two domain boundaries:
|
||||
|
||||
1. provider `CatalogQuestionDTO` → student-safe projection or practice-session creation;
|
||||
2. persisted `PracticeQuestionDO` snapshot → practice-session response.
|
||||
|
||||
Both boundaries use the same type classification and option-shape rules. Scalar and Java adapters remain responsible only for transport/database parsing and mapping; they must not define divergent business validity.
|
||||
|
||||
## Compatibility notes
|
||||
|
||||
- Legacy source evidence identifies `choice`, `multi`, `judge`, and `image` as objective/option-backed and requires at least two options.
|
||||
- Legacy source recognizes `reading` as a composite type with sub-questions.
|
||||
- Legacy source recognizes the optionless types listed above and requires answer text for authoring; answer text is intentionally not exposed by the safe read contract.
|
||||
- Current target tests sometimes construct `choice` questions with null, one, or empty options. Those fixtures describe previous permissive behavior and must be corrected where they cross a student-visible or snapshot boundary.
|
||||
- `multi_choice` is retained as a target compatibility alias because current submit tests use it, while the legacy canonical type is `multi`.
|
||||
|
||||
## Required tests
|
||||
|
||||
### Shared contract
|
||||
|
||||
- each recognized type is classified correctly;
|
||||
- type matching trims and ignores case;
|
||||
- null, blank, and unknown types fail;
|
||||
- option-backed types reject null, empty, and one-option lists;
|
||||
- optionless types accept null/empty and reject supplied options;
|
||||
- `reading` fails as unsupported composite content;
|
||||
- null elements, wrong field types, blank labels, duplicate labels, blank contents, non-finite orders, and duplicate explicit orders fail;
|
||||
- valid options preserve safe fields and never expose `isCorrect`.
|
||||
|
||||
### Provider paths
|
||||
|
||||
Run the same logical contract cases against Scalar and Java mappings. Transport-specific malformed data may fail earlier, but no provider may turn malformed input into an empty valid list.
|
||||
|
||||
### Service paths
|
||||
|
||||
- single-question browsing fails closed for unsafe content;
|
||||
- page browsing fails the whole response for unsafe content;
|
||||
- collection browsing fails the whole response for unsafe content;
|
||||
- unpublished, hidden, inactive, disabled-source, and unavailable-source behavior remains fail-closed;
|
||||
- successful output contains no answer-bearing fields.
|
||||
|
||||
### Practice paths
|
||||
|
||||
- session creation rejects unsafe source questions before persisting snapshots;
|
||||
- a valid option-backed snapshot restores its options;
|
||||
- a valid optionless snapshot restores an empty option list;
|
||||
- malformed or type-inconsistent snapshots fail closed;
|
||||
- snapshot JSON contains only `label`, `content`, and `order`;
|
||||
- cross-tenant and ownership protections remain unchanged.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- choosing Scalar or Java as the authoritative provider;
|
||||
- adding composite/sub-question APIs;
|
||||
- adding subjective answer submission or scoring;
|
||||
- validating that correct answers exist or are unique;
|
||||
- repairing historical snapshots;
|
||||
- changing database schema or Flyway migrations;
|
||||
- submit-idempotency redesign.
|
||||
432
docs/education/migration/GOAL.md
Normal file
432
docs/education/migration/GOAL.md
Normal file
@@ -0,0 +1,432 @@
|
||||
# Education SaaS Migration Goal
|
||||
|
||||
> Status: active goal
|
||||
>
|
||||
> Source system: `/Users/tiku1/code/tiku-backend`
|
||||
>
|
||||
> Target system: `/Users/tiku1/code/ruoyi-vue-pro`
|
||||
>
|
||||
> Target branch at goal creation: `feature/education-core-loop`
|
||||
>
|
||||
> Created: 2026-07-29
|
||||
|
||||
## 1. Mission
|
||||
|
||||
Migrate the valuable business capabilities, data models, rules, state machines, authorization semantics, idempotency guarantees, and API contracts from `tiku-backend` into the RuoYi-Vue-Pro architecture.
|
||||
|
||||
This is a capability migration, not a file-by-file TypeScript-to-Java translation.
|
||||
|
||||
The resulting system must be a multi-tenant education SaaS backend that:
|
||||
|
||||
1. Places education-specific behavior in `yudao-module-education`.
|
||||
2. Reuses RuoYi-Vue-Pro platform modules before adding new infrastructure.
|
||||
3. Uses the framework's tenant, authentication, RBAC, logging, file, job, messaging, payment, and membership capabilities.
|
||||
4. Uses PostgreSQL and module-owned Flyway migrations for all forward database changes.
|
||||
5. Is independently buildable, testable, migratable, and progressively deployable by vertical slice.
|
||||
6. Does not require the old NestJS service after migration, except for explicitly documented temporary adapters with an exit plan.
|
||||
|
||||
## 2. Non-negotiable architecture rules
|
||||
|
||||
### 2.1 Reuse before building
|
||||
|
||||
| Legacy capability | Target capability to evaluate first |
|
||||
|---|---|
|
||||
| Login, token, refresh, logout, verification | Member/System authentication |
|
||||
| Student and administrator accounts | Member/System users; Education stores domain extensions only |
|
||||
| Tenant lookup, status, and isolation | System Tenant and framework tenant support |
|
||||
| Roles, menus, permissions, data permission | System RBAC |
|
||||
| Payment, refund, channel, callback | Pay |
|
||||
| Generic products and orders | Mall and Pay |
|
||||
| Membership, level, entitlement, points | Member first; Education only orchestrates domain rules |
|
||||
| Notifications, SMS, email | System/Infra messaging capabilities |
|
||||
| Uploads and object storage | Infra File |
|
||||
| Scheduled and background work | Infra Job or existing messaging facilities |
|
||||
| Audit and operation logs | System/Infra logging |
|
||||
| AI generation and recommendation | AI |
|
||||
| CRM leads and customer follow-up | CRM |
|
||||
| Questions, practice, exams, wrong questions, favorites, reports | Education |
|
||||
|
||||
Reuse means depending on public APIs, framework extension points, or events. Education must not depend on another module's internal `ServiceImpl`, Mapper, or DO and must not copy platform implementations.
|
||||
|
||||
A change outside Education is allowed only when the existing public capability cannot satisfy the need and the new interface is minimal, generic, backward-compatible, tested, and owned by the module that provides the capability.
|
||||
|
||||
### 2.2 Multi-tenancy and identity
|
||||
|
||||
- Tenant business DOs inherit `TenantBaseDO`.
|
||||
- MyBatis-Plus tenant injection remains the normal isolation mechanism.
|
||||
- Request bodies and query parameters are never trusted for `tenantId` or current `userId`.
|
||||
- The current tenant and user come from framework security context.
|
||||
- Student identity reuses Member; administrator identity reuses System.
|
||||
- Education stores education profiles and relationships, not passwords, tokens, or generic accounts.
|
||||
- Cross-tenant platform operations use existing tenant-ignore mechanisms with strict permissions; no custom bypass.
|
||||
- Unique constraints include `tenant_id` whenever uniqueness is tenant-scoped.
|
||||
|
||||
### 2.3 Security
|
||||
|
||||
- Controllers never return DOs directly.
|
||||
- Question responses strip answers, explanations, scoring rules, correctness flags, and administrative metadata before leaving the service boundary.
|
||||
- Invisible questions, unavailable tenants, disabled features, and unavailable catalog sources fail closed.
|
||||
- Logs do not contain tokens, passwords, verification codes, answers, or payment secrets.
|
||||
- Student App, Tenant Admin, Platform Admin, public, and internal APIs have explicit and separate authorization models.
|
||||
- Existing System RBAC and permission annotations are used for admin endpoints.
|
||||
|
||||
### 2.4 PostgreSQL and Flyway
|
||||
|
||||
All new or changed schema, indexes, constraints, required seed data, backfills, baselines, and Flyway configuration must use the project `flyway-postgresql` skill.
|
||||
|
||||
Required conventions include:
|
||||
|
||||
- `BIGINT GENERATED BY DEFAULT AS IDENTITY`
|
||||
- `TIMESTAMP` and `CURRENT_TIMESTAMP`
|
||||
- PostgreSQL `BOOLEAN`
|
||||
- `ON CONFLICT ... DO NOTHING`
|
||||
- `ON CONFLICT (...) DO UPDATE SET ... EXCLUDED.column`
|
||||
- `COALESCE`, `TO_CHAR`, and `EXTRACT` where applicable
|
||||
- module migration path: `<module>/src/main/resources/db/migration/<module>/`
|
||||
|
||||
Published migrations are immutable. Corrections use higher-version forward migrations. Historical `sql/mysql/education` files are not the delivery mechanism for new database changes. Application-layer tenant isolation must not be replaced by copied Supabase RLS.
|
||||
|
||||
Only an actual successful run against PostgreSQL may be reported as a successful database migration. Static SQL review, compilation, packaging, or resource copying must be described accurately as such.
|
||||
|
||||
## 3. Required Phase 0 investigation
|
||||
|
||||
Do not start broad feature implementation before completing this investigation.
|
||||
|
||||
### 3.1 Repository and rule inspection
|
||||
|
||||
Read and obey:
|
||||
|
||||
- target `CLAUDE.md`;
|
||||
- target `yudao-module-education/README.md`;
|
||||
- source `README.md`;
|
||||
- applicable `AGENTS.md`, module READMEs, database documentation, and `.claude/skills/index.yaml`;
|
||||
- actual runtime configuration and Git state.
|
||||
|
||||
Inspect both repositories' working trees and histories. Preserve all existing uncommitted work: no reset, destructive checkout, clean, or unrelated rewrite.
|
||||
|
||||
### 3.2 Historical commit review
|
||||
|
||||
Review these commits and determine whether their non-Education changes remain justified:
|
||||
|
||||
- `11e9cc6 feat(education): add module application shell`
|
||||
- `0f846fd feat(education): resolve student tenant context`
|
||||
|
||||
Review at least:
|
||||
|
||||
- root `pom.xml`;
|
||||
- `yudao-server/pom.xml`;
|
||||
- `ServiceErrorCodeRange`;
|
||||
- `TenantCommonApi`;
|
||||
- `TenantRespDTO`;
|
||||
- `TenantApiImpl`;
|
||||
- historical `sql/mysql/education` artifacts;
|
||||
- Education tenant-resolution logic.
|
||||
|
||||
Classify each design as retain, adjust, replace, remove by forward correction, or pending decision. Do not revert whole commits merely because one part is unsuitable.
|
||||
|
||||
### 3.3 Legacy capability inventory
|
||||
|
||||
Scan at least:
|
||||
|
||||
```text
|
||||
apps/api/src/features
|
||||
apps/api/src/nest
|
||||
apps/worker/src
|
||||
apps/asset-scanner/src
|
||||
packages
|
||||
supabase/migrations
|
||||
supabase/seed*
|
||||
docs
|
||||
```
|
||||
|
||||
Cluster capabilities rather than mechanically mapping every endpoint. Cover Auth, Tenant, Profile, Learning, Catalog, Scoreline, Video, AI, Tenant Content, Tenant Admin, Platform Admin, Referral, Commerce, Worker, Asset Scanner, tables, indexes, constraints, RLS, functions, triggers, and seeds.
|
||||
|
||||
### 3.4 Target capability inventory
|
||||
|
||||
Inspect Education's current implementation and reusable capabilities in System, Member, Pay, Mall, Infra, AI, CRM, framework starters, and Server integration. Account for both committed and uncommitted implementation; do not rebuild existing slices.
|
||||
|
||||
## 4. Required migration artifacts
|
||||
|
||||
Maintain these artifacts under `docs/education/migration/` or a reviewed scratch equivalent while discovery is incomplete:
|
||||
|
||||
1. `current-state.md` — verified implementation and working-tree state.
|
||||
2. `capability-matrix.md` — grouped legacy-to-target capability matrix.
|
||||
3. `api-mapping.md` — legacy method/path and authorization to target contract.
|
||||
4. `database-object-mapping.md` — table/RLS/function/trigger/storage disposition.
|
||||
5. `module-reuse-map.md` — reusable public APIs and identified gaps.
|
||||
6. `commit-review-11e9cc6.md`.
|
||||
7. `commit-review-0f846fd.md`.
|
||||
8. `decisions.md` — unresolved product or architecture decisions and ADR links.
|
||||
9. `slice-roadmap.md` — vertical slices with blocking edges.
|
||||
10. `first-slice.md` — first incomplete, bounded, low-risk delivery slice.
|
||||
|
||||
Each capability-matrix row must include:
|
||||
|
||||
```text
|
||||
legacy capability
|
||||
legacy code location
|
||||
legacy database objects
|
||||
business value
|
||||
target module
|
||||
existing capability to reuse
|
||||
Education gap
|
||||
whether another module must change
|
||||
priority
|
||||
risk
|
||||
verification method
|
||||
current status
|
||||
evidence
|
||||
open decision
|
||||
```
|
||||
|
||||
Allowed status values:
|
||||
|
||||
- replaced by RuoYi-Vue-Pro;
|
||||
- migrated;
|
||||
- partially migrated;
|
||||
- pending migration;
|
||||
- explicitly retired;
|
||||
- product decision required.
|
||||
|
||||
## 5. Delivery phases
|
||||
|
||||
### Phase 0 — inventory and architecture mapping
|
||||
|
||||
Complete the artifacts above, review the two historical commits, assess current uncommitted work, correct confirmed obsolete documentation, and select the first incomplete vertical slice.
|
||||
|
||||
### Phase 1 — tenant, identity, and permission baseline
|
||||
|
||||
Reuse System Tenant and Member/System Auth, unify Student/Tenant Admin/Platform Admin identity rules, verify cross-tenant protections, and decide whether the `TenantCommonApi` extension is a valid generic API.
|
||||
|
||||
### Phase 2 — student core learning loop
|
||||
|
||||
Verify and complete only genuine gaps in:
|
||||
|
||||
```text
|
||||
catalog browsing
|
||||
→ safe question browsing
|
||||
→ create practice
|
||||
→ save answer
|
||||
→ restore practice
|
||||
→ submit
|
||||
→ report
|
||||
→ wrong questions
|
||||
→ favorites
|
||||
```
|
||||
|
||||
The current branch may already implement much of this phase. Review before adding anything.
|
||||
|
||||
### Phase 3 — education content management
|
||||
|
||||
Question banks, questions, classifications, catalogs, publishing, imports/exports, resource associations, question videos, and content access control.
|
||||
|
||||
### Phase 4 — tenant education management
|
||||
|
||||
Classes, education student relationships, invitations, education roles, tenant education configuration, education points/badges, learning insight, and operations metrics. Generic users, roles, and tenants remain in Member/System.
|
||||
|
||||
### Phase 5 — commercialization
|
||||
|
||||
Products, orders, payments, refunds, subscriptions or entitlements, reconciliation, collection, commission, and referral relationships. Prefer composition of Mall, Pay, Member, and CRM. Education owns only education-domain bindings and orchestration.
|
||||
|
||||
### Phase 6 — asynchronous and operational capabilities
|
||||
|
||||
Imports/exports, content processing, billing work, notifications, resource scanning, audit, retries, and observability using Infra Job, messaging, File, and logging capabilities.
|
||||
|
||||
Each phase must be independently compilable, testable, deployable, and reversible at the application/configuration level.
|
||||
|
||||
## 6. Workflow operating model
|
||||
|
||||
This goal is executed as a decision-first, multi-session program:
|
||||
|
||||
```text
|
||||
Phase 0 read-only multi-agent discovery
|
||||
→ Wayfinder-style decision map
|
||||
→ domain modeling and module-boundary design
|
||||
→ migration specification
|
||||
→ blocker-aware vertical-slice tickets
|
||||
→ one fresh implementation context per ticket
|
||||
→ TDD and PostgreSQL/Flyway when applicable
|
||||
→ standards/spec review
|
||||
→ security review
|
||||
→ simplification
|
||||
→ focused and integration verification
|
||||
```
|
||||
|
||||
### 6.1 Multi-agent use
|
||||
|
||||
Use multi-agent workflows for broad read-only discovery, independent commit reviews, module capability mapping, adversarial verification, and completeness checks.
|
||||
|
||||
Do not allow multiple agents to edit the current dirty working tree concurrently. Implementation is serial by default. Isolated worktrees are permitted only for independent file sets with an explicit integration plan.
|
||||
|
||||
### 6.2 Ticket shape
|
||||
|
||||
Tickets are vertical behaviors, not technical layers. A ticket may include migration, DO, Mapper, Service, Controller, tests, and documentation needed to deliver one observable capability.
|
||||
|
||||
Good examples:
|
||||
|
||||
- a student can browse published catalog content in the current tenant;
|
||||
- a student can create and restore a practice session;
|
||||
- a student can idempotently save one answer;
|
||||
- a student can idempotently submit and read an immutable report;
|
||||
- a tenant administrator can publish a question.
|
||||
|
||||
Avoid tickets such as “create all DOs” or “create all Controllers.” Declare blocking edges explicitly and implement blockers first.
|
||||
|
||||
### 6.3 Skill selection
|
||||
|
||||
- `flyway-postgresql`: every database or Flyway change.
|
||||
- `mattpocock-skills:domain-modeling`: ambiguous or overloaded education language.
|
||||
- `mattpocock-skills:codebase-design`: module interfaces, provider/adapter seams, and public API boundaries.
|
||||
- `mattpocock-skills:research`: external primary-source research, not local repository inventory.
|
||||
- `mattpocock-skills:prototype`: throwaway executable exploration for a single unresolved design question.
|
||||
- `mattpocock-skills:tdd`: red-green implementation of a concrete behavior.
|
||||
- `mattpocock-skills:diagnosing-bugs`: hard defects after establishing a reliable failing command.
|
||||
- `mattpocock-skills:code-review`: standards and specification review from a fixed Git point.
|
||||
- `security-review`: tenant, identity, authorization, secret, answer, payment, and file boundaries.
|
||||
- `simplify`: reuse and structural cleanup after correctness review.
|
||||
- `run` and `webapp-testing`: real application and student-flow verification.
|
||||
|
||||
If a named planning skill is unavailable, preserve the same artifacts and gates using repository documents, issue files, and the workflow tool rather than skipping the phase.
|
||||
|
||||
## 7. Implementation rules
|
||||
|
||||
Follow the target layering:
|
||||
|
||||
```text
|
||||
controller
|
||||
service
|
||||
dal/dataobject
|
||||
dal/mysql
|
||||
convert
|
||||
enums
|
||||
api
|
||||
framework/integration
|
||||
```
|
||||
|
||||
- Controllers perform protocol adaptation and validation.
|
||||
- Services own transactions, state transitions, authorization-relevant domain checks, and idempotency semantics.
|
||||
- Mappers own data access only.
|
||||
- VO, DTO, and DO responsibilities remain distinct.
|
||||
- Use project `CommonResult`, paging, validation, conversion, exception, error-code, Redis, lock, transaction, and audit facilities.
|
||||
- External or legacy coexistence is hidden behind explicit Provider/Adapter boundaries.
|
||||
- Do not introduce NestJS runtime dependencies or reproduce NestJS Guard/Decorator architecture.
|
||||
|
||||
Idempotency and consistency requirements:
|
||||
|
||||
- database uniqueness is the final idempotency guard;
|
||||
- critical writes are transactional;
|
||||
- do not rely only on check-then-insert;
|
||||
- duplicate-request response semantics are explicit;
|
||||
- concurrency is tested;
|
||||
- external payment, notification, and file calls do not create long database transactions;
|
||||
- at-least-once consumers define duplicate handling.
|
||||
|
||||
## 8. Verification gates
|
||||
|
||||
Every implementation slice runs the minimum sufficient focused tests plus at least:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
Behavior changes require focused tests in Education and every affected module. Database changes additionally require PostgreSQL syntax validation, module packaging, and confirmation that migration files appear under `target/classes/db/migration/`.
|
||||
|
||||
Test applicable negative and concurrent scenarios:
|
||||
|
||||
- cross-tenant access;
|
||||
- unauthenticated access;
|
||||
- unauthorized access;
|
||||
- duplicate request;
|
||||
- concurrent request;
|
||||
- sensitive-field leakage;
|
||||
- catalog source failure;
|
||||
- disabled feature;
|
||||
- historical-data compatibility.
|
||||
|
||||
## 9. Per-slice reporting contract
|
||||
|
||||
Before implementation, report:
|
||||
|
||||
1. legacy capability and evidence;
|
||||
2. legacy files and database objects;
|
||||
3. target module;
|
||||
4. RuoYi-Vue-Pro capabilities reused;
|
||||
5. why another module will or will not change;
|
||||
6. database changes;
|
||||
7. tests;
|
||||
8. risks and rollback method.
|
||||
|
||||
After implementation, report:
|
||||
|
||||
1. changed files;
|
||||
2. reused modules;
|
||||
3. new Education domain capability;
|
||||
4. reasons for every non-Education change;
|
||||
5. replaced legacy code;
|
||||
6. unmigrated capabilities;
|
||||
7. commands actually run and results;
|
||||
8. whether PostgreSQL migration was actually executed;
|
||||
9. known risks and recommended next slice.
|
||||
|
||||
Do not state “complete” without verifiable files and command results.
|
||||
|
||||
## 10. Prohibitions
|
||||
|
||||
Do not:
|
||||
|
||||
- embed the old NestJS project;
|
||||
- mechanically translate all TypeScript files or all 342 APIs;
|
||||
- duplicate authentication, tenant, RBAC, payment, membership, notification, file, job, or audit platforms in Education;
|
||||
- trust client `userId` or `tenantId`;
|
||||
- expose answers or explanations;
|
||||
- introduce MySQL dialect or new MySQL delivery scripts;
|
||||
- bypass Flyway or modify published migrations;
|
||||
- depend on internal implementations of other modules;
|
||||
- weaken security for backward compatibility;
|
||||
- overwrite unrelated uncommitted work;
|
||||
- use destructive Git commands;
|
||||
- claim tests or migrations succeeded without running them;
|
||||
- begin a broad implementation before Phase 0 identifies the actual gaps.
|
||||
|
||||
## 11. Definition of done
|
||||
|
||||
The migration is complete only when:
|
||||
|
||||
1. every legacy capability has a reuse, migration, retirement, or decision status;
|
||||
2. Education-specific behavior resides in Education;
|
||||
3. platform capabilities are reused through appropriate boundaries;
|
||||
4. every non-Education modification has a necessity statement and tests;
|
||||
5. tenant isolation and sensitive-question-field controls are verified;
|
||||
6. database changes use PostgreSQL Flyway;
|
||||
7. core vertical flows have automated tests;
|
||||
8. required compile and diff checks pass;
|
||||
9. documentation matches the current PostgreSQL/Flyway architecture;
|
||||
10. existing user changes have not been overwritten;
|
||||
11. the target can run without the old service, or every temporary dependency has an owner and exit plan.
|
||||
|
||||
## 12. Immediate execution directive
|
||||
|
||||
Phase 0 inventory and the first safe-question slice have been executed. Continue through the blocker-aware tickets under [`docs/education/migration/issues/`](issues/README.md).
|
||||
|
||||
Current execution order:
|
||||
|
||||
1. `EDU-002` — restore the full Practice regression baseline;
|
||||
2. `EDU-003` — decide tenant resolution and student-principal policy;
|
||||
3. `EDU-004` — enforce the selected tenant/identity policy;
|
||||
4. `EDU-005` — decide PostgreSQL/Flyway takeover;
|
||||
5. `EDU-006` — deliver the approved Practice schema through module-owned Flyway;
|
||||
6. `EDU-007` through `EDU-009` — verify and complete the student core loop;
|
||||
7. later phases proceed only when their ticket blockers are complete.
|
||||
|
||||
Before every ticket:
|
||||
|
||||
1. read this Goal, the ticket, relevant decisions, and current Git status;
|
||||
2. preserve all existing uncommitted work;
|
||||
3. state the legacy capability, reuse boundary, database impact, tests, risk, and rollback;
|
||||
4. use a fresh implementation context and work serially in the dirty tree;
|
||||
5. use `flyway-postgresql` for any database or Flyway change;
|
||||
6. finish with focused tests, `git diff --check`, and `mvn -pl yudao-server -am -DskipTests clean compile`;
|
||||
7. report exact results and never claim PostgreSQL migration success without a real successful run.
|
||||
|
||||
Questions that can be answered from code, Git history, configuration, tests, or documentation must be investigated rather than asked. Ask only for genuine product decisions whose outcomes materially change implementation.
|
||||
37
docs/education/migration/issues/EDU-000-phase-0-inventory.md
Normal file
37
docs/education/migration/issues/EDU-000-phase-0-inventory.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# EDU-000 — Phase 0 inventory and architecture map
|
||||
|
||||
- **Status:** done
|
||||
- **Type:** discovery
|
||||
- **Phase:** 0
|
||||
- **Blockers:** none
|
||||
|
||||
## Outcome
|
||||
|
||||
A verified static map of the source system, target capabilities, historical commits, database objects, reusable modules, unresolved decisions, and vertical-slice roadmap exists under `docs/education/migration/`.
|
||||
|
||||
## Delivered artifacts
|
||||
|
||||
- `00-current-state.md`
|
||||
- `01-capability-matrix.md`
|
||||
- `02-api-mapping.md`
|
||||
- `03-database-object-mapping.md`
|
||||
- `04-module-reuse-map.md`
|
||||
- `05-commit-review-11e9cc6.md`
|
||||
- `06-commit-review-0f846fd.md`
|
||||
- `07-decisions.md`
|
||||
- `08-slice-roadmap.md`
|
||||
- `09-first-slice.md`
|
||||
- `10-documentation-corrections.md`
|
||||
|
||||
## Evidence and caveats
|
||||
|
||||
- Investigation was read-only and multi-agent.
|
||||
- No PostgreSQL migration was executed during discovery.
|
||||
- The source baseline is provisionally `main` at `033701a`; no source `feature/education-core-loop` ref was found.
|
||||
- The target worktree is dirty and must remain protected.
|
||||
- Completing this ticket did not resolve the product and architecture decisions recorded in `07-decisions.md`.
|
||||
|
||||
## Verification
|
||||
|
||||
- Artifacts generated and inspected.
|
||||
- `git diff --check -- docs/education/migration` passed at delivery time.
|
||||
@@ -0,0 +1,55 @@
|
||||
# EDU-001 — Provider-neutral safe question content
|
||||
|
||||
- **Status:** done with recorded follow-up coverage
|
||||
- **Type:** implementation
|
||||
- **Phase:** 0 / core-loop prerequisite
|
||||
- **Blockers:** EDU-000
|
||||
|
||||
## Student outcome
|
||||
|
||||
A student cannot receive or restore an apparently valid question when its type, visibility, or options are malformed. Student-visible question content and practice snapshot JSON do not expose answer-bearing fields.
|
||||
|
||||
## Scope delivered
|
||||
|
||||
- Shared question-type and option-shape contract.
|
||||
- Option-backed, optionless, unsupported composite, and unknown type handling.
|
||||
- Fail-closed single/page/collection safe projection.
|
||||
- Fail-closed practice creation for disabled/unavailable provider, invisible question, and unsafe options.
|
||||
- Strict practice snapshot restoration.
|
||||
- Answer-free option snapshot JSON.
|
||||
|
||||
## Relevant files
|
||||
|
||||
- `docs/education/migration/11-question-content-safety-contract.md`
|
||||
- `yudao-module-education/CONTEXT.md`
|
||||
- `service/question/QuestionContentSafety.java`
|
||||
- `service/question/QuestionCatalogServiceImpl.java`
|
||||
- `service/practice/PracticeSessionServiceImpl.java`
|
||||
- `service/practice/SessionResponseAssembler.java`
|
||||
- corresponding focused tests
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Invalid option-backed content fails closed.
|
||||
- [x] Valid optionless content may have no options.
|
||||
- [x] `reading` and unknown types fail closed until modeled.
|
||||
- [x] Safe responses and option snapshot JSON exclude correctness and explanation fields.
|
||||
- [x] Malformed persisted snapshots do not become empty valid options.
|
||||
- [x] Disabled/unavailable providers and invisible questions cannot create sessions.
|
||||
- [x] Focused safety tests pass.
|
||||
- [x] Required compile and diff checks pass.
|
||||
|
||||
## Follow-up coverage
|
||||
|
||||
- Add a clean JavaCatalogProvider public-seam/PostgreSQL contract test when the native catalog test harness is established.
|
||||
- Add explicit cross-tenant and `tenant_id=0` PUBLIC graph tests in the native catalog/graph-integrity slice.
|
||||
- Do not test private provider parsing through reflection.
|
||||
|
||||
## Verification recorded
|
||||
|
||||
```text
|
||||
Focused tests: 112 run, 0 failures, 0 errors
|
||||
git diff --check: passed
|
||||
yudao-server clean compile: BUILD SUCCESS
|
||||
PostgreSQL migration: not applicable and not executed
|
||||
```
|
||||
@@ -0,0 +1,103 @@
|
||||
# EDU-002 — Restore the full Practice regression baseline
|
||||
|
||||
- **Status:** completed as test-context repair; PostgreSQL persistence coverage moved to EDU-016
|
||||
- **Type:** test-enablement vertical slice
|
||||
- **Phase:** 0 / Phase 2 prerequisite
|
||||
- **Blockers:** EDU-001
|
||||
|
||||
## Outcome
|
||||
|
||||
The complete Practice test set starts reliably and distinguishes test-context failures from real behavior regressions across create, answer, restore, submit, report, wrong-question, and favorite flows.
|
||||
|
||||
## Why this is next
|
||||
|
||||
The direct EDU-001 tests pass, but broader Practice tests currently fail during Spring test-context creation because test configurations that import `PracticeSessionServiceImpl` do not consistently provide its current `ScoringService` dependency. Some tests also use name-based `@Resource` injection against Mapper proxies, producing type mismatches. Continuing core-loop work without this feedback loop would hide regressions.
|
||||
|
||||
## Existing code and data
|
||||
|
||||
- No legacy capability is being newly migrated.
|
||||
- No database object changes are required.
|
||||
- Existing Education test SQL and Mapper test infrastructure are reused.
|
||||
|
||||
## Scope
|
||||
|
||||
1. Inventory every test that imports, instantiates, or indirectly creates `PracticeSessionServiceImpl`.
|
||||
2. For each test context, choose one explicit dependency strategy:
|
||||
- import the real `ScoringServiceImpl` when scoring behavior is under test; or
|
||||
- provide `@MockitoBean ScoringService` when the test is outside the scoring seam.
|
||||
3. Replace ambiguous name-based Mapper injection only where it currently prevents the target tests from starting.
|
||||
4. Run the complete focused Practice regression set.
|
||||
5. Classify remaining failures as:
|
||||
- test assembly defect;
|
||||
- existing product defect;
|
||||
- expected contract change from EDU-001;
|
||||
- unrelated dirty-worktree issue.
|
||||
6. Fix only test-assembly defects in this ticket. Create separate tickets for product defects.
|
||||
|
||||
## Reuse boundaries
|
||||
|
||||
- Reuse `BaseDbUnitTest`, existing Education test SQL, Spring `@Import`, and `@MockitoBean`.
|
||||
- Do not create a parallel test framework.
|
||||
- Do not modify System, Member, database schema, or production state machines.
|
||||
- Do not weaken assertions merely to make tests green.
|
||||
|
||||
## Target test set
|
||||
|
||||
```text
|
||||
PracticeSessionServiceImplTest
|
||||
PracticeAnswerServiceImplTest
|
||||
PracticeSubmitServiceImplTest
|
||||
PracticeSubmitProjectionIntegrationTest
|
||||
PracticeSessionControllerHttpTest
|
||||
PracticeAnswerControllerHttpTest
|
||||
PracticeSessionControllerSubmitHttpTest
|
||||
WrongQuestionServiceImplTest
|
||||
FavoriteServiceImplTest
|
||||
```
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Every target class starts its Spring/JUnit context.
|
||||
- [ ] No target class fails because `ScoringService` is missing.
|
||||
- [ ] No target class fails from avoidable Mapper bean-name/type injection ambiguity.
|
||||
- [ ] EDU-001 safe-content assertions remain green.
|
||||
- [ ] Any actual behavior failure is documented with reproducible command and assigned a separate ticket.
|
||||
- [ ] No production behavior or database schema is changed unless a failing regression proves it is necessary and the ticket is explicitly amended.
|
||||
|
||||
## Test command
|
||||
|
||||
```bash
|
||||
mvn -pl yudao-module-education \
|
||||
-Dtest='PracticeSessionServiceImplTest,PracticeAnswerServiceImplTest,PracticeSubmitServiceImplTest,PracticeSubmitProjectionIntegrationTest,PracticeSessionControllerHttpTest,PracticeAnswerControllerHttpTest,PracticeSessionControllerSubmitHttpTest,WrongQuestionServiceImplTest,FavoriteServiceImplTest' \
|
||||
-Dsurefire.failIfNoSpecifiedTests=false \
|
||||
test
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** Low production risk; medium risk of exposing pre-existing behavior defects.
|
||||
- **Rollback:** Revert only this ticket's test assembly changes. There is no database rollback.
|
||||
|
||||
## Completion result
|
||||
|
||||
Test-context assembly was repaired:
|
||||
|
||||
- `ScoringService` is now explicitly mocked in Practice contexts that are not testing scoring itself.
|
||||
- `PracticeQuestionMapper` fields use type-based injection where name-based `@Resource` resolved the wrong MyBatis proxy.
|
||||
- Controller tests and `PracticeSessionServiceImplTest` start and pass.
|
||||
|
||||
The expanded regression run then exposed a separate infrastructure limitation rather than a remaining Spring context defect: H2 cannot execute the production PostgreSQL `ON CONFLICT` statements, and the unified `education_idempotency` test table was missing. A temporary H2 table definition was added so table absence no longer masks the dialect issue, but PostgreSQL conflict semantics cannot be made truthful on H2. The required follow-up is [`EDU-016`](EDU-016-postgresql-persistence-tests.md).
|
||||
|
||||
## Verification result
|
||||
|
||||
- Controller Practice tests: 39 passed.
|
||||
- `PracticeSessionServiceImplTest`: 24 passed before PostgreSQL-dialect persistence paths were included.
|
||||
- Full targeted suite starts after dependency/injection repair, then fails on confirmed H2/PostgreSQL dialect mismatch and downstream assertions.
|
||||
- No production behavior was changed by EDU-002.
|
||||
@@ -0,0 +1,160 @@
|
||||
# EDU-003 — Decide tenant resolution and student-principal policy
|
||||
|
||||
- **Status:** done — corrected policy and EDU-004 test seams are implementation-ready
|
||||
- **Type:** decision
|
||||
- **Phase:** 1
|
||||
- **Blockers:** EDU-000
|
||||
|
||||
## Decision outcome
|
||||
|
||||
Public tenant resolution accepts caller-supplied locator claims and is not an authentication boundary. Browser `Origin`/`Referer` evidence improves browser-context consistency but is forgeable by non-browser clients. The accepted contract therefore documents tenant-existence disclosure, uses one redacted unavailable response for unknown/disabled/expired tenants, requires abuse controls, and reserves authenticated/signed locators for deployments that require spoof resistance. Authenticated Education context is Member-only. This ticket records policy and tests-to-write only; it changes no production behavior.
|
||||
|
||||
## Domain language
|
||||
|
||||
- A **Tenant Locator Claim** is an unauthenticated pre-login value used to request tenant selection: either a browser-context hostname claim or an explicit Public Tenant Handle. It is not proof of caller identity or tenant authorization.
|
||||
- **Browser-context evidence** is a normalized host derived from `Origin`, falling back to `Referer`. It can bind browser UX inputs consistently, but any HTTP client can forge it.
|
||||
- A **Public Tenant Handle** is the current System tenant's unique `name` used as an exact public lookup key because the target has no separate stable tenant-code capability. It is not called a Tenant Code. It is case-sensitive, must match `^[A-Za-z0-9._-]{2,64}$`, and administrators must treat it as immutable after publication. A future mutable display label must be a separate field.
|
||||
- A **Student Principal** is an authenticated identity whose `LoginUser.userType` is `UserTypeEnum.MEMBER`. A generic authenticated account is not necessarily a Student Principal.
|
||||
- **Public Tenant Resolution** maps a Tenant Locator Claim to minimal login-routing fields. It intentionally discloses existence when a claim succeeds; it does not disclose whether a failed tenant is unknown, disabled, or expired.
|
||||
|
||||
## Evidence reviewed
|
||||
|
||||
- Legacy `apps/api/src/features/tenant/locator.ts` parses and compares `Origin`, `Referer`, request hosts, and a tenant code, but does not authenticate header provenance.
|
||||
- Legacy `resolver.ts` compares the source `slug` with the explicit code, proving the source Tenant Code was distinct from its display name.
|
||||
- The target has no System-owned stable tenant-code field or API. `system_tenant.name` is unique and mutable through administration; it is the only current exact generic lookup key.
|
||||
- Current `EducationTenantController` accepts arbitrary public `hostname` or `tenantName`, preserves ports, returns status and Education-configured `loginMethods`, and exposes distinct unknown/disabled/expired errors.
|
||||
- `EducationProperties.hostnameTenantMap` documents lowercase host-only keys without ports, while current implementation and tests preserve ports.
|
||||
- `system_tenant.websites` is an exact string-list lookup and existing target tests demonstrate values containing a scheme. No normalization seam currently makes those values host-only.
|
||||
- `EducationContextController` derives IDs from framework contexts but reads only the user ID and therefore does not reject an authenticated ADMIN principal.
|
||||
- `TenantSecurityWebFilter` already fills a missing request tenant from the authenticated principal, rejects authenticated principal/request-tenant mismatch, requires a tenant for non-ignored URLs, and validates tenant availability.
|
||||
- `TenantCommonApi` exposes generic System-owned tenant lookup methods; `TenantApiImpl` implements them, but the interface currently hides missing adapters behind `UnsupportedOperationException` defaults and has no focused owning-module contract test.
|
||||
- No verified Member public interface advertises enabled login methods. `MemberConfigApi` currently exposes points configuration only.
|
||||
|
||||
## ADR: public tenant-resolution and student-principal policy
|
||||
|
||||
### Status
|
||||
|
||||
Accepted for EDU-004.
|
||||
|
||||
### Context and trade-off
|
||||
|
||||
The resolver is public and cannot authenticate `Origin`, `Referer`, or ordinary query/header values. Browser headers are useful for consistent browser routing, not identity. A successful lookup necessarily distinguishes an available tenant from a failed candidate when it returns routing fields. The contract can hide lifecycle state among failures, but cannot honestly promise general non-enumeration without an unguessable or signed locator.
|
||||
|
||||
The target also lacks the source system's distinct stable tenant code. Adding one would require a separately designed System-owned capability and likely data work. For the current slice, the existing unique System tenant `name` is explicitly exposed as a constrained Public Tenant Handle; it is no longer mislabeled as a Tenant Code.
|
||||
|
||||
### Decision
|
||||
|
||||
1. **Production browser-context binding, not trusted identity**
|
||||
- Derive browser-context evidence from a valid HTTP(S) `Origin`; if absent, use a valid HTTP(S) `Referer`.
|
||||
- A supplied `hostname` may only confirm that evidence. A mismatch is a public locator conflict.
|
||||
- `Origin` and `Referer` are untrusted caller claims. Proxy preservation and forwarding-header controls do not make them authentic and are not cited as spoofing protection.
|
||||
- A non-browser/headless caller can forge either header and probe hostnames. This accepted threat is handled through the public disclosure policy and abuse controls below.
|
||||
- A deployment requiring spoof resistance must replace this public mode with an authenticated/signed locator or a host value supplied through a separately designed trusted-proxy boundary. That stronger mode is not implemented by EDU-004.
|
||||
|
||||
2. **Explicit headless handle and legacy query compatibility**
|
||||
- A headless client may submit `tenantHandle`, defined above as the existing System tenant unique `name` under a constrained public contract.
|
||||
- The legacy public `tenantName` query is unsupported and must be rejected, not silently aliased. EDU-004 adds a compatibility test for its rejection/removal.
|
||||
- A browser domain claim and explicit `tenantHandle` may be supplied together only when both resolve to the same tenant; disagreement is a public locator conflict.
|
||||
|
||||
3. **Local-development activation seam**
|
||||
- The sole authority is `yudao.education.tenant-resolution.local-development-enabled`.
|
||||
- Its secure default is `false`; absence means production-safe behavior. Spring profile names and environment names do not implicitly enable it.
|
||||
- Only developer workstations and automated tests may set it to `true`; shared, staging, and production deployments must keep it `false`.
|
||||
- When enabled, a configured local request host (`localhost`, `*.localhost`, loopback IPv4, `0.0.0.0`, or `::1`) may resolve without a handle. If `tenantHandle` is also present, the explicit handle takes precedence.
|
||||
- EDU-004 tests code-less local host, local host plus handle, and rejection of local/request-host fallback when the flag is absent or false.
|
||||
|
||||
4. **Hostname identity and normalization**
|
||||
- Tenant hostname identity is host-only: trim whitespace, lowercase, remove one trailing dot, remove IPv6 brackets, and discard default or non-default ports.
|
||||
- Accept valid DNS hosts, IPv4, and IPv6; reject credentials, paths, comma-separated/multi-value input, malformed authorities, and unsupported schemes.
|
||||
- `localhost:48080` normalizes to `localhost`.
|
||||
- Canonical `system_tenant.websites` entries used for this resolver are host-only values in the same normalized form. Entries containing a scheme, path, credentials, comma-separated values, or a port are legacy/non-canonical configuration and are not matched by Public Tenant Resolution.
|
||||
- EDU-004 implements canonical exact lookup and focused tests; it does not silently normalize legacy stored candidates at read time. Tenant administrators must correct non-canonical website configuration before enabling domain resolution. If later inventory requires automated data correction, that becomes a separately scoped Flyway/data ticket using `flyway-postgresql`; EDU-004 must not claim such correction.
|
||||
|
||||
5. **Authenticated Education context**
|
||||
- `/education/context` obtains the full `LoginUser`, rejects missing authentication, and rejects `userType != UserTypeEnum.MEMBER`.
|
||||
- User and tenant IDs continue to come only from security and tenant contexts.
|
||||
- EDU-004 preserves and does not duplicate or bypass `TenantSecurityWebFilter` mismatch and availability checks.
|
||||
|
||||
6. **Login-method metadata ownership**
|
||||
- Login-method metadata belongs to Member authentication, not System tenant metadata and not Education.
|
||||
- EDU-004 removes `loginMethods` from Education resolution and deprecates Education configuration/documentation that presents it as authoritative.
|
||||
- If later routing proves it necessary, introduce only a minimal Member-owned public interface with focused Member tests; do not create tenant-specific auth configuration in Education.
|
||||
|
||||
7. **Exact external wire contract**
|
||||
- The target framework represents business failures as HTTP `200 OK` with a `CommonResult` envelope. EDU-004 keeps that convention; tests assert both transport status and envelope.
|
||||
- Malformed, missing, locally forbidden, or otherwise unsupported locator claim: HTTP `200`; `CommonResult.code = 1005001003`; `msg = "租户识别请求无效"`; `data = null`.
|
||||
- Domain/handle or browser-evidence/requested-host conflict: HTTP `200`; `CommonResult.code = 1005001008` (new stable Education business code); `msg = "租户识别信息冲突"`; `data = null`.
|
||||
- Unknown, disabled, or expired tenant: HTTP `200`; `CommonResult.code = 1005001004`; `msg = "当前租户不可用"`; `data = null`.
|
||||
- Messages contain no rejected host/handle, lifecycle status, System exception text, or lookup detail. Logs may record a reason category and correlation metadata but must not log secrets or echo unsanitized header values.
|
||||
- Unknown, disabled, and expired paths must have identical status, code, message, JSON field set, null-data shape, and no intentional timing distinction. System errors remain internal.
|
||||
- Success is HTTP `200`, `code = 0`, `msg = ""`, and data contains only `tenantId` and `displayName`. `displayName` currently comes from the System tenant `name`; because that same field is the current Public Tenant Handle, an exact handle lookup necessarily returns the submitted handle as `displayName`. A future non-echoing mutable label requires a separate System-owned public display field. The response contains no separate handle field, raw status, websites, expiry, package, private configuration, internal lifecycle detail, or `loginMethods`.
|
||||
|
||||
8. **Disclosure and abuse threat model**
|
||||
- The resolver is not generally non-enumerating: a valid Public Tenant Handle or domain claim yields success with tenant ID/display name, while an unavailable candidate yields the generic failure.
|
||||
- The accepted guarantee is only unknown/disabled/expired indistinguishability.
|
||||
- EDU-004 must attach the public resolver to the repository's existing public API rate-limiting/ingress mechanism where available, emit structured success/failure-category security metrics, and document alerting for sustained candidate probing. If no reusable limiter seam exists, EDU-004 records that operational blocker rather than inventing an Education-only limiter.
|
||||
|
||||
9. **System seam**
|
||||
- Retain `TenantCommonApi` as the generic System-owned seam; do not add Education-specific locator, branding, redaction, or login-method concepts.
|
||||
- Replace `UnsupportedOperationException` lookup defaults with required abstract methods and add focused `TenantApiImpl` contract tests.
|
||||
- `EducationTenantController` remains the public adapter applying claim consistency, canonical website policy, availability coarsening, exact errors, and redaction.
|
||||
|
||||
### Rejected alternatives
|
||||
|
||||
- Treating `Origin` or `Referer` as authenticated tenant identity.
|
||||
- Claiming forwarding-header ingress controls authenticate browser headers.
|
||||
- Claiming general non-enumeration while successful lookup returns identifying fields.
|
||||
- Silently aliasing System tenant `name` to the distinct Tenant Code domain term.
|
||||
- Continuing the legacy `tenantName` public query.
|
||||
- Silently normalizing scheme/path/port-bearing stored website values during lookup.
|
||||
- Port-sensitive tenant identity.
|
||||
- ADMIN accepted as Student Principal.
|
||||
- Education-owned login methods or an Education-specific System API.
|
||||
|
||||
### Consequences
|
||||
|
||||
- EDU-004 intentionally changes current query, response, error, local-mode, website, and port behavior.
|
||||
- Published Public Tenant Handles use the System tenant unique `name`; renaming one is a breaking login-routing change until a genuine stable System-owned code exists.
|
||||
- Non-canonical website entries require configuration correction before domain resolution is enabled; no database change is authorized here.
|
||||
- Public existence disclosure is accepted and must be monitored and throttled. Strong spoof resistance requires a future signed/authenticated locator design.
|
||||
|
||||
## EDU-004 exact test matrix
|
||||
|
||||
| Scenario | Exact expected behavior | Owning test seam |
|
||||
|---|---|---|
|
||||
| Valid production `Origin` | Resolve normalized domain claim; success HTTP 200/code 0 | Education controller HTTP test |
|
||||
| Missing `Origin`, valid `Referer` | Resolve normalized Referer host; success HTTP 200/code 0 | Education controller HTTP test |
|
||||
| Forged but syntactically valid browser header | Documented as accepted untrusted claim; no authenticity assertion | Education controller test name/documentation |
|
||||
| Malformed `Origin` | HTTP 200/code 1005001003/generic message/null data; no fallback | Education controller HTTP test |
|
||||
| Origin/requested-host mismatch | HTTP 200/code 1005001008/generic conflict/null data | Education controller HTTP test |
|
||||
| Arbitrary production hostname without browser evidence | HTTP 200/code 1005001003 | Education controller HTTP test |
|
||||
| Explicit `tenantHandle` | Exact case-sensitive constrained System-name lookup | Education controller HTTP test |
|
||||
| Legacy `tenantName` query | Rejected/unsupported; HTTP 200/code 1005001003 | Education controller compatibility HTTP test |
|
||||
| Unknown, disabled, expired | Identical HTTP 200/code 1005001004/message/JSON/null data | Education controller HTTP parameterized test |
|
||||
| Host case/trailing dot/IPv4/IPv6/ports | Canonical host-only identity; all ports discarded | Education normalization/HTTP tests |
|
||||
| Non-canonical stored website candidate | Not matched; generic unavailable response | System adapter fixture plus Education HTTP test |
|
||||
| Local flag absent/false | Local/request-host fallback rejected with code 1005001003 | Education controller HTTP test |
|
||||
| Local flag true, code-less local host | Configured local host may resolve | Education controller HTTP test |
|
||||
| Local flag true, local host plus handle | Explicit handle takes precedence | Education controller HTTP test |
|
||||
| Domain/handle agreement | Resolve one tenant | Education controller HTTP test |
|
||||
| Domain/handle conflict | HTTP 200/code 1005001008 | Education controller HTTP test |
|
||||
| Anonymous `/education/context` | Existing unauthorized contract | Education context HTTP test |
|
||||
| Missing tenant or authenticated mismatch | Existing filter behavior remains active | Framework `TenantSecurityWebFilter` tests |
|
||||
| ADMIN/MEMBER principal | ADMIN rejected; MEMBER accepted with context-derived IDs | Education context HTTP tests |
|
||||
| Public field redaction | Success has only tenantId/displayName; failure has code/msg/data only | Education controller HTTP test |
|
||||
| `TenantCommonApi` adapters | Required methods delegate/map; no unsupported defaults | System `TenantApiImpl` contract test |
|
||||
| Abuse controls | Reused limiter/ingress attachment and structured category metric proven, or blocker recorded | Configuration/integration test where seam exists |
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Browser headers are described as forgeable consistency evidence, not trusted identity.
|
||||
- [x] Public existence disclosure and the narrower lifecycle-indistinguishability guarantee are explicit.
|
||||
- [x] Public Tenant Handle is distinguished from the source Tenant Code and has exact mutability/case/format semantics.
|
||||
- [x] Local behavior has one named, secure-default configuration seam and unambiguous precedence.
|
||||
- [x] Canonical stored website compatibility policy is selected without claiming data migration.
|
||||
- [x] Every error category has exact HTTP status, stable `CommonResult` code, message, data shape, and redaction rules.
|
||||
- [x] EDU-004 has exact production/test seams and legacy `tenantName` compatibility coverage.
|
||||
|
||||
## Verification
|
||||
|
||||
Static design review only. Reviewed legacy `locator.ts`/`resolver.ts`, current Education controller/properties/error codes, `CommonResult` and global error handling, `TenantSecurityWebFilter`, `TenantCommonApi`/`TenantApiImpl`, System tenant name/website storage and tests, Member public interfaces, the completed EDU-016 ticket, tracker, and dirty working tree. No production implementation, build, database connection, Flyway execution, or migration was performed by EDU-003.
|
||||
@@ -0,0 +1,139 @@
|
||||
# EDU-004 — Enforce tenant resolution and student identity boundaries
|
||||
|
||||
- **Status:** done — accepted tenant-locator and Member-principal policy implemented and verified; ingress/IP-only probing throttle remains an operational blocker
|
||||
- **Type:** implementation
|
||||
- **Phase:** 1
|
||||
- **Blockers:** EDU-003
|
||||
|
||||
## Selected policy from EDU-003
|
||||
|
||||
- `Origin` then `Referer` supplies forgeable browser-context evidence, not trusted identity. It binds browser UX inputs but does not prevent non-browser spoofing.
|
||||
- Headless clients use `tenantHandle`, the existing System tenant unique `name` under an exact constrained public contract; do not call it a Tenant Code.
|
||||
- Reject/remove the legacy public `tenantName` query as a separate compatibility behavior.
|
||||
- Production domain/handle agreement is checked; disagreement is a locator conflict.
|
||||
- Host identity removes case, whitespace, trailing dot, IPv6 brackets, and all ports.
|
||||
- Local fallback is controlled only by `yudao.education.tenant-resolution.local-development-enabled`, default `false`; profiles do not implicitly enable it.
|
||||
- Canonical System website values for this resolver are normalized host-only strings. Scheme/path/port-bearing stored candidates are not silently normalized and require configuration correction or a separate future Flyway/data ticket.
|
||||
- `/education/context` accepts only an authenticated `UserTypeEnum.MEMBER` Student Principal.
|
||||
- Unknown/disabled/expired failures are identical, but successful resolution still discloses tenant existence. Reuse rate limiting/ingress controls and emit abuse-monitoring metrics.
|
||||
- Login-method metadata is Member-owned; remove/deprecate Education `loginMethods` unless a minimal Member public interface is first proven necessary.
|
||||
- Retain generic `TenantCommonApi`, make its lookup methods required, and add System-owned `TenantApiImpl` contract tests.
|
||||
|
||||
See [`EDU-003-tenant-resolution-decision.md`](EDU-003-tenant-resolution-decision.md) for rationale and exact threat model.
|
||||
|
||||
## Implementation result
|
||||
|
||||
Implemented the accepted public HTTP contracts for tenant resolution and Member-only Education context. The resolver treats `Origin`, `Referer`, `hostname`, and `tenantHandle` only as forgeable locator claims; successful responses expose only `tenantId` and `displayName`, and unknown/disabled/expired tenants share the exact unavailable envelope. Local fallback is controlled exclusively by the secure-default property, including browser-derived loopback hosts, and only configured local hosts use the Education mapping. Production domains always use the canonical System website lookup. `TenantCommonApi` lookup methods are now required and System-owned adapter tests prove exact delegation and DTO mapping. Existing `TenantSecurityWebFilter` production behavior was unchanged and is covered by focused filter-boundary regression tests.
|
||||
|
||||
No adequate reusable candidate-probing rate-limit attachment was found. The existing `ClientIpRateLimiterKeyResolver` includes attacker-controlled method arguments in its key, so attaching it would create per-candidate limits rather than an IP-only probing limit. No Education-only limiter was introduced; ingress/IP-only throttling and alerting remain an operational blocker. The Education module also has no direct generic Micrometer dependency seam, so structured resolver metrics remain part of the same operational blocker rather than adding an Education-only dependency or abstraction.
|
||||
|
||||
System currently has no separate public tenant display field: its unique `name` is both the Public Tenant Handle and the only public label available through `TenantCommonApi`. Therefore handle-based success returns that same value as `displayName`; tests now model this real exact-name adapter behavior. Suppressing that value requires a future generic System-owned display-field capability, not an Education workaround.
|
||||
|
||||
No database or Flyway change was made or executed.
|
||||
|
||||
## Student outcome
|
||||
|
||||
A student receives minimal login-routing data for an available tenant, while authenticated Education endpoints reject wrong tenants and non-Member principals. The public resolver does not claim that caller-supplied locator headers authenticate tenant identity.
|
||||
|
||||
## Scope
|
||||
|
||||
- browser-context domain claim selection from `Origin`, then `Referer`;
|
||||
- requested-host confirmation and domain/handle conflict handling;
|
||||
- explicit `tenantHandle` exact lookup and legacy `tenantName` rejection/removal;
|
||||
- host-only normalization and canonical stored-website behavior;
|
||||
- secure-default local-development configuration seam and precedence;
|
||||
- Member/student principal enforcement for `/education/context`;
|
||||
- exact public `CommonResult` contract and safe response fields;
|
||||
- minimal generic `TenantCommonApi` adjustment with System-owned tests;
|
||||
- reuse of public resolver rate limiting/ingress controls and structured abuse metrics where an existing seam is available.
|
||||
|
||||
## Exact external contract
|
||||
|
||||
All business outcomes use the framework convention of HTTP `200 OK` with `CommonResult`:
|
||||
|
||||
| Category | HTTP | `CommonResult.code` | `msg` | `data` |
|
||||
|---|---:|---:|---|---|
|
||||
| Malformed/missing/untrusted/locally forbidden locator | 200 | `1005001003` | `租户识别请求无效` | `null` |
|
||||
| Requested-host/domain/handle conflict | 200 | `1005001008` | `租户识别信息冲突` | `null` |
|
||||
| Unknown, disabled, or expired tenant | 200 | `1005001004` | `当前租户不可用` | `null` |
|
||||
| Success | 200 | `0` | empty string | object containing only `tenantId`, `displayName`; current `displayName` is System tenant `name` and therefore equals a successful handle claim |
|
||||
|
||||
Failure messages and JSON shape never contain the rejected host/handle, lifecycle state, System exception detail, or lookup reason. Unknown, disabled, and expired paths must be byte-shape equivalent after normal serialization and have no intentional timing distinction.
|
||||
|
||||
## Reuse boundaries
|
||||
|
||||
- Reuse `TenantSecurityWebFilter`, `TenantContextHolder`, System Tenant public APIs, Member/System security context, `UserTypeEnum`, and an existing public rate-limit/ingress seam if present.
|
||||
- Do not duplicate tenant tables, token logic, login methods, RBAC, or a generic rate-limiter in Education.
|
||||
- Education must not depend on System internal Services, Mappers, or DOs.
|
||||
- A non-Education change must be generic, minimal, backward-compatible, and tested in its owning module.
|
||||
- If no reusable abuse-control seam exists, record the operational blocker; do not invent an Education-only infrastructure abstraction.
|
||||
|
||||
## Required TDD tests
|
||||
|
||||
### Education tenant controller HTTP tests
|
||||
|
||||
- valid production `Origin`; valid `Referer` fallback;
|
||||
- syntactically valid forged header is treated only as an untrusted claim, with no authenticity assertion;
|
||||
- malformed Origin and no attacker-selected fallback: exact HTTP/code/msg/data;
|
||||
- Origin/requested-host mismatch: exact conflict contract;
|
||||
- arbitrary production hostname without browser evidence: exact invalid contract;
|
||||
- explicit case-sensitive `tenantHandle` with `^[A-Za-z0-9._-]{2,64}$` validation;
|
||||
- legacy `tenantName` query rejected/removed independently;
|
||||
- domain/handle agreement and conflict;
|
||||
- unknown/disabled/expired exact identical wire shape;
|
||||
- case, trailing dot, DNS, IPv4, bracketed IPv6, default and non-default port normalization;
|
||||
- local flag absent/false rejects local/request-host fallback;
|
||||
- local flag true permits code-less configured local host;
|
||||
- local flag true plus handle gives the handle precedence;
|
||||
- non-canonical stored website candidate does not match;
|
||||
- success exposes only `tenantId` and System tenant `name` as `displayName`; for handle lookup this necessarily equals the submitted handle until System owns a separate public display field; no separate handle field, status, websites, expiry, package, private config, or `loginMethods`.
|
||||
|
||||
### Education context HTTP tests
|
||||
|
||||
- unauthenticated context rejected;
|
||||
- ADMIN principal rejected;
|
||||
- MEMBER principal accepted and IDs derived only from security/tenant contexts.
|
||||
|
||||
### System contract tests
|
||||
|
||||
- `TenantCommonApi` lookup methods are required, not optional unsupported defaults;
|
||||
- `TenantApiImpl` exact name and canonical website lookups delegate and map DTOs;
|
||||
- non-canonical website candidates are not silently normalized by the Public Tenant Resolution path.
|
||||
|
||||
### Framework/configuration tests
|
||||
|
||||
- existing missing-tenant and authenticated tenant/header mismatch filter behavior remains active;
|
||||
- local-development flag defaults false and is not inferred from a Spring profile;
|
||||
- reusable limiter/ingress attachment and structured success/failure-category metric are verified where an existing seam is identified.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Client `tenantId` and `userId` are never authoritative.
|
||||
- [x] Browser headers are documented and implemented as forgeable context claims, not authentication.
|
||||
- [x] Public existence disclosure is accepted; only unknown/disabled/expired status is indistinguishable.
|
||||
- [x] `tenantHandle` is not mislabeled as Tenant Code; mutability, case, and format match EDU-003.
|
||||
- [x] Legacy `tenantName` is rejected/removed and covered by a compatibility test.
|
||||
- [x] Local fallback uses the named secure-default property and unambiguous precedence.
|
||||
- [x] Canonical website compatibility policy is implemented without silent legacy normalization.
|
||||
- [x] Exact HTTP/CommonResult code/message/data contracts are asserted.
|
||||
- [x] Authenticated Student context enforces Member principal type.
|
||||
- [x] Existing framework mismatch checks remain active and are not bypassed.
|
||||
- [x] Public abuse-control gap is truthfully recorded; no inadequate or Education-only limiter was introduced.
|
||||
- [x] Every non-Education modification has a necessity explanation and focused owning-module tests.
|
||||
- [x] API documentation matches implementation and tests.
|
||||
|
||||
## Verification
|
||||
|
||||
Run focused Education, System, framework, and configuration tests as applicable, then:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
No database change is in scope. If investigation proves automated website data correction is required, stop that part, create a separate blocked data/Flyway ticket, and invoke `flyway-postgresql` before any schema/data work.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High security, disclosure, and login-routing impact.
|
||||
- **Rollback:** Application/configuration rollback to the previous resolver adapter; keep local mode disabled by default and do not weaken authenticated tenant checks. No destructive tenant-data operation.
|
||||
@@ -0,0 +1,160 @@
|
||||
# EDU-005 — Decide PostgreSQL/Flyway takeover strategy
|
||||
|
||||
- **Status:** done — forward-only takeover and EDU-006 version plan accepted
|
||||
- **Type:** decision
|
||||
- **Phase:** 1 / Phase 2 prerequisite
|
||||
- **Blockers:** EDU-002
|
||||
|
||||
## Decision outcome
|
||||
|
||||
Education schema ownership moves exclusively to module-owned PostgreSQL Flyway migrations under `yudao-module-education/src/main/resources/db/migration/education/`. The existing root `sql/postgresql/education/` files are classified as manual bootstrap/design history, not Flyway history. The MySQL files are obsolete archival artifacts and must not remain in operational instructions.
|
||||
|
||||
`V4010__initialize_education_flyway.sql` and `V4020__create_native_catalog.sql` are uncommitted working-tree resources in this checkout, and the inspected local disposable PostgreSQL database has no `flyway_schema_history` table and no Education tables. This proves neither migration ran in that database, but it does not prove they never ran in another environment. To avoid assigning a second meaning to a potentially distributed version, EDU-006 must preserve both files byte-for-byte and allocate new work from `V4030`.
|
||||
|
||||
No migration or production schema change was executed by EDU-005.
|
||||
|
||||
## Evidence and classification
|
||||
|
||||
| Artifact | Verified state | Classification | Forward disposition |
|
||||
|---|---|---|---|
|
||||
| `V4010__initialize_education_flyway.sql` | Untracked module resource; contains only `SELECT 1`; packaged in current `target/classes` | Potentially distributed Flyway history; execution unverified | Freeze byte-for-byte; do not repurpose |
|
||||
| `V4020__create_native_catalog.sql` | Untracked module resource; owns 11 native catalog tables; differs materially from manual `008` | Potentially distributed Flyway history; execution unverified | Freeze byte-for-byte; do not replace with manual `008` |
|
||||
| `sql/postgresql/education/002`–`005`, `007`, `009` | Untracked manual scripts implementing the current Practice/report/wrong/favorite/unified-idempotency model in stages | Manual bootstrap/design history, not active Flyway | Consolidate the approved final state into higher Flyway versions; do not copy the obsolete intermediate tables as fresh schema |
|
||||
| `sql/postgresql/education/008` | Manual native-catalog design predating/diverging from V4020 | Superseded manual design | V4020 remains the only intended Flyway owner of native catalog schema |
|
||||
| `sql/postgresql/education/000`–`001` | Placeholder schema plus menu/tenant seed scripts | Manual bootstrap/seed history | Do not create a separate `education` schema; evaluate the still-used `education:capability` menu seed separately |
|
||||
| `sql/mysql/education/**` | Historical MySQL schema, seeds, and rollback scripts | Obsolete archive | Remove from runbooks; retain only if explicitly labeled non-operational archive |
|
||||
| `src/test/resources/sql/postgresql/create_tables.sql` | EDU-016 disposable test bridge; 140 PostgreSQL persistence tests passed against it | Temporary test fixture | Replace with Flyway-driven test setup after EDU-006 proves equivalent schema |
|
||||
| Docker init mounts for manual Education SQL | Dirty Docker configuration mounts `000`–`009` directly | Obsolete delivery path | Remove Education manual mounts after Flyway takeover; the server owns migration execution |
|
||||
|
||||
## Approved schema owner map
|
||||
|
||||
### V4020 owner — unchanged
|
||||
|
||||
V4020 exclusively owns the native catalog tables:
|
||||
|
||||
- `education_region`, `education_school`, `education_major`, `education_subject`, `education_category`;
|
||||
- `education_content_entry`, `education_content_node`;
|
||||
- `education_question_collection`, `education_question`, `education_practice_blueprint`;
|
||||
- `education_question_collection_question`.
|
||||
|
||||
EDU-006 does not fold Practice schema into V4020 and does not silently substitute manual `008`.
|
||||
|
||||
### EDU-006 new owner — Practice final state
|
||||
|
||||
The new Practice migration owns the final runtime shape of:
|
||||
|
||||
- `education_practice_session` and `education_practice_question`;
|
||||
- `education_practice_report` and `education_practice_report_detail`;
|
||||
- `education_wrong_question` and `education_wrong_question_idempotency`;
|
||||
- `education_favorite`;
|
||||
- `education_idempotency`.
|
||||
|
||||
The approved fresh schema does **not** create `education_answer_idempotency` or `education_submit_idempotency`. Current production services use `IdempotencyStoreMapper` and `education_idempotency`; the old DOs/Mappers are unused compatibility residue and must be removed or explicitly isolated during EDU-006.
|
||||
|
||||
The migration must include all columns already required by runtime code and the proven EDU-016 bridge, including `client_sequence`, `last_client_sequence`, `review_fingerprint`, protected answer snapshots, report content snapshots, JSONB fields, tenant IDs, logical-delete fields, and observed conflict/query indexes.
|
||||
|
||||
## Version plan for EDU-006
|
||||
|
||||
Version numbers are project-wide. With V4020 frozen, the next allocated version is:
|
||||
|
||||
1. **V4030 — Practice core-loop final schema and adoption**
|
||||
- Create the final tables, columns, constraints, and indexes listed above.
|
||||
- Be adoption-aware for databases that contain manually bootstrapped Practice tables.
|
||||
- Validate existing column types and required uniqueness before treating existing objects as compatible; fail closed on incompatible shapes rather than silently accepting them.
|
||||
- Backfill the unified idempotency table from legacy answer/submit tables when those tables exist.
|
||||
- Preserve old idempotency tables during the initial adoption migration; do not make data destruction a prerequisite for application rollout.
|
||||
2. **V4040 — deterministic Education capability seed, only if still approved**
|
||||
- Seed menu IDs `6800`/`6801` idempotently if the existing `EducationCapabilityController` remains an exposed administrator capability.
|
||||
- Keep role assignment outside the migration.
|
||||
- If the capability endpoint/menu is retired before EDU-006, omit this migration rather than seeding dead UI.
|
||||
3. **Later forward cleanup migration**
|
||||
- Drop legacy `education_answer_idempotency` and `education_submit_idempotency` only after every adopted environment has verified backfill counts, the application no longer contains active references, and a separately reviewed forward cleanup is approved.
|
||||
|
||||
If repository-wide migration inventory changes before implementation, EDU-006 must re-run the version scan and use the next unused project-wide version instead of blindly taking V4030/V4040.
|
||||
|
||||
## Existing-environment takeover classes
|
||||
|
||||
`baseline-on-migrate=true` with baseline `4009` is an adoption aid, not proof that Education objects match Flyway.
|
||||
|
||||
1. **Empty or platform-only database, no Education tables**
|
||||
- Use baseline `4009` only when the non-empty platform schema requires adoption.
|
||||
- Run V4010, V4020, then V4030+ normally.
|
||||
2. **Manual Practice tables exist, native catalog tables do not**
|
||||
- Baseline `4009` may be used.
|
||||
- V4020 creates catalog objects; V4030 validates/adopts Practice objects and performs required backfills.
|
||||
3. **Manual catalog tables equivalent to V4020 already exist, no Flyway history**
|
||||
- Do not run V4020 into colliding tables.
|
||||
- First compare the actual schema with the frozen V4020 contract.
|
||||
- For a verified equivalent environment, use a one-time environment-specific baseline at `4020`, then run V4030+. This records adoption, not execution of V4020, and must be documented per environment.
|
||||
- If the schema is not equivalent, correct it through an explicit higher-version adoption path; do not falsify history or edit V4020.
|
||||
4. **Flyway history already contains V4010 and/or V4020**
|
||||
- Compare script/checksum/success with the frozen resources.
|
||||
- Never edit an executed script. Any mismatch or failed row blocks rollout until an environment-specific repair decision is reviewed.
|
||||
5. **Unknown shared environment**
|
||||
- No migration rollout is authorized until its Education tables and `flyway_schema_history` are inventoried.
|
||||
|
||||
After all existing environments carry an explicit baseline/history record, changing `baseline-on-migrate` to `false` is a separate reviewed configuration ticket. `validate-on-migrate=true`, `clean-disabled=true`, and `out-of-order=false` remain mandatory.
|
||||
|
||||
## Data compatibility and backfill rules
|
||||
|
||||
- Copy legacy answer and submit idempotency rows into `education_idempotency` with deterministic operation values and `ON CONFLICT ... DO NOTHING` only after verifying duplicate-key/request-hash compatibility.
|
||||
- Preserve original IDs only if required by references; otherwise allow identity allocation and verify semantic row counts by operation.
|
||||
- Existing Practice tables must be compared with the final DO/Mapper contract, not merely checked for table-name existence.
|
||||
- JSON snapshot fields use PostgreSQL `JSONB` where current runtime/test behavior expects JSONB normalization.
|
||||
- Tenant-scoped uniqueness includes `tenant_id` where the business key is tenant-local. `education_practice_report` uses `(tenant_id, session_id)` as the final unique report key.
|
||||
- Do not copy Supabase RLS. Framework tenant isolation remains primary; database constraints enforce integrity and idempotency.
|
||||
- No destructive rollback SQL is delivered. Recovery is application rollback plus a higher-version forward correction.
|
||||
|
||||
## Documentation and operational corrections
|
||||
|
||||
EDU-006 must update operational documentation in the same slice:
|
||||
|
||||
- replace `yudao-module-education/README.md` MySQL apply/rollback commands with Flyway/PostgreSQL forward-only instructions;
|
||||
- remove the manual Education SQL mounts from `script/docker/docker-compose.yml` so a fresh Docker database is not initialized outside Flyway before server startup;
|
||||
- label `sql/postgresql/education/` and `sql/mysql/education/` as non-operational history or move them to an explicitly archival location without rewriting history;
|
||||
- replace the EDU-016 temporary PostgreSQL schema bridge with Flyway-driven setup after equivalence is proven;
|
||||
- state per environment whether Flyway was actually run, validated, or only packaged/compiled.
|
||||
|
||||
## Required EDU-006 verification
|
||||
|
||||
Static and build gates:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-module-education -am -DskipTests clean package
|
||||
find yudao-module-education/target/classes/db/migration/education -type f -print
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
Real disposable PostgreSQL gate:
|
||||
|
||||
1. initialize a disposable platform database or approved baseline fixture;
|
||||
2. run Flyway migrate using the server's exact migration locations and PostgreSQL driver;
|
||||
3. run Flyway validate;
|
||||
4. inspect `flyway_schema_history` with version, script, checksum, and success;
|
||||
5. inspect all approved tables, columns, constraints, indexes, and backfill counts;
|
||||
6. run the EDU-016 PostgreSQL persistence suite against the migrated schema;
|
||||
7. test at least the empty/platform-only path and one representative manually bootstrapped adoption path.
|
||||
|
||||
Only these real successful executions may be reported as migration success.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] No published or potentially distributed migration is authorized for editing.
|
||||
- [x] Every required table/index/constraint/seed has one intended Flyway owner and version range.
|
||||
- [x] Manual SQL is not silently treated as executed history.
|
||||
- [x] The plan includes migration packaging and real PostgreSQL execution evidence requirements.
|
||||
- [x] Documentation correction scope is explicit.
|
||||
|
||||
## Verification performed by EDU-005
|
||||
|
||||
- Read project Flyway rules, local/dev Flyway configuration, server dependencies, all active migration locations, manual PostgreSQL/MySQL artifacts, core-loop DOs/Mappers, PostgreSQL test bridge, Docker initialization, Git history, and dirty-tree state.
|
||||
- Inspected the reachable disposable `postgresdb` container. Target identity was database `postgres`, user `postgres`, schema `public`; it contained no `flyway_schema_history` relation and no Education tables. Container startup logs state that `/docker-entrypoint-initdb.d/*` was ignored because the volume was already initialized.
|
||||
- Confirmed V4010/V4020 are currently packaged under `target/classes/db/migration/education/` from a prior build.
|
||||
- Did not modify migration SQL, application code, server configuration, Docker configuration, or any database object.
|
||||
- Did not run Flyway migrate/validate and does not claim a successful database migration.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High. Existing manually initialized databases may have partially overlapping or divergent table shapes, and a false baseline can hide incompatibility.
|
||||
- **Rollback:** No rollback is required for this decision-only ticket. EDU-006 uses forward migrations, preserves legacy idempotency tables during first adoption, and supports application rollback without `flyway clean` or destructive down scripts.
|
||||
@@ -0,0 +1,83 @@
|
||||
# EDU-006 — Deliver Practice schema through module-owned Flyway
|
||||
|
||||
- **Status:** done — V4030/V4040 delivered and verified; V4050 adds forward-only column documentation
|
||||
- **Type:** database implementation
|
||||
- **Phase:** 2 prerequisite
|
||||
- **Blockers:** EDU-005
|
||||
|
||||
## Implementation result
|
||||
|
||||
`V4030__create_and_adopt_practice_schema.sql` now owns the final Practice session/question, report/detail, wrong-question/idempotency, favorite, and unified idempotency schema. Fresh databases do not create legacy answer/submit idempotency tables. Compatible manually initialized Practice tables receive missing final columns and JSONB alignment; legacy answer/submit idempotency rows are backfilled into `education_idempotency` while the source tables remain untouched. A conflicting request hash fails the migration transactionally.
|
||||
|
||||
The EDU-016 test seam now runs the real Flyway chain in a random disposable PostgreSQL schema. Its temporary `create_tables.sql` bridge was removed. The established 140 persistence tests and five migration-contract scenarios pass together.
|
||||
|
||||
Manual Education SQL mounts were removed from Docker Compose, and the active Education README and Pilot runbook now describe PostgreSQL/Flyway forward-only delivery. V4010/V4020 remained byte-for-byte unchanged. V4040 adds the submit-claim token and lease timestamp required by EDU-009 crash recovery; it also normalizes adopted successful submit rows without changing V4030 release history.
|
||||
|
||||
No shared or production database was migrated. Successful migration evidence applies only to the isolated no-volume PostgreSQL container and random schemas used by the tests.
|
||||
|
||||
## Scope
|
||||
|
||||
Implement only the objects approved in EDU-005, potentially covering:
|
||||
|
||||
- practice sessions and question snapshots;
|
||||
- answer and submit idempotency;
|
||||
- reports and report details;
|
||||
- wrong questions and favorites;
|
||||
- tenant-scoped unique constraints;
|
||||
- indexes required by verified query paths;
|
||||
- necessary menu/permission seed data;
|
||||
- compatible backfills for existing development data.
|
||||
|
||||
Exact objects and versions are determined by EDU-005 and `flyway-postgresql`.
|
||||
|
||||
## Architecture rules
|
||||
|
||||
- Use PostgreSQL dialect only.
|
||||
- Tenant-scoped uniqueness includes `tenant_id` where required.
|
||||
- Database uniqueness is the final idempotency guard.
|
||||
- Use `ON CONFLICT` where approved by the design.
|
||||
- Do not copy Supabase auth/RLS as the application isolation model.
|
||||
- Do not add destructive rollback migrations.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] New migrations use versions allocated by `flyway-postgresql`.
|
||||
- [x] V4010/V4020 remain unchanged as potentially distributed history.
|
||||
- [x] Migrations are packaged under `target/classes/db/migration/education/`.
|
||||
- [x] Annotated SQL and Mapper behavior match PostgreSQL constraints.
|
||||
- [x] Focused repository/integration tests cover uniqueness and tenant scope.
|
||||
- [x] Real PostgreSQL Flyway migrate/validate succeeds in an isolated disposable test environment.
|
||||
- [x] Operational docs no longer instruct users to apply MySQL or manual Education SQL for these objects.
|
||||
|
||||
## Verification
|
||||
|
||||
At minimum:
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
mvn -pl yudao-module-education -am -DskipTests clean package
|
||||
find yudao-module-education/target/classes/db/migration/education -type f
|
||||
mvn -pl yudao-server -am -DskipTests clean compile
|
||||
```
|
||||
|
||||
Also run the PostgreSQL commands prescribed by `flyway-postgresql` when an authorized database is available.
|
||||
|
||||
## Verification performed
|
||||
|
||||
Against an isolated PostgreSQL container bound only to `127.0.0.1`, the focused Flyway suite exercised fresh migration, baseline-4009 adoption, compatible session/question plus legacy-idempotency adoption, conflict with existing unified history, and conflicting duplicate legacy keys. Together with the existing persistence suite: 145 tests passed, 0 failures, 0 errors, 0 skipped. Every test schema was dropped and the no-volume container was stopped.
|
||||
|
||||
Also completed:
|
||||
|
||||
```text
|
||||
mvn -pl yudao-module-education -am -DskipTests clean package — BUILD SUCCESS
|
||||
V4010, V4020, V4030, V4040 present under target/classes/db/migration/education/ at the recorded verification point; V4050 must be included in the next verification run
|
||||
mvn -pl yudao-server -am -DskipTests clean compile — BUILD SUCCESS
|
||||
git diff --check — passed
|
||||
```
|
||||
|
||||
V4010 and V4020 retained their pre-ticket SHA-256 values. V4050 was added later as a metadata-only forward migration to document protected snapshot and idempotency state columns. V4060 validates every adopted Practice unique index against its required uniqueness and ordered key columns, failing closed when a stale same-named index would weaken tenant or idempotency guarantees. The corrected Education package, PostgreSQL Flyway suite, persistence suite, and server compile are rerun after each forward migration. No shared or production PostgreSQL database was changed.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High data compatibility and deployment-order risk.
|
||||
- **Rollback:** Forward correction migration plus application rollback. Never use `clean` or destructive rollback in shared environments.
|
||||
@@ -0,0 +1,57 @@
|
||||
# EDU-007 — Verify tenant-scoped practice creation and restoration
|
||||
|
||||
- **Status:** done — bounded create/restore contract verified against V4030 PostgreSQL
|
||||
- **Type:** implementation/verification
|
||||
- **Phase:** 2
|
||||
- **Blockers:** EDU-004, EDU-006
|
||||
|
||||
## Implementation result
|
||||
|
||||
The existing create/restore aggregate was retained and re-verified rather than rebuilt. Practice endpoints now require a `UserTypeEnum.MEMBER` Student Principal and continue deriving user/tenant only from the authenticated principal. Concurrent creation now uses the existing PostgreSQL `ON CONFLICT DO NOTHING` mapper seam, avoiding a query inside an aborted duplicate-key transaction. Real PostgreSQL tests prove identical concurrent requests return one session and conflicting fingerprints produce one winner plus one idempotency mismatch.
|
||||
|
||||
Focused tests also prove provider failure leaves no partial state and restore uses the persisted Question Snapshot after source content changes. The service create/restore suite now runs on the V4030 Flyway-owned PostgreSQL schema.
|
||||
|
||||
PUBLIC catalog read predicates and provider-neutral safety remain unchanged. Cross-scope PUBLIC graph-integrity semantics remain an explicit later architecture decision; EDU-007 does not claim or invent those constraints. Legacy entitlement/quota, timed practice, rich blueprint/random/review modes, and discovery of multiple active sessions are outside this bounded ticket.
|
||||
|
||||
## Scope
|
||||
|
||||
- Verify or complete session creation idempotency.
|
||||
- Verify session ownership and tenant isolation.
|
||||
- Restore immutable safe question snapshots.
|
||||
- Preserve provider-neutral question safety from EDU-001.
|
||||
- Verify PUBLIC catalog reads continue using the existing explicit scope predicates; tenant-consistent PUBLIC graph constraints remain blocked on the graph decision.
|
||||
- Remove no existing core-loop behavior unless a regression proves it invalid.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Current user and tenant derive from a Member security principal at the controller boundary.
|
||||
- [x] Duplicate client session ID with identical fingerprint returns the existing session.
|
||||
- [x] Conflicting fingerprint, user, or tenant does not expose the existing session.
|
||||
- [x] Underfilled, invisible, malformed, disabled, and unavailable content fails closed.
|
||||
- [x] Restored content remains stable after source content changes.
|
||||
- [x] Cross-tenant and wrong-user access is denied.
|
||||
- [x] Provider-neutral question safety and existing PUBLIC read predicates are preserved; graph-integrity enforcement remains blocked on the recorded architecture decision.
|
||||
- [x] PostgreSQL uniqueness and transaction behavior are tested against the EDU-006 schema.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused create/restore service, Mapper, controller, and PostgreSQL tests; then required diff/compile gates.
|
||||
|
||||
## Verification performed
|
||||
|
||||
Against an isolated PostgreSQL database using the V4010/V4020/V4030 Flyway chain:
|
||||
|
||||
```text
|
||||
PracticeSessionControllerHttpTest: 15 passed
|
||||
PracticeSessionServiceImplTest: 25 passed
|
||||
PracticeSessionServicePostgreSqlIntegrationTest: 2 passed
|
||||
Total: 42 passed
|
||||
Failures/errors/skipped: 0
|
||||
```
|
||||
|
||||
The PostgreSQL concurrency tests use bounded latches and prove both identical and conflicting fingerprint races. No database migration was added or changed by EDU-007.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** Medium session-ownership and compatibility risk.
|
||||
- **Rollback:** Application rollback; retain forward-compatible schema.
|
||||
@@ -0,0 +1,53 @@
|
||||
# EDU-008 — Verify idempotent answer saving
|
||||
|
||||
- **Status:** done — answer idempotency and rollback contract verified on PostgreSQL
|
||||
- **Type:** implementation/verification
|
||||
- **Phase:** 2
|
||||
- **Blockers:** EDU-007
|
||||
|
||||
## Implementation result
|
||||
|
||||
The existing unified PostgreSQL idempotency claim remains the final guard. Matching keys replay only a complete, valid stored response; null, blank, malformed, or structurally incomplete replay data now fails closed without re-executing the answer mutation. Completion of a newly claimed response must update exactly one idempotency row before session/question state changes.
|
||||
|
||||
Answer saving remains limited to Option-backed Questions. Optionless/free-text behavior is explicitly rejected until a separate subjective-answer contract is designed. The answer HTTP seam now uses the EDU-007 Member principal and TenantContextHolder boundary and rejects ADMIN principals.
|
||||
|
||||
PostgreSQL tests prove same-key/same-payload replay, same-key/different-payload conflict including concurrent requests, different-key CAS serialization, stale version/sequence rejection, user/tenant/state/question ownership checks, full rollback of answer/session/claim state, refresh recovery, and no answer-key/explanation leakage. No migration was added or executed by EDU-008.
|
||||
|
||||
## Scope
|
||||
|
||||
- Same key and same canonical payload replays the original result.
|
||||
- Same key and different payload returns a conflict.
|
||||
- Database uniqueness is the final idempotency guard.
|
||||
- Session version and client sequence prevent stale updates.
|
||||
- Selected options are validated against the safe snapshot contract.
|
||||
- Optionless answer behavior remains blocked until explicitly designed; do not pretend it is option-backed.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Same-payload duplicate semantics are explicit and tested.
|
||||
- [x] Conflicting payload is rejected.
|
||||
- [x] Concurrent same-key and different-key behavior is tested on PostgreSQL.
|
||||
- [x] Stale session version and stale per-session command sequence are rejected.
|
||||
- [x] Wrong user, tenant, session state, or question membership is rejected.
|
||||
- [x] Responses and restored sessions contain no answer key or explanation.
|
||||
- [x] Failure does not partially update answer, sequence, session version, or the idempotency claim.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused answer service/controller/Mapper tests, PostgreSQL concurrency tests, EDU-001 regressions, and required diff/compile gates.
|
||||
|
||||
## Verification performed
|
||||
|
||||
```text
|
||||
PracticeAnswerControllerHttpTest: 16 passed
|
||||
PracticeAnswerServiceImplTest: 37 passed on PostgreSQL/V4030
|
||||
Total focused: 53 passed
|
||||
Failures/errors/skipped: 0
|
||||
```
|
||||
|
||||
The service suite includes concurrent same-key identical and conflicting payloads plus exact different-key winner/loser assertions. Incomplete replay rows fail closed, and rollback assertions cover session version, session sequence, question state, and claim removal.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** Medium-to-high concurrency and offline-retry risk.
|
||||
- **Rollback:** Application rollback with schema retained; forward migration for any constraint correction.
|
||||
@@ -0,0 +1,69 @@
|
||||
# EDU-009 — Atomic submit, immutable report, wrong questions, and favorites
|
||||
|
||||
- **Status:** done
|
||||
- **Type:** implementation
|
||||
- **Phase:** 2
|
||||
- **Blockers:** EDU-008 (done)
|
||||
|
||||
## Student outcome
|
||||
|
||||
A student can retry submission safely, receive exactly one immutable report, and see consistent wrong-question and favorite projections.
|
||||
|
||||
## Core defect to resolve
|
||||
|
||||
The current submit path has evidence of check-then-insert idempotency. This ticket must define and implement an atomic initial claim with crash recovery before treating submission as complete.
|
||||
|
||||
## Scope
|
||||
|
||||
- Atomic submit-key reservation using PostgreSQL uniqueness/`ON CONFLICT` or the approved project mechanism.
|
||||
- Explicit processing/completed/failed or equivalent recovery semantics.
|
||||
- Same-key replay and conflicting-payload behavior.
|
||||
- Single state transition from active session to submitted.
|
||||
- Immutable scoring/report snapshot.
|
||||
- Duplicate-safe wrong-question projection.
|
||||
- Favorite behavior remains independent and tenant/user scoped.
|
||||
- No external calls inside a long database transaction.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Concurrent same-key same-payload requests converge on one report.
|
||||
- [x] Same key with different payload is rejected.
|
||||
- [x] Different keys racing on one session produce at most one committed submit.
|
||||
- [x] A crash after claim has a documented retry/recovery result.
|
||||
- [x] Report content remains stable after question mutation.
|
||||
- [x] Wrong-question projection is idempotent.
|
||||
- [x] Report and history access enforce user and tenant ownership.
|
||||
- [x] Pre-submit responses never expose protected answer data; post-submit response follows the approved report contract.
|
||||
|
||||
## Recovery contract
|
||||
|
||||
- The submit key is serialized with a PostgreSQL transaction-level advisory lock, then reserved with
|
||||
`INSERT ... ON CONFLICT DO NOTHING` before session/report writes.
|
||||
- The claim uses `PROCESSING` with a unique token and lease timestamp; report, report detail,
|
||||
wrong-question projection, session CAS, and token-checked claim completion run in the same transaction.
|
||||
- A normal processing failure rolls the full transaction back, including a newly inserted claim. If a previously
|
||||
committed/manual `PROCESSING` claim exists (for example after legacy partial persistence), a retry can take over
|
||||
the matching claim after the 120-second lease expires. A mismatched payload can never take over the claim.
|
||||
- A completed claim stores `report_id` and the complete immutable response as `COMPLETED`; same-key retries
|
||||
replay only a structurally complete matching response. Malformed or incomplete committed rows fail closed.
|
||||
- A different key that loses the session race is completed against the immutable winner report, so retries of
|
||||
either accepted key remain stable.
|
||||
|
||||
No external provider call occurs in the submit transaction: scoring uses the persisted session question snapshot.
|
||||
V4040 adds the claim token/timestamp columns and normalizes migrated successful `SUBMIT_SESSION` rows from
|
||||
legacy `ACCEPTED` to `COMPLETED` without changing V4030 release history.
|
||||
|
||||
## Verification
|
||||
|
||||
PostgreSQL concurrency tests are mandatory, along with service/controller/projection tests and required diff/compile gates.
|
||||
|
||||
Focused PostgreSQL verification on 2026-07-30:
|
||||
|
||||
- `PracticeSubmitServiceImplTest`: 38 passed.
|
||||
- Submit/report controller, projection, wrong-question, and favorite suites: 129 passed total.
|
||||
- Failures, errors, skipped: 0.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High state-machine and data-consistency risk.
|
||||
- **Rollback:** Disable practice writes or roll back application version; repair through forward migration only.
|
||||
@@ -0,0 +1,33 @@
|
||||
# EDU-010 — Tenant content publication and graph integrity
|
||||
|
||||
- **Status:** blocked
|
||||
- **Type:** implementation program
|
||||
- **Phase:** 3
|
||||
- **Blockers:** EDU-004, EDU-009, provider-authority decision, PUBLIC graph-semantics decision
|
||||
|
||||
## Tenant-admin outcome
|
||||
|
||||
Authorized tenant administrators can author, classify, publish, archive, and retire education content without creating cross-tenant or invalid PUBLIC/tenant relationships, and student reads remain consistent with publication state.
|
||||
|
||||
## Scope
|
||||
|
||||
- Question banks, questions, versions, classifications, catalogs, collections, blueprints, and bindings.
|
||||
- Draft/published/archived lifecycle.
|
||||
- System RBAC/DataPermission enforcement.
|
||||
- Tenant-consistent graph constraints or equivalent transactional enforcement.
|
||||
- Provider consistency between authoring source and student reads.
|
||||
- Safe projections preserved from EDU-001.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Admin permission and data-scope matrix is explicit.
|
||||
- [ ] Cross-tenant graph relationships cannot be persisted.
|
||||
- [ ] PUBLIC and tenant-owned reference rules are enforced and tested.
|
||||
- [ ] Unpublished/archived content is never student-visible.
|
||||
- [ ] Publication is transactional and auditable.
|
||||
- [ ] Database changes use `flyway-postgresql` and forward migrations.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High content-integrity and authorization risk.
|
||||
- **Rollback:** Disable authoring/publishing and roll back application; preserve data and correct forward.
|
||||
@@ -0,0 +1,32 @@
|
||||
# EDU-011 — Content import, export, assets, and scanning
|
||||
|
||||
- **Status:** blocked
|
||||
- **Type:** implementation program
|
||||
- **Phase:** 3 / 6
|
||||
- **Blockers:** EDU-010, Infra File contract, scanner ownership decision, durable job claim decision
|
||||
|
||||
## Tenant-admin outcome
|
||||
|
||||
Administrators can import and export education content through durable, duplicate-safe jobs, with secure files, malware scanning, tenant propagation, audit, retries, and partial-failure reporting.
|
||||
|
||||
## Reuse
|
||||
|
||||
- Education owns import/export business state and content validation.
|
||||
- Infra owns File, Job/MQ, locks, logging, and audit primitives.
|
||||
- Scanner integration sits behind a clear adapter; Education does not implement generic storage or scheduling.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Preview and execute are distinct states.
|
||||
- [ ] Jobs use atomic claim/lease/heartbeat/recovery semantics.
|
||||
- [ ] At-least-once retries are duplicate-safe.
|
||||
- [ ] File type, size, object key, access, and retention are enforced.
|
||||
- [ ] Scanning fails closed.
|
||||
- [ ] Tenant context propagates into asynchronous handlers.
|
||||
- [ ] Exports redact answers and private fields according to authorization.
|
||||
- [ ] Partial failures and dead letters are visible and auditable.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High operational and file-security risk.
|
||||
- **Rollback:** Disable job handlers and preserve job/business state for forward recovery.
|
||||
@@ -0,0 +1,33 @@
|
||||
# EDU-012 — Classes and education relationships
|
||||
|
||||
- **Status:** blocked
|
||||
- **Type:** implementation program
|
||||
- **Phase:** 4
|
||||
- **Blockers:** EDU-004, education relationship model decision, Member relationship contract, System data-scope policy
|
||||
|
||||
## Tenant-admin outcome
|
||||
|
||||
Tenant administrators manage classes, student education relationships, invitations, and supervision within explicit tenant and row-level scopes while Member/System remain the owners of generic users and roles.
|
||||
|
||||
## Scope
|
||||
|
||||
- Education class entity and membership relationships.
|
||||
- Student/teacher/class domain roles without duplicating System RBAC.
|
||||
- Invitations and duplicate-safe acceptance.
|
||||
- Education profile extensions.
|
||||
- Supervision relationships and data scopes if retained.
|
||||
- Audit and operation logging.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Generic account, password, token, tenant, and role tables are not duplicated.
|
||||
- [ ] Student/teacher/class permission matrix is documented and tested.
|
||||
- [ ] Cross-class and cross-tenant access is denied.
|
||||
- [ ] Invitation acceptance is idempotent and auditable.
|
||||
- [ ] Platform-admin tenant-ignore operations are explicit and permission guarded.
|
||||
- [ ] Database changes use `flyway-postgresql`.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High authorization and relationship-integrity risk.
|
||||
- **Rollback:** Disable management endpoints and correct relationships through audited forward operations.
|
||||
33
docs/education/migration/issues/EDU-013-commercialization.md
Normal file
33
docs/education/migration/issues/EDU-013-commercialization.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# EDU-013 — Education commercialization binding
|
||||
|
||||
- **Status:** blocked
|
||||
- **Type:** decision and implementation program
|
||||
- **Phase:** 5
|
||||
- **Blockers:** product/entitlement model, Mall/Pay API assessment, Member entitlement decision, EDU-004
|
||||
|
||||
## Outcome
|
||||
|
||||
Education products and access rights are connected to Mall, Pay, Member, and CRM without creating a parallel product, order, payment, refund, membership, or financial ledger in Education.
|
||||
|
||||
## Education ownership
|
||||
|
||||
Education may own only domain bindings and fulfillment orchestration, such as:
|
||||
|
||||
- education product to course/exam/content binding;
|
||||
- entitlement scope and education-resource association;
|
||||
- duplicate-safe fulfillment event state where no platform facility exists.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Mall/Pay/Member/CRM public contracts are mapped before implementation.
|
||||
- [ ] Payment callbacks and refunds remain in Pay.
|
||||
- [ ] Generic products/orders remain in Mall where applicable.
|
||||
- [ ] Entitlement issuance, revocation, expiry, and refund effects are explicit and idempotent.
|
||||
- [ ] Paid/private practice remains inaccessible until entitlement checks are complete.
|
||||
- [ ] Reconciliation and commission/referral ownership is explicit.
|
||||
- [ ] Financial and authorization tests cover duplicate callbacks and cross-tenant access.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** Very high financial and access-control risk.
|
||||
- **Rollback:** Disable fulfillment handlers and paid access; preserve financial ledgers in their owning modules.
|
||||
37
docs/education/migration/issues/EDU-014-extended-learning.md
Normal file
37
docs/education/migration/issues/EDU-014-extended-learning.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# EDU-014 — Extended student and secondary learning waves
|
||||
|
||||
- **Status:** blocked
|
||||
- **Type:** decision map followed by implementation tickets
|
||||
- **Phase:** 5
|
||||
- **Blockers:** explicit product scope, EDU-004, entitlement model, AI/File/Member/System/Infra contract assessment
|
||||
|
||||
## Outcome
|
||||
|
||||
Every legacy Auth/Profile/extended Learning, scoreline, vocabulary, video, AI, notification, badge, feedback, and exam-date capability receives a traceable conclusion: replaced, migrated, retired, deferred, or product decision required.
|
||||
|
||||
## Required decomposition
|
||||
|
||||
Do not implement this as one large ticket. Create one child ticket per selected capability family after ownership is decided. At minimum assess:
|
||||
|
||||
- Auth compatibility and phone/OAuth binding;
|
||||
- profile and education profile extensions;
|
||||
- vocabulary learning/review;
|
||||
- scoreline and admissions content;
|
||||
- video entitlement and progress;
|
||||
- recommendation and AI generation;
|
||||
- notifications and reminders;
|
||||
- points, badges, check-ins, feedback, exam countdowns;
|
||||
- learning analytics, leaderboard, trends, and reports.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Each family has target owner, reusable public capability, data disposition, API conclusion, priority, and tests.
|
||||
- [ ] Member/System/Infra/AI capabilities are reused rather than copied.
|
||||
- [ ] Sensitive reports and exports are redacted.
|
||||
- [ ] Media and AI access follows entitlement and tenant rules.
|
||||
- [ ] Retired capabilities have compatibility and data-retention conclusions.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** Medium-to-high scope and entitlement risk.
|
||||
- **Rollback:** Per child ticket; this parent is a planning gate.
|
||||
@@ -0,0 +1,42 @@
|
||||
# EDU-015 — Operational independence and legacy exit
|
||||
|
||||
- **Status:** blocked
|
||||
- **Type:** integration and deployment program
|
||||
- **Phase:** 6
|
||||
- **Blockers:** EDU-011, EDU-013, EDU-014 child decisions, all temporary-adapter owners and exit plans
|
||||
|
||||
## Outcome
|
||||
|
||||
The target backend runs its selected education capabilities without depending on the old NestJS API, worker, Supabase auth/storage, or asset-scanner deployment, except for explicitly time-bounded adapters with owners and exit dates.
|
||||
|
||||
## Scope
|
||||
|
||||
- Replace selected Worker jobs with Infra Job/MQ and owning-domain handlers.
|
||||
- Complete retries, dead letters, audit, notifications, and observability.
|
||||
- Complete file/scanner deployment or approved alternative.
|
||||
- Remove or disable temporary Scalar/legacy adapters according to provider strategy.
|
||||
- Reconcile migrated data and operational runbooks.
|
||||
- Prove deployment, startup, Flyway, and core user flows.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Every temporary legacy dependency has an owner, telemetry, failure policy, and exit date.
|
||||
- [ ] At-least-once consumers are duplicate-safe.
|
||||
- [ ] Job retries/dead letters and scanner health are observable.
|
||||
- [ ] PostgreSQL migrations are actually executed and validated in an authorized environment.
|
||||
- [ ] Student and selected admin E2E flows pass against the target only.
|
||||
- [ ] Runbooks contain no active MySQL/manual-SQL or obsolete NestJS startup requirement.
|
||||
- [ ] Rollback and incident procedures are documented.
|
||||
|
||||
## Verification
|
||||
|
||||
- Application startup and health.
|
||||
- Flyway history and migration execution.
|
||||
- Worker/job deployment smoke tests.
|
||||
- Playwright student harness and selected admin flows.
|
||||
- Logs, metrics, traces, retry/dead-letter, and scanner health checks.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** High deployment and production reliability risk.
|
||||
- **Rollback:** Per capability using application/configuration rollback while preserving forward database history.
|
||||
@@ -0,0 +1,64 @@
|
||||
# EDU-016 — Move PostgreSQL-specific Education persistence tests off H2
|
||||
|
||||
- **Status:** done — focused PostgreSQL persistence suite passes against the reachable `postgresdb` seam
|
||||
- **Type:** test infrastructure / PostgreSQL integration
|
||||
- **Phase:** 0 / database prerequisite
|
||||
- **Blockers:** EDU-002, EDU-005 for final schema ownership
|
||||
|
||||
## Confirmed defect
|
||||
|
||||
Education unit tests use H2 with `MODE=MYSQL`, while production Mapper SQL intentionally uses PostgreSQL `ON CONFLICT`. H2 rejects the annotated SQL for favorites, wrong-question idempotency, unified answer/submit idempotency, and review-session conflict handling. Switching H2 to PostgreSQL mode does not solve this: H2 still rejects `ON CONFLICT` and also exposes Boolean/integer compatibility differences.
|
||||
|
||||
This prevents the full Practice/Wrong/Favorite regression suite from exercising production persistence semantics.
|
||||
|
||||
## Outcome
|
||||
|
||||
PostgreSQL-specific persistence behavior runs against real ephemeral PostgreSQL in the test suite, while fast database-independent tests may remain on H2 where their SQL is portable.
|
||||
|
||||
## Scope
|
||||
|
||||
- Select the repository-standard PostgreSQL integration-test mechanism, preferably Testcontainers or an existing project fixture.
|
||||
- Move tests that execute `ON CONFLICT`, PostgreSQL JSON/JSONB, identity, Boolean, or concurrency semantics onto PostgreSQL.
|
||||
- Keep controller and pure domain tests database-independent.
|
||||
- Align test schema with module-owned Flyway after EDU-005/EDU-006; avoid maintaining a divergent hand-written full schema long term.
|
||||
- Cover at least:
|
||||
- `IdempotencyStoreMapper.insertIgnore`;
|
||||
- wrong-question idempotency insert;
|
||||
- favorite upsert;
|
||||
- review-session insert-ignore;
|
||||
- concurrent answer and submit claims.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] No test relies on H2 to validate PostgreSQL `ON CONFLICT` semantics.
|
||||
- [x] PostgreSQL tests execute the same Mapper SQL as production.
|
||||
- [x] Test database is isolated and disposable.
|
||||
- [x] Schema setup uses Flyway or an explicitly temporary bridge with an exit ticket.
|
||||
- [x] Concurrency tests are stable and prove unique-constraint behavior.
|
||||
- [x] CI prerequisites and local commands are documented.
|
||||
|
||||
## Verification
|
||||
|
||||
Completed against the existing reachable `postgresdb` service with credentials supplied only through `EDU_TEST_POSTGRES_*` environment variables:
|
||||
|
||||
```bash
|
||||
mvn -pl yudao-module-education \
|
||||
-Dtest=PracticeSessionMapperTest,FavoriteServiceImplTest,PracticeAnswerServiceImplTest,PracticeSubmitServiceImplTest,PracticeSubmitProjectionIntegrationTest,WrongQuestionServiceImplTest test
|
||||
```
|
||||
|
||||
Result: 140 tests passed, 0 failures, 0 errors. The same 140-test suite also passed with JUnit class parallelism explicitly enabled, proving the shared schema resource lock prevents class-level collisions. The suite executes production Mapper SQL on PostgreSQL, including `ON CONFLICT` and JSONB behavior. A JUnit resource lock serializes PostgreSQL test classes that share one random JVM-scoped schema; each class closes its Spring context before the inherited lifecycle drops and recreates that schema, preventing cached contexts from reusing a dropped schema.
|
||||
|
||||
The temporary schema bridge was removed by EDU-006. PostgreSQL persistence tests now create their disposable random schema through the module-owned Flyway chain (`V4010`, `V4020`, `V4030`) and retain only `clean.sql` for per-test data isolation.
|
||||
|
||||
Local/CI prerequisites:
|
||||
|
||||
- a reachable disposable PostgreSQL database;
|
||||
- PostgreSQL JDBC connectivity from the Maven process;
|
||||
- non-blank `EDU_TEST_POSTGRES_HOST`, `EDU_TEST_POSTGRES_PORT`, `EDU_TEST_POSTGRES_DB`, `EDU_TEST_POSTGRES_USER`, and `EDU_TEST_POSTGRES_PASSWORD` values.
|
||||
|
||||
No Testcontainers or other external dependency was added. No PostgreSQL Flyway migration was executed or authorized by this ticket.
|
||||
|
||||
## Risk and rollback
|
||||
|
||||
- **Risk:** Medium CI/runtime cost; high value for persistence confidence.
|
||||
- **Rollback:** Keep prior fast tests temporarily, but do not restore false H2 coverage claims for PostgreSQL SQL.
|
||||
59
docs/education/migration/issues/README.md
Normal file
59
docs/education/migration/issues/README.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Education Migration Tickets
|
||||
|
||||
This directory turns [`GOAL.md`](../GOAL.md) into executable, blocker-aware vertical slices.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Work only tickets whose blockers are complete.
|
||||
2. Start each implementation ticket in a fresh context after reading `GOAL.md`, the ticket, relevant decisions, and current Git status.
|
||||
3. Preserve the dirty working tree. Implementation is serial unless an isolated worktree and integration plan are explicit.
|
||||
4. Apply TDD at the ticket's declared seams.
|
||||
5. Use `flyway-postgresql` for every schema, index, constraint, seed, baseline, backfill, or Flyway configuration change.
|
||||
6. Close with focused tests, `git diff --check`, and `mvn -pl yudao-server -am -DskipTests clean compile`.
|
||||
7. Report exact commands and results. Never report PostgreSQL migration success without an actual successful PostgreSQL run.
|
||||
|
||||
## Status vocabulary
|
||||
|
||||
- `done`: implemented and verified to the ticket's current acceptance criteria.
|
||||
- `in-progress`: currently being implemented.
|
||||
- `ready`: all blockers complete and no unresolved decision prevents work.
|
||||
- `blocked`: depends on another ticket or product decision.
|
||||
- `decision`: produces a recorded decision rather than production behavior.
|
||||
|
||||
## Ticket graph
|
||||
|
||||
```text
|
||||
EDU-000 Phase 0 artifacts done
|
||||
├── EDU-001 Safe question content done, follow-up coverage remains
|
||||
├── EDU-002 Practice regression baseline done
|
||||
│ ├── EDU-016 PostgreSQL persistence tests done; temporary bridge blocked on EDU-005/EDU-006
|
||||
│ └── EDU-006 Practice schema Flyway done
|
||||
│ ├── EDU-007 Create/restore practice done
|
||||
│ ├── EDU-008 Idempotent answer save done
|
||||
│ └── EDU-009 Atomic submit/report done
|
||||
├── EDU-003 Tenant resolution decision done
|
||||
│ └── EDU-004 Tenant/identity security done; ingress/IP-only probing throttle remains operational blocker
|
||||
└── EDU-005 PostgreSQL/Flyway takeover decision done
|
||||
|
||||
EDU-009 + provider/content decisions
|
||||
└── EDU-010 Tenant content publication blocked
|
||||
└── EDU-011 Import/export/assets/scanning blocked
|
||||
|
||||
EDU-004
|
||||
└── EDU-012 Classes and education relationships blocked
|
||||
|
||||
Commerce ownership decisions
|
||||
└── EDU-013 Education commercialization blocked
|
||||
|
||||
All owner/contract decisions
|
||||
└── EDU-014 Extended learning waves blocked
|
||||
└── EDU-015 Operational independence blocked
|
||||
```
|
||||
|
||||
## Recommended execution order
|
||||
|
||||
1. Select the next unblocked content-management decision/ticket after EDU-009.
|
||||
|
||||
## Phase 0 completion caveat
|
||||
|
||||
Phase 0 artifacts exist, but several architecture and product decisions remain open. `EDU-000` is considered complete as an inventory deliverable, not as resolution of every decision it discovered.
|
||||
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 相关表,并记录应用版本与 `flyway_schema_history`。
|
||||
2. 使用 Server 配置的 PostgreSQL Flyway 执行 migrate 和 validate,检查版本、脚本、checksum 与 success;不得手工应用 Education 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 PostgreSQL 表行数和历史查询均未减少。
|
||||
|
||||
### 练习写入熔断
|
||||
|
||||
设置 `practice-write-enabled=false` 后:
|
||||
|
||||
- 新建练习、保存答案和交卷必须被拒绝;
|
||||
- 当前会话恢复、指定会话读取、报告和报告历史仍应可读;
|
||||
- 不执行清理、归档或 rollback SQL。
|
||||
|
||||
### 应用回滚
|
||||
|
||||
1. 将应用回滚到上一已验证版本。
|
||||
2. 保留所有 Education 表和数据,不执行 `flyway clean`、手工删除或任何 `*-rollback.sql`。
|
||||
3. 若旧版本与新 schema 不兼容,保持功能关闭并通过更高版本 Flyway migration 前滚修复;不得通过删表恢复服务。
|
||||
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 租户列表属于部署配置,修改后需要按配置刷新机制重新加载或重启应用。
|
||||
225
docs/education/scalar-contract-from-source.md
Normal file
225
docs/education/scalar-contract-from-source.md
Normal file
@@ -0,0 +1,225 @@
|
||||
# Scalar (tiku-backend) 接口契约 —— 从源码提取
|
||||
|
||||
日期:2026-07-28
|
||||
来源:`/Users/tiku1/code/tiku-backend` 仓库 NestJS Controller、DTO 和装饰器
|
||||
状态:源码级契约冻结,真实 endpoint 验证需启动完整运行时(Supabase + API server)
|
||||
|
||||
## 运行时信息
|
||||
|
||||
- 框架:NestJS + Fastify
|
||||
- OpenAPI 路径:`/openapi.json`(仅非生产环境)
|
||||
- Scalar 文档:`/docs`(仅非生产环境)
|
||||
- 认证:Bearer Token(JWT)+ `x-tenant-id` header
|
||||
- 响应 envelope:`{ items/item, meta: { requestId } }`
|
||||
|
||||
## RuoYi Education 实际调用的路径
|
||||
|
||||
以下为 RuoYi `ScalarCatalogProvider` 使用的只读 GET 路径:
|
||||
|
||||
### 1. GET /api/catalog/regions
|
||||
|
||||
- **安全方案**: `x-tenant-id` header (`@ApiSecurity('tenant-id')`, `@TenantAccess()`)
|
||||
- **查询参数**: `regionId?` (UUID, 可选)
|
||||
- **响应**: `{ items: CatalogRegionResponseDto[], meta: { requestId } }`
|
||||
- **CatalogRegionResponseDto 字段**:
|
||||
- `id` (uuid, 必填)
|
||||
- `legacyId` (string, nullable)
|
||||
- `name` (string, 必填)
|
||||
- `code` (string, nullable)
|
||||
- `shortName` (string, nullable)
|
||||
- `fullName` (string, nullable)
|
||||
- `icon` (string, nullable)
|
||||
- `pinyin` (string, nullable)
|
||||
- `isHot` (boolean, 必填)
|
||||
- `isActive` (boolean, 必填)
|
||||
- `order` (number, 必填)
|
||||
|
||||
### 2. GET /api/catalog/region-modules
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**: `regionId?` (UUID)
|
||||
- **响应**: `{ items: CatalogRegionModuleResponseDto[], meta }`
|
||||
- **字段**: id, legacyId, regionId, name, type, icon, color, textColor, description, route, isPrimarySchoolModule, isActive, order
|
||||
|
||||
### 3. GET /api/catalog/module-nodes
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `regionId?` (UUID)
|
||||
- `moduleId?` (UUID)
|
||||
- `parentId?` (string, "root" 表示根节点)
|
||||
- **响应**: `{ items: CatalogEntityDto[], meta }` — 通用实体列表
|
||||
|
||||
### 4. GET /api/catalog/schools
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**: `regionId?`, `schoolId?`
|
||||
- **响应**: `{ items: CatalogSchoolResponseDto[], meta }`
|
||||
- **字段**: id, legacyId, regionId, moduleId, name, professionalExamDate, metadata, createdAt, updatedAt
|
||||
|
||||
### 5. GET /api/catalog/majors
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**: `regionId?`, `schoolId?`, `majorId?`, `moduleId?`, `type?`
|
||||
- **响应**: `{ items: CatalogMajorResponseDto[], meta }`
|
||||
|
||||
### 6. GET /api/catalog/subjects
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**: `regionId?`, `schoolId?`, `majorId?` (UUID), `moduleId?` (UUID), `type?` (string)
|
||||
- **响应**: `{ items: CatalogEntityDto[], meta }`
|
||||
|
||||
### 7. GET /api/catalog/categories
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**: `subjectId?` (UUID), `nodeId?` (UUID, 旧导航节点)
|
||||
- **响应**: `{ items: CatalogEntityDto[], meta }`
|
||||
|
||||
### 8. GET /api/catalog/questions
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `subjectId?` (UUID)
|
||||
- `categoryId?` (UUID)
|
||||
- `nodeId?` (UUID, 旧导航节点)
|
||||
- `entryId?` (UUID)
|
||||
- `contentNodeId?` (UUID)
|
||||
- `collectionId?` (UUID)
|
||||
- `questionIds?` (string | string[], 逗号分隔或重复传参)
|
||||
- `limit?` (int, 1-2000)
|
||||
- **响应**: `{ items: QuestionResponseDto[], meta }`
|
||||
- **QuestionResponseDto 字段** (extends CatalogEntityDto):
|
||||
- `id` (uuid)
|
||||
- `type` (string, 必填 — 题型)
|
||||
- `typeLabel` (string, nullable)
|
||||
- `difficulty` (number, nullable)
|
||||
- `content` (unknown, 题干)
|
||||
- `options` (array, 选项列表)
|
||||
- `explanation` (string, nullable — **敏感字段**)
|
||||
- `hasVideoExplanation` (boolean)
|
||||
- 继承字段: legacyId, name, title, regionId, order, isActive, description, metadata
|
||||
- **注意**: `options` 中包含正确选项标记、`explanation` 包含答案解析。RuoYi 在返回学生端 DTO 前必须剥离这些字段。
|
||||
|
||||
### 9. GET /api/catalog/content-entries
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `regionId?` (UUID)
|
||||
- `entryType?` (string)
|
||||
- `includeHidden?` (boolean, default false)
|
||||
- **响应**: `{ items: ContentEntryResponseDto[], meta }`
|
||||
|
||||
### 10. GET /api/catalog/content-nodes
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `entryId` (UUID, **必填**)
|
||||
- `parentId?` (string, "root" 表示根节点)
|
||||
- `mode?` ('children' | 'flat', default 'children')
|
||||
- `includeInactive?` (boolean, default false)
|
||||
- `markerType?` (string)
|
||||
- **响应**: `{ items: ContentNodeResponseDto[], meta }`
|
||||
|
||||
### 11. GET /api/catalog/question-collections
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `regionId?` (UUID)
|
||||
- `entryId?` (UUID)
|
||||
- `nodeId?` (UUID)
|
||||
- `collectionType?` (string)
|
||||
- `limit?` (int, 1-2000)
|
||||
- **响应**: `{ items: QuestionCollectionResponseDto[], meta }`
|
||||
|
||||
### 12. GET /api/catalog/question-collections/questions
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `collectionId` (UUID, **必填**)
|
||||
- `limit?` (int, 1-2000)
|
||||
- **响应**: `{ items: QuestionResponseDto[], meta }`
|
||||
|
||||
### 13. GET /api/catalog/practice-blueprints
|
||||
|
||||
- **安全方案**: `x-tenant-id`
|
||||
- **查询参数**:
|
||||
- `entryId?` (UUID)
|
||||
- `nodeId?` (UUID)
|
||||
- `collectionId?` (UUID)
|
||||
- `mode?` (string)
|
||||
- `limit?` (int, 1-2000)
|
||||
- **响应**: `{ items: PracticeBlueprintResponseDto[], meta }`
|
||||
- **字段**: id, mode, entryId, nodeId, collectionId, questionLimit, durationMinutes + CatalogEntityDto 继承字段
|
||||
|
||||
## 认证机制
|
||||
|
||||
### 租户识别
|
||||
- 所有 catalog 路径使用 `@TenantAccess()` 装饰器 → `AccessPolicy { kind: 'tenant' }`
|
||||
- 租户 ID 从 `x-tenant-id` 请求头提取(CORS 白名单包含此头)
|
||||
- `Principal` 装饰器从请求上下文提取 `principal.tenant.tenantId`
|
||||
|
||||
### Bearer Token
|
||||
- catalog 的大多数端点不需要 Bearer(只读、租户级访问)
|
||||
- `assets`、`assets/download`、`assets/preview` 需要 `@ApiBearerAuth()`
|
||||
- 学习写入路径 (`/api/learning/*`) 需要 `@ApiBearerAuth()` + `@TenantUserAccess()`
|
||||
|
||||
## 响应格式
|
||||
|
||||
### 成功
|
||||
```json
|
||||
{
|
||||
"items": [...],
|
||||
"meta": { "requestId": "uuid" }
|
||||
}
|
||||
```
|
||||
或
|
||||
```json
|
||||
{
|
||||
"item": {...},
|
||||
"meta": { "requestId": "uuid" }
|
||||
}
|
||||
```
|
||||
|
||||
### 错误
|
||||
```json
|
||||
{
|
||||
"error": "面向调用方的错误信息",
|
||||
"code": "REQUIRED_FIELD",
|
||||
"requestId": "uuid",
|
||||
"meta": { "requestId": "uuid" }
|
||||
}
|
||||
```
|
||||
|
||||
## 与 RuoYi adapter 的差异
|
||||
|
||||
| 项目 | RuoYi (Java) 假设 | Scalar (tiku-backend) 实际 |
|
||||
|------|-------------------|---------------------------|
|
||||
| 基础路径 | 配置的 `base-url` | `/api/catalog/*` |
|
||||
| 认证头 | `Authorization: Bearer <token>` | 大多数 catalog 端点只需 `x-tenant-id`,不需要 Bearer |
|
||||
| 租户头 | `x-tenant-id` | `x-tenant-id` ✅ 一致 |
|
||||
| 分页 | `page` + `pageSize` | `limit` (1-2000),无 page 参数! |
|
||||
| 题目过滤 | `published=true&hidden=false` 由 RuoYi 追加 | Scalar 端已有 `isActive` 过滤,但无 `published`/`hidden` query 参数 |
|
||||
| 响应 envelope | 预期 `items` + 可能的 `total` | `items` + `meta.requestId`,无 `total` 字段! |
|
||||
| 正确答案 | RuoYi 在返回学生端前剥离 | `QuestionResponseDto.options` 包含正确选项标记 |
|
||||
|
||||
## ⚠️ 关键差异
|
||||
|
||||
1. **分页**: RuoYi `ScalarCatalogProvider` 使用 `page` + `pageSize` query 参数,但 Scalar 只接受 `limit`。Java 端第 526-540 行固定追加 `page` 和 `pageSize` —— 这些参数在 Scalar controller 中不存在,会被忽略。
|
||||
2. **total 字段**: RuoYi adapter 期望服务端返回 `total` 用于分页,但 Scalar 响应没有此字段。如果 RuoYi 依赖 `total` 做前端分页计算,需要确认 adapter 如何处理。
|
||||
3. **published/hidden**: RuoYi 端固定追加 `published=true&hidden=false`,但这些参数在 Scalar controller DTO 中未定义。Scalar 的过滤逻辑在 repository 层而非 query 参数层。
|
||||
|
||||
## OpenAPI 生成方式
|
||||
|
||||
```bash
|
||||
# 需要 Docker + Supabase 运行
|
||||
cd tiku-backend
|
||||
npm run supabase:start
|
||||
npm run dev:api
|
||||
curl http://127.0.0.1:8787/openapi.json > /tmp/tiku-openapi.json
|
||||
|
||||
# 或通过测试套件(也会启动真实服务器)
|
||||
BACKEND_TEST_SKIP_DATABASE=true npm run test:backend:migration
|
||||
# 生成文件:/tmp/tiku-openapi.json
|
||||
```
|
||||
|
||||
当前环境不具备 Supabase/Docker,无法生成运行时 OpenAPI JSON。源码级契约已在此文档冻结。
|
||||
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
pom.xml
5
pom.xml
@@ -15,7 +15,8 @@
|
||||
<!-- 各种 module 拓展 -->
|
||||
<module>yudao-module-system</module>
|
||||
<module>yudao-module-infra</module>
|
||||
<!-- <module>yudao-module-member</module>-->
|
||||
<module>yudao-module-member</module>
|
||||
<module>yudao-module-education</module>
|
||||
<!-- <module>yudao-module-bpm</module>-->
|
||||
<!-- <module>yudao-module-report</module>-->
|
||||
<!-- <module>yudao-module-mp</module>-->
|
||||
@@ -32,7 +33,7 @@
|
||||
</modules>
|
||||
|
||||
<name>恭学教育</name>
|
||||
<description>恭学教育 - 让教育更简单。基于 Spring Boot + MyBatis Plus + Vue & Element 的后台管理系统。</description>
|
||||
<description>恭学教育 - 让教育更简单。基于 Spring Boot + MyBatis Plus + Vue & Element 的后台管理系统。</description>
|
||||
<url>https://www.gongxue.com</url>
|
||||
|
||||
<properties>
|
||||
|
||||
@@ -45,5 +45,5 @@ docker compose --env-file docker.env up -d
|
||||
|
||||
- admin ui: http://localhost:8080
|
||||
- api server: http://localhost:48080
|
||||
- mysql: root/123456, port: 3306
|
||||
- postgresql: root/123456, port: 5432
|
||||
- redis: port: 6379
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
version: "3.4"
|
||||
|
||||
name: yudao-system
|
||||
|
||||
services:
|
||||
mysql:
|
||||
container_name: yudao-mysql
|
||||
image: mysql:8
|
||||
postgres:
|
||||
container_name: yudao-postgres
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
tty: true
|
||||
ports:
|
||||
- "3306:3306"
|
||||
- "5432:5432"
|
||||
environment:
|
||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-ruoyi-vue-pro}
|
||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-123456}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-ruoyi-vue-pro}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-root}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-123456}
|
||||
volumes:
|
||||
- mysql:/var/lib/mysql/
|
||||
- ./sql/mysql/ruoyi-vue-pro.sql:/docker-entrypoint-initdb.d/ruoyi-vue-pro.sql:ro
|
||||
- postgres:/var/lib/postgresql/data/
|
||||
- ../../sql/postgresql/ruoyi-vue-pro.sql:/docker-entrypoint-initdb.d/000-ruoyi-vue-pro.sql:ro
|
||||
|
||||
redis:
|
||||
container_name: yudao-redis
|
||||
@@ -44,15 +42,15 @@ services:
|
||||
-Djava.security.egd=file:/dev/./urandom
|
||||
}
|
||||
ARGS:
|
||||
--spring.datasource.dynamic.datasource.master.url=${MASTER_DATASOURCE_URL:-jdbc:mysql://yudao-mysql:3306/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true}
|
||||
--spring.datasource.dynamic.datasource.master.url=${MASTER_DATASOURCE_URL:-jdbc:postgresql://yudao-postgres:5432/ruoyi-vue-pro}
|
||||
--spring.datasource.dynamic.datasource.master.username=${MASTER_DATASOURCE_USERNAME:-root}
|
||||
--spring.datasource.dynamic.datasource.master.password=${MASTER_DATASOURCE_PASSWORD:-123456}
|
||||
--spring.datasource.dynamic.datasource.slave.url=${SLAVE_DATASOURCE_URL:-jdbc:mysql://yudao-mysql:3306/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true}
|
||||
--spring.datasource.dynamic.datasource.slave.url=${SLAVE_DATASOURCE_URL:-jdbc:postgresql://yudao-postgres:5432/ruoyi-vue-pro}
|
||||
--spring.datasource.dynamic.datasource.slave.username=${SLAVE_DATASOURCE_USERNAME:-root}
|
||||
--spring.datasource.dynamic.datasource.slave.password=${SLAVE_DATASOURCE_PASSWORD:-123456}
|
||||
--spring.data.redis.host=${REDIS_HOST:-yudao-redis}
|
||||
depends_on:
|
||||
- mysql
|
||||
- postgres
|
||||
- redis
|
||||
|
||||
admin:
|
||||
@@ -78,7 +76,7 @@ services:
|
||||
- server
|
||||
|
||||
volumes:
|
||||
mysql:
|
||||
postgres:
|
||||
driver: local
|
||||
redis:
|
||||
driver: local
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
## mysql
|
||||
MYSQL_DATABASE=ruoyi-vue-pro
|
||||
MYSQL_ROOT_PASSWORD=123456
|
||||
## postgresql
|
||||
POSTGRES_DB=ruoyi-vue-pro
|
||||
POSTGRES_USER=root
|
||||
POSTGRES_PASSWORD=123456
|
||||
|
||||
## server
|
||||
JAVA_OPTS=-Xms512m -Xmx512m -Djava.security.egd=file:/dev/./urandom
|
||||
|
||||
MASTER_DATASOURCE_URL=jdbc:mysql://yudao-mysql:3306/${MYSQL_DATABASE}?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
MASTER_DATASOURCE_USERNAME=root
|
||||
MASTER_DATASOURCE_PASSWORD=${MYSQL_ROOT_PASSWORD}
|
||||
MASTER_DATASOURCE_URL=jdbc:postgresql://yudao-postgres:5432/${POSTGRES_DB}
|
||||
MASTER_DATASOURCE_USERNAME=${POSTGRES_USER}
|
||||
MASTER_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD}
|
||||
SLAVE_DATASOURCE_URL=${MASTER_DATASOURCE_URL}
|
||||
SLAVE_DATASOURCE_USERNAME=${MASTER_DATASOURCE_USERNAME}
|
||||
SLAVE_DATASOURCE_PASSWORD=${MASTER_DATASOURCE_PASSWORD}
|
||||
|
||||
8
sql/mysql/education/000-education-rollback.sql
Normal file
8
sql/mysql/education/000-education-rollback.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- =============================================
|
||||
-- Education 模块种子数据回滚
|
||||
-- =============================================
|
||||
|
||||
DELETE FROM `system_menu`
|
||||
WHERE `id` = 6801 AND `permission` = 'education:capability' AND `parent_id` = 6800;
|
||||
DELETE FROM `system_menu`
|
||||
WHERE `id` = 6800 AND `path` = '/education' AND `name` = '教育管理';
|
||||
5
sql/mysql/education/000-education-schema.sql
Normal file
5
sql/mysql/education/000-education-schema.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- =============================================
|
||||
-- Education 模块 DDL
|
||||
-- 当前为应用外壳阶段,无业务表;后续票据在此追加 CREATE TABLE 语句。
|
||||
-- =============================================
|
||||
-- 占位:education 模块当前无业务表
|
||||
15
sql/mysql/education/000-education-seed.sql
Normal file
15
sql/mysql/education/000-education-seed.sql
Normal file
@@ -0,0 +1,15 @@
|
||||
-- =============================================
|
||||
-- Education 模块种子数据
|
||||
-- 菜单 ID 范围:6800-6899
|
||||
-- 权限标识前缀:education:
|
||||
-- 可重复执行;角色授权由管理员按租户完成
|
||||
-- =============================================
|
||||
|
||||
INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `component_name`, `status`, `visible`, `keep_alive`, `always_show`, `creator`, `create_time`, `updater`, `update_time`, `deleted`)
|
||||
SELECT 6800, '教育管理', '', 1, 50, 0, '/education', 'ep:school', NULL, NULL, 0, b'1', b'1', b'1', 'admin', NOW(), 'admin', NOW(), b'0'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `system_menu` WHERE `id` = 6800);
|
||||
|
||||
INSERT INTO `system_menu` (`id`, `name`, `permission`, `type`, `sort`, `parent_id`, `path`, `icon`, `component`, `component_name`, `status`, `visible`, `keep_alive`, `always_show`, `creator`, `create_time`, `updater`, `update_time`, `deleted`)
|
||||
SELECT 6801, '能力查询', 'education:capability', 3, 1, 6800, '', '', '', NULL, 0, b'1', b'1', b'1', 'admin', NOW(), 'admin', NOW(), b'0'
|
||||
WHERE EXISTS (SELECT 1 FROM `system_menu` WHERE `id` = 6800 AND `path` = '/education' AND `deleted` = b'0')
|
||||
AND NOT EXISTS (SELECT 1 FROM `system_menu` WHERE `id` = 6801);
|
||||
1
sql/mysql/education/001-education-tenant-rollback.sql
Normal file
1
sql/mysql/education/001-education-tenant-rollback.sql
Normal file
@@ -0,0 +1 @@
|
||||
-- Ticket #3 creates no database records, so rollback is intentionally a no-op.
|
||||
3
sql/mysql/education/001-education-tenant-seed.sql
Normal file
3
sql/mysql/education/001-education-tenant-seed.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
-- Ticket #3 adds no administrator permission.
|
||||
-- Tenant resolution is @PermitAll and current education context only requires an authenticated Member session.
|
||||
-- Therefore no system_menu rows are required for this vertical slice.
|
||||
@@ -0,0 +1,28 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 练习会话与题目快照回滚
|
||||
-- Ticket #6 / Migration 002
|
||||
-- =============================================
|
||||
--
|
||||
-- WARNING: This file contains NO executable SQL.
|
||||
-- Destructive rollback (DROP TABLE) requires manual operator verification.
|
||||
--
|
||||
-- Manual rollback procedure (operator must execute):
|
||||
-- 1. Verify no other tables depend on these tables:
|
||||
-- SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME
|
||||
-- FROM information_schema.KEY_COLUMN_USAGE
|
||||
-- WHERE REFERENCED_TABLE_NAME IN ('education_practice_session', 'education_practice_question')
|
||||
-- AND TABLE_SCHEMA = DATABASE();
|
||||
-- Result MUST be empty before proceeding.
|
||||
--
|
||||
-- 2. Verify the tables contain only data from this migration:
|
||||
-- SELECT COUNT(*) AS session_count FROM education_practice_session;
|
||||
-- SELECT COUNT(*) AS question_count FROM education_practice_question;
|
||||
-- Operator must confirm these counts are acceptable to destroy.
|
||||
--
|
||||
-- 3. After verification, execute:
|
||||
-- DROP TABLE IF EXISTS education_practice_question;
|
||||
-- DROP TABLE IF EXISTS education_practice_session;
|
||||
--
|
||||
-- DO NOT uncomment or execute the lines below without operator verification.
|
||||
-- -- DROP TABLE IF EXISTS education_practice_question;
|
||||
-- -- DROP TABLE IF EXISTS education_practice_session;
|
||||
101
sql/mysql/education/002-education-practice-session.sql
Normal file
101
sql/mysql/education/002-education-practice-session.sql
Normal file
@@ -0,0 +1,101 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 练习会话与题目快照 DDL
|
||||
-- Ticket #6: 练习会话创建、题目快照、恢复与状态机
|
||||
-- Migration: 002
|
||||
-- Prerequisites: 000-education-schema.sql (database creation)
|
||||
-- 001-education-tenant-seed.sql (tenant seed data)
|
||||
-- =============================================
|
||||
|
||||
-- =============================================
|
||||
-- Preconditions
|
||||
-- =============================================
|
||||
-- This migration MUST fail if either table already exists (no IF NOT EXISTS).
|
||||
-- Operator is expected to verify:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name IN ('education_practice_session', 'education_practice_question');
|
||||
-- Result MUST be 0 before executing this migration.
|
||||
|
||||
-- =============================================
|
||||
-- 练习会话表
|
||||
-- =============================================
|
||||
-- Indexes:
|
||||
-- uk_tenant_client_session — per-tenant uniqueness for clientSessionId idempotency.
|
||||
-- Used by: selectByTenantAndClientSessionId (idempotent create check),
|
||||
-- DuplicateKeyException catch for concurrent-create race resolution.
|
||||
-- idx_tenant_user_status — covers getCurrentSession (latest ACTIVE by tenant+user)
|
||||
-- and ownership queries. Column order: (tenant_id, user_id, status) so the
|
||||
-- index supports both filtering by tenant+user and tenant+user+status.
|
||||
-- Lock impact: INSERT acquires next-key lock on uk_tenant_client_session unique key;
|
||||
-- concurrent inserts with same (tenant_id, client_session_id) serialize naturally.
|
||||
-- No additional table-level locks required.
|
||||
CREATE TABLE `education_practice_session` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '会话主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT 'Member 用户编号',
|
||||
`client_session_id` VARCHAR(36) NOT NULL COMMENT '客户端生成的会话标识(UUID),用于幂等创建',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'ACTIVE'
|
||||
COMMENT '会话状态:ACTIVE-进行中, SUBMITTED-已提交, EXPIRED-已过期, CANCELLED-已取消',
|
||||
`question_count` INT NOT NULL DEFAULT 0 COMMENT '题目总数',
|
||||
`collection_id` VARCHAR(64) DEFAULT NULL COMMENT '源题集 ID',
|
||||
`node_id` VARCHAR(64) DEFAULT NULL COMMENT '源目录节点 ID',
|
||||
`type` VARCHAR(32) DEFAULT NULL COMMENT '筛选题型',
|
||||
`difficulty` VARCHAR(32) DEFAULT NULL COMMENT '筛选难度',
|
||||
`version` INT NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_client_session` (`tenant_id`, `client_session_id`),
|
||||
KEY `idx_tenant_user_status` (`tenant_id`, `user_id`, `status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-练习会话';
|
||||
|
||||
-- =============================================
|
||||
-- 练习会话题目快照表
|
||||
-- =============================================
|
||||
-- Indexes:
|
||||
-- uk_session_sequence — per-session uniqueness for question sequence numbers.
|
||||
-- Used by: insertBatch to ensure no duplicate sequences within a session.
|
||||
-- idx_session_id — covers selectBySessionIdOrderBySequence (load all questions
|
||||
-- for a session, ordered by sequence). Also used by cascade delete lookups.
|
||||
-- Lock impact: INSERT acquires gap locks within session_id range on uk_session_sequence;
|
||||
-- concurrent inserts into different sessions are independent.
|
||||
-- Options column: JSON data type stores only label, content, order — never isCorrect.
|
||||
-- Application layer (optionsToSafeJson) strips correctness before storage.
|
||||
CREATE TABLE `education_practice_question` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`session_id` BIGINT NOT NULL COMMENT '会话 ID',
|
||||
`sequence` INT NOT NULL COMMENT '题目序号(1-based,服务端固定)',
|
||||
`question_id` VARCHAR(64) NOT NULL COMMENT '原始题目 ID',
|
||||
`content_version` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '快照时的题目内容版本',
|
||||
`stem` TEXT NOT NULL COMMENT '题干快照',
|
||||
`type` VARCHAR(32) NOT NULL COMMENT '题型快照',
|
||||
`difficulty` VARCHAR(32) DEFAULT NULL COMMENT '难度快照',
|
||||
`options` JSON NOT NULL COMMENT '选项快照 JSON(不含 isCorrect)',
|
||||
`selected_answer` TEXT DEFAULT NULL COMMENT '学生已选答案',
|
||||
`is_answered` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否已作答',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_session_sequence` (`session_id`, `sequence`),
|
||||
KEY `idx_session_id` (`session_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-练习会话题目快照';
|
||||
|
||||
-- =============================================
|
||||
-- Post-migration verification queries
|
||||
-- =============================================
|
||||
-- Verify tables exist with correct structure:
|
||||
-- SHOW CREATE TABLE education_practice_session;
|
||||
-- SHOW CREATE TABLE education_practice_question;
|
||||
-- Verify unique keys are enforced:
|
||||
-- SHOW INDEX FROM education_practice_session WHERE Key_name = 'uk_tenant_client_session';
|
||||
-- SHOW INDEX FROM education_practice_question WHERE Key_name = 'uk_session_sequence';
|
||||
-- Verify no orphan data (should be 0 after fresh migration):
|
||||
-- SELECT COUNT(*) FROM education_practice_session;
|
||||
-- SELECT COUNT(*) FROM education_practice_question;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 答案保存幂等性回滚
|
||||
-- Ticket #7 / Migration 003
|
||||
-- =============================================
|
||||
--
|
||||
-- WARNING: This file contains NO executable SQL.
|
||||
-- Destructive rollback requires manual operator verification.
|
||||
--
|
||||
-- Manual rollback procedure (operator must execute):
|
||||
-- 1. Verify no other tables depend on education_answer_idempotency:
|
||||
-- SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME
|
||||
-- FROM information_schema.KEY_COLUMN_USAGE
|
||||
-- WHERE REFERENCED_TABLE_NAME = 'education_answer_idempotency'
|
||||
-- AND TABLE_SCHEMA = DATABASE();
|
||||
-- Result MUST be empty before proceeding.
|
||||
--
|
||||
-- 2. Verify the table contains only data from this migration:
|
||||
-- SELECT COUNT(*) AS idempotency_count FROM education_answer_idempotency;
|
||||
-- Operator must confirm this count is acceptable to destroy.
|
||||
--
|
||||
-- 3. Verify no application code depends on client_sequence column:
|
||||
-- Search codebase for 'clientSequence' / 'client_sequence' references.
|
||||
--
|
||||
-- 4. After verification, execute:
|
||||
-- DROP TABLE IF EXISTS education_answer_idempotency;
|
||||
-- ALTER TABLE education_practice_question DROP COLUMN client_sequence;
|
||||
--
|
||||
-- DO NOT uncomment or execute the lines below without operator verification.
|
||||
-- -- DROP TABLE IF EXISTS education_answer_idempotency;
|
||||
-- -- ALTER TABLE education_practice_question DROP COLUMN client_sequence;
|
||||
97
sql/mysql/education/003-education-answer-idempotency.sql
Normal file
97
sql/mysql/education/003-education-answer-idempotency.sql
Normal file
@@ -0,0 +1,97 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 答案保存幂等性 DDL
|
||||
-- Ticket #7: 答案命令幂等、乐观锁并发控制、答案恢复
|
||||
-- Migration: 003
|
||||
-- Prerequisites: 002-education-practice-session.sql (session + question snapshots)
|
||||
-- =============================================
|
||||
|
||||
-- =============================================
|
||||
-- Preconditions
|
||||
-- =============================================
|
||||
-- Operator is expected to verify:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name = 'education_answer_idempotency';
|
||||
-- Result MUST be 0 before executing this migration.
|
||||
--
|
||||
-- Verify prerequisite tables exist:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name IN ('education_practice_session', 'education_practice_question');
|
||||
-- Result MUST be 2.
|
||||
|
||||
-- =============================================
|
||||
-- 答案命令幂等表
|
||||
-- =============================================
|
||||
-- Purpose: Provide durable idempotency for answer save commands.
|
||||
-- Same (tenant, user, operation, idempotency_key) + same request_hash → replay original response.
|
||||
-- Same key + different request_hash → conflict.
|
||||
-- Concurrent same-key inserts are resolved by unique constraint race handling.
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_answer_idempotency — per-tenant, per-actor, per-operation uniqueness for idempotency key.
|
||||
-- INSERT during answer save. DuplicateKeyException catch for concurrent-create race resolution.
|
||||
-- idx_tenant_session — covers lookup by session for audit/debug.
|
||||
--
|
||||
-- response_json: Stores the serialized answer response for replay after network timeout/retry.
|
||||
-- request_hash: SHA-256 of canonical payload (sorted JSON fields) for content-based dedup.
|
||||
CREATE TABLE `education_answer_idempotency` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '答题用户编号',
|
||||
`operation` VARCHAR(32) NOT NULL DEFAULT 'SUBMIT_ANSWER'
|
||||
COMMENT '操作类型:SUBMIT_ANSWER',
|
||||
`idempotency_key` VARCHAR(64) NOT NULL COMMENT '客户端幂等键(UUID)',
|
||||
`request_hash` VARCHAR(64) NOT NULL COMMENT '请求载荷 SHA-256 哈希',
|
||||
`session_id` BIGINT NOT NULL COMMENT '会话 ID',
|
||||
`question_id` VARCHAR(64) NOT NULL COMMENT '题目 ID',
|
||||
`selected_answer` TEXT DEFAULT NULL COMMENT '学生已选答案',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'ACCEPTED'
|
||||
COMMENT '状态:ACCEPTED-已接受, CONFLICT-冲突',
|
||||
`response_json` TEXT NOT NULL COMMENT '首次成功响应 JSON(用于重试重放)',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_answer_idempotency` (`tenant_id`, `user_id`, `operation`, `idempotency_key`),
|
||||
KEY `idx_tenant_session` (`tenant_id`, `session_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-答案命令幂等记录';
|
||||
|
||||
-- =============================================
|
||||
-- PracticeQuestionDO: add client_sequence column
|
||||
-- =============================================
|
||||
-- Purpose: Track the last accepted client command sequence per question.
|
||||
-- Rejects stale clientSequence: only sequences strictly greater than the
|
||||
-- stored value are accepted (monotonic forward progression).
|
||||
-- NULL means no answer has been accepted yet.
|
||||
ALTER TABLE `education_practice_question`
|
||||
ADD COLUMN `client_sequence` INT DEFAULT NULL COMMENT '最后接受的客户端命令序号',
|
||||
ADD INDEX `idx_client_sequence` (`client_sequence`);
|
||||
|
||||
-- =============================================
|
||||
-- PracticeSessionDO: add last_client_sequence column
|
||||
-- =============================================
|
||||
-- Purpose: Session-wide monotonic counter for client commands.
|
||||
-- Rejects stale clientSequence across questions (not just per-question).
|
||||
-- CAS incrementVersion now updates this column alongside version.
|
||||
-- NULL means no answer has been accepted yet for this session.
|
||||
ALTER TABLE `education_practice_session`
|
||||
ADD COLUMN `last_client_sequence` INT DEFAULT NULL COMMENT '会话级最后接受的客户端命令序号(跨题目)';
|
||||
|
||||
-- =============================================
|
||||
-- Post-migration verification queries
|
||||
-- =============================================
|
||||
-- Verify new table exists:
|
||||
-- SHOW CREATE TABLE education_answer_idempotency;
|
||||
-- Verify unique key is enforced:
|
||||
-- SHOW INDEX FROM education_answer_idempotency WHERE Key_name = 'uk_answer_idempotency';
|
||||
-- Verify column added to question table:
|
||||
-- SELECT COLUMN_NAME, DATA_TYPE, COLUMN_DEFAULT
|
||||
-- FROM information_schema.COLUMNS
|
||||
-- WHERE TABLE_SCHEMA = DATABASE()
|
||||
-- AND TABLE_NAME = 'education_practice_question'
|
||||
-- AND COLUMN_NAME = 'client_sequence';
|
||||
-- Verify no orphan data (should be 0 after fresh migration):
|
||||
-- SELECT COUNT(*) FROM education_answer_idempotency;
|
||||
42
sql/mysql/education/004-education-submit-report-rollback.sql
Normal file
42
sql/mysql/education/004-education-submit-report-rollback.sql
Normal file
@@ -0,0 +1,42 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — Ticket #8 迁移回滚
|
||||
-- 004-education-submit-report-rollback.sql
|
||||
-- =============================================
|
||||
--
|
||||
-- WARNING: This file contains NO executable SQL.
|
||||
-- Destructive rollback requires manual operator verification.
|
||||
--
|
||||
-- Manual rollback procedure (operator must execute):
|
||||
-- 1. Verify no other tables depend on these tables:
|
||||
-- SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME
|
||||
-- FROM information_schema.KEY_COLUMN_USAGE
|
||||
-- WHERE REFERENCED_TABLE_NAME IN ('education_submit_idempotency',
|
||||
-- 'education_practice_report', 'education_practice_report_detail')
|
||||
-- AND TABLE_SCHEMA = DATABASE();
|
||||
-- Result MUST be empty before proceeding.
|
||||
--
|
||||
-- 2. Verify columns are not referenced by application code:
|
||||
-- Search codebase for 'correct_answer' / 'explanation' references in
|
||||
-- education_practice_question to confirm no other consumers.
|
||||
--
|
||||
-- 3. Verify the tables contain only data from this migration:
|
||||
-- SELECT COUNT(*) AS idempotency_count FROM education_submit_idempotency;
|
||||
-- SELECT COUNT(*) AS report_count FROM education_practice_report;
|
||||
-- SELECT COUNT(*) AS detail_count FROM education_practice_report_detail;
|
||||
-- Operator must confirm these counts are acceptable to destroy.
|
||||
--
|
||||
-- 4. After verification, execute:
|
||||
-- DROP TABLE IF EXISTS education_practice_report_detail;
|
||||
-- DROP TABLE IF EXISTS education_practice_report;
|
||||
-- DROP TABLE IF EXISTS education_submit_idempotency;
|
||||
-- ALTER TABLE education_practice_question
|
||||
-- DROP COLUMN correct_answer,
|
||||
-- DROP COLUMN explanation;
|
||||
--
|
||||
-- DO NOT uncomment or execute the lines below without operator verification.
|
||||
-- -- DROP TABLE IF EXISTS education_practice_report_detail;
|
||||
-- -- DROP TABLE IF EXISTS education_practice_report;
|
||||
-- -- DROP TABLE IF EXISTS education_submit_idempotency;
|
||||
-- -- ALTER TABLE education_practice_question
|
||||
-- -- DROP COLUMN correct_answer,
|
||||
-- -- DROP COLUMN explanation;
|
||||
164
sql/mysql/education/004-education-submit-report.sql
Normal file
164
sql/mysql/education/004-education-submit-report.sql
Normal file
@@ -0,0 +1,164 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 交卷提交与成绩报告 DDL
|
||||
-- Ticket #8: 交卷 CAS、保护性答案快照、评分与报告
|
||||
-- Migration: 004
|
||||
-- Prerequisites: 003-education-answer-idempotency.sql
|
||||
-- =============================================
|
||||
|
||||
-- =============================================
|
||||
-- Preconditions
|
||||
-- =============================================
|
||||
-- Operator is expected to verify:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name IN ('education_submit_idempotency',
|
||||
-- 'education_practice_report',
|
||||
-- 'education_practice_report_detail');
|
||||
-- Result MUST be 0 before executing this migration.
|
||||
--
|
||||
-- Verify prerequisite tables exist:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name IN ('education_practice_session',
|
||||
-- 'education_practice_question',
|
||||
-- 'education_answer_idempotency');
|
||||
-- Result MUST be 3.
|
||||
|
||||
-- =============================================
|
||||
-- PracticeQuestionDO: add protected answer snapshot columns
|
||||
-- =============================================
|
||||
-- Purpose: At session creation, snapshot correct_answer and explanation
|
||||
-- from the full CatalogQuestionDTO. These fields are NEVER exposed
|
||||
-- before submission (enforced by SafeQuestionRespVO allow-list and
|
||||
-- PracticeQuestionRespVO which does not include them).
|
||||
ALTER TABLE `education_practice_question`
|
||||
ADD COLUMN `correct_answer` TEXT DEFAULT NULL COMMENT '正确答案快照(不可在交卷前暴露)',
|
||||
ADD COLUMN `explanation` TEXT DEFAULT NULL COMMENT '解析快照(不可在交卷前暴露)';
|
||||
|
||||
-- =============================================
|
||||
-- 交卷幂等表
|
||||
-- =============================================
|
||||
-- Purpose: Provide durable idempotency for submit-session commands.
|
||||
-- Same (tenant, user, operation, idempotency_key) + same request_hash → replay original report.
|
||||
-- Same key + different request_hash → conflict.
|
||||
-- Concurrent same-key inserts resolved by unique constraint race handling.
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_submit_idempotency — per-tenant, per-actor, per-operation uniqueness for idempotency key.
|
||||
-- INSERT during submit. DuplicateKeyException catch for concurrent-create race resolution.
|
||||
-- idx_submit_session — covers lookup by session for audit/debug.
|
||||
CREATE TABLE `education_submit_idempotency` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '交卷用户编号',
|
||||
`operation` VARCHAR(32) NOT NULL DEFAULT 'SUBMIT_SESSION'
|
||||
COMMENT '操作类型:SUBMIT_SESSION',
|
||||
`idempotency_key` VARCHAR(64) NOT NULL COMMENT '客户端幂等键(UUID)',
|
||||
`request_hash` VARCHAR(64) NOT NULL COMMENT '请求载荷 SHA-256 哈希',
|
||||
`session_id` BIGINT NOT NULL COMMENT '会话 ID',
|
||||
`report_id` BIGINT DEFAULT NULL COMMENT '关联的报告 ID(成功时有值)',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'ACCEPTED'
|
||||
COMMENT '状态:ACCEPTED-已接受, CONFLICT-冲突',
|
||||
`response_json` TEXT NOT NULL COMMENT '首次成功响应 JSON(用于重试重放)',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_submit_idempotency` (`tenant_id`, `user_id`, `operation`, `idempotency_key`),
|
||||
KEY `idx_submit_session` (`tenant_id`, `session_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-交卷幂等记录';
|
||||
|
||||
-- =============================================
|
||||
-- 练习报告表(会话级)
|
||||
-- =============================================
|
||||
-- Purpose: Store the computed scoring result for a submitted session.
|
||||
-- One report per session. Immutable after creation.
|
||||
-- Question snapshots (stem, selectedAnswer, correctAnswer, explanation)
|
||||
-- are stored in report_details so source question edits don't affect history.
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_report_session — one report per session (unique).
|
||||
-- idx_report_tenant_user — covers paginated history queries for current tenant+user.
|
||||
-- idx_report_create_time — covers time-sorted listing.
|
||||
CREATE TABLE `education_practice_report` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '用户编号',
|
||||
`session_id` BIGINT NOT NULL COMMENT '会话 ID',
|
||||
`question_count` INT NOT NULL COMMENT '题目总数',
|
||||
`answered_count` INT NOT NULL DEFAULT 0 COMMENT '已答题数',
|
||||
`unanswered_count` INT NOT NULL DEFAULT 0 COMMENT '未答题数',
|
||||
`correct_count` INT NOT NULL DEFAULT 0 COMMENT '正确题数',
|
||||
`incorrect_count` INT NOT NULL DEFAULT 0 COMMENT '错误题数',
|
||||
`score` INT NOT NULL DEFAULT 0 COMMENT '得分(整数,满分 100 为基准)',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'SUBMITTED'
|
||||
COMMENT '报告状态:SUBMITTED',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_report_session` (`session_id`),
|
||||
KEY `idx_report_tenant_user` (`tenant_id`, `user_id`),
|
||||
KEY `idx_report_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-练习报告';
|
||||
|
||||
-- =============================================
|
||||
-- 练习报告明细表(逐题结果)
|
||||
-- =============================================
|
||||
-- Purpose: Store per-question scoring results at submission time.
|
||||
-- Includes snapshot of stem, selectedAnswer, correctAnswer, and explanation
|
||||
-- so that history is stable even if source questions are later edited.
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_report_sequence — per-report uniqueness for question sequence.
|
||||
-- idx_detail_session — covers lookup by session for report assembly.
|
||||
CREATE TABLE `education_practice_report_detail` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '用户编号',
|
||||
`report_id` BIGINT NOT NULL COMMENT '报告 ID',
|
||||
`session_id` BIGINT NOT NULL COMMENT '会话 ID',
|
||||
`question_id` VARCHAR(64) NOT NULL COMMENT '原始题目 ID',
|
||||
`sequence` INT NOT NULL COMMENT '题目序号(1-based)',
|
||||
`stem` TEXT NOT NULL COMMENT '题干快照',
|
||||
`type` VARCHAR(32) NOT NULL COMMENT '题型快照',
|
||||
`difficulty` VARCHAR(32) DEFAULT NULL COMMENT '难度快照',
|
||||
`selected_answer` TEXT DEFAULT NULL COMMENT '学生已选答案',
|
||||
`correct_answer` TEXT DEFAULT NULL COMMENT '正确答案快照',
|
||||
`is_correct` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否正确',
|
||||
`explanation` TEXT DEFAULT NULL COMMENT '解析快照',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_report_sequence` (`report_id`, `sequence`),
|
||||
KEY `idx_detail_session` (`session_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-练习报告明细';
|
||||
|
||||
-- =============================================
|
||||
-- Post-migration verification queries
|
||||
-- =============================================
|
||||
-- Verify new tables exist:
|
||||
-- SHOW CREATE TABLE education_submit_idempotency;
|
||||
-- SHOW CREATE TABLE education_practice_report;
|
||||
-- SHOW CREATE TABLE education_practice_report_detail;
|
||||
-- Verify columns added to question table:
|
||||
-- SELECT COLUMN_NAME, DATA_TYPE, COLUMN_DEFAULT
|
||||
-- FROM information_schema.COLUMNS
|
||||
-- WHERE TABLE_SCHEMA = DATABASE()
|
||||
-- AND TABLE_NAME = 'education_practice_question'
|
||||
-- AND COLUMN_NAME IN ('correct_answer', 'explanation');
|
||||
-- Verify unique keys are enforced:
|
||||
-- SHOW INDEX FROM education_submit_idempotency WHERE Key_name = 'uk_submit_idempotency';
|
||||
-- SHOW INDEX FROM education_practice_report WHERE Key_name = 'uk_report_session';
|
||||
-- SHOW INDEX FROM education_practice_report_detail WHERE Key_name = 'uk_report_sequence';
|
||||
-- Verify no orphan data (should be 0 after fresh migration):
|
||||
-- SELECT COUNT(*) FROM education_submit_idempotency;
|
||||
-- SELECT COUNT(*) FROM education_practice_report;
|
||||
-- SELECT COUNT(*) FROM education_practice_report_detail;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 错题本 DDL Rollback
|
||||
-- Migration: 005
|
||||
-- =============================================
|
||||
-- IMPORTANT: This is a documentation-only rollback.
|
||||
-- No DROP/ALTER/DELETE statements are executed. The wrong_question
|
||||
-- table is provenance-safe: it only accumulates data and mastering
|
||||
-- is a status flag. Dropping these tables would lose student error
|
||||
-- history with no recovery path.
|
||||
--
|
||||
-- What this migration created:
|
||||
-- - education_wrong_question (new table)
|
||||
-- - education_wrong_question_idempotency (new table)
|
||||
-- - education_practice_report_detail.options (new column)
|
||||
-- - education_practice_session.review_fingerprint (new column)
|
||||
--
|
||||
-- Manual rollback requires:
|
||||
-- 1. Verified database backup before rollback
|
||||
-- 2. Operator approval (DBA sign-off)
|
||||
-- 3. Provenance of all wrong-question records preserved (exported)
|
||||
-- 4. Soft-delete via deleted = b'1' before any hard drop
|
||||
--
|
||||
-- These tables are NOT deleted by this script. Wrong history is
|
||||
-- retained; if deletion is required by external policy, consult
|
||||
-- the DBA for a verified rollback procedure.
|
||||
154
sql/mysql/education/005-education-wrong-question.sql
Normal file
154
sql/mysql/education/005-education-wrong-question.sql
Normal file
@@ -0,0 +1,154 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 错题本 DDL
|
||||
-- Ticket #9: 错题自动收集、复习练习创建
|
||||
-- Migration: 005
|
||||
-- Prerequisites: 004-education-submit-report.sql (report + detail tables)
|
||||
-- =============================================
|
||||
|
||||
-- =============================================
|
||||
-- Preconditions
|
||||
-- =============================================
|
||||
-- Operator is expected to verify:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name IN ('education_wrong_question',
|
||||
-- 'education_wrong_question_idempotency');
|
||||
-- Result MUST be 0 before executing this migration.
|
||||
--
|
||||
-- Verify prerequisite tables exist:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name IN ('education_practice_report',
|
||||
-- 'education_practice_report_detail');
|
||||
-- Result MUST be 2.
|
||||
|
||||
-- =============================================
|
||||
-- PracticeReportDetailDO: add options snapshot column
|
||||
-- =============================================
|
||||
-- PracticeReportDetailDO: add content_version + options snapshot columns
|
||||
-- =============================================
|
||||
-- Purpose: At submit time, snapshot question content version and options
|
||||
-- (without isCorrect) so wrong-question book and review sessions have
|
||||
-- stable display data. The options are already stripped of isCorrect
|
||||
-- by the submit flow.
|
||||
ALTER TABLE `education_practice_report_detail`
|
||||
ADD COLUMN `content_version` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '题目内容版本快照',
|
||||
ADD COLUMN `options` TEXT DEFAULT NULL COMMENT '选项快照 JSON(不含 isCorrect)';
|
||||
|
||||
-- =============================================
|
||||
-- PracticeSessionDO: add review fingerprint column
|
||||
-- =============================================
|
||||
-- Purpose: Persist the canonical fingerprint of wrong-question IDs used
|
||||
-- to create a review session. On idempotent replay, the fingerprint
|
||||
-- is compared: same tenant+clientSessionId+sameUser+sortedIDs match
|
||||
-- returns the existing session; different ID set returns
|
||||
-- SESSION_IDEMPOTENCY_MISMATCH.
|
||||
ALTER TABLE `education_practice_session`
|
||||
ADD COLUMN `review_fingerprint` VARCHAR(64) DEFAULT NULL COMMENT '复习会话题目指纹(SHA-256 of sorted unique wrongQuestionIds)';
|
||||
-- 错题表
|
||||
-- =============================================
|
||||
-- Purpose: Persistent wrong-question book per student.
|
||||
-- Each (tenant, user, question) is a unique entry.
|
||||
-- Repeated wrong answers on the SAME question increment wrong_count
|
||||
-- and update last_wrong_time. The idempotency guard table ensures
|
||||
-- each (tenant, user, question, report) can upsert at most once.
|
||||
--
|
||||
-- master_status values: 'PENDING' (default) | 'MASTERED'
|
||||
-- Marking mastered retains the full history and count; it does NOT
|
||||
-- delete or archive the record. Students can optionally un-master.
|
||||
--
|
||||
-- Snapshot fields (stem, type, difficulty, options, content_version):
|
||||
-- populated from the latest report detail that touched this question.
|
||||
-- These are for listing/detail display without joining report details.
|
||||
--
|
||||
-- latest_correct_answer, latest_explanation:
|
||||
-- also from the latest report detail; available for detail display
|
||||
-- post-submit (not exposed in review session creation pre-submit).
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_tenant_user_question — per-tenant, per-user, per-question uniqueness.
|
||||
-- INSERT ... ON DUPLICATE KEY UPDATE is the primary write path.
|
||||
-- idx_tenant_user_status — covers filtered list queries (page with status filter).
|
||||
-- idx_tenant_user_last_wrong — covers time-sorted listing.
|
||||
CREATE TABLE `education_wrong_question` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '学生用户编号',
|
||||
`question_id` VARCHAR(64) NOT NULL COMMENT '原始题目 ID',
|
||||
-- snapshot fields for listing / detail (from latest report detail)
|
||||
`stem` TEXT NOT NULL COMMENT '题干快照(最新)',
|
||||
`type` VARCHAR(32) NOT NULL COMMENT '题型快照',
|
||||
`difficulty` VARCHAR(32) DEFAULT NULL COMMENT '难度快照',
|
||||
`options` JSON NOT NULL COMMENT '选项快照 JSON(不含 isCorrect)',
|
||||
`content_version` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '题目内容版本',
|
||||
`latest_correct_answer` TEXT DEFAULT NULL COMMENT '正确答案快照(最新,供详情展示)',
|
||||
`latest_explanation` TEXT DEFAULT NULL COMMENT '解析快照(最新,供详情展示)',
|
||||
-- timing & count
|
||||
`first_wrong_time` DATETIME NOT NULL COMMENT '首次错误时间',
|
||||
`last_wrong_time` DATETIME NOT NULL COMMENT '最近错误时间',
|
||||
`wrong_count` INT NOT NULL DEFAULT 1 COMMENT '累计错误次数',
|
||||
-- mastery
|
||||
`master_status` VARCHAR(20) NOT NULL DEFAULT 'PENDING'
|
||||
COMMENT '掌握状态:PENDING-待掌握, MASTERED-已掌握',
|
||||
`mastered_time` DATETIME DEFAULT NULL COMMENT '标记掌握时间',
|
||||
-- provenance
|
||||
`last_report_id` BIGINT DEFAULT NULL COMMENT '最近关联的报告 ID',
|
||||
`last_session_id` BIGINT DEFAULT NULL COMMENT '最近关联的会话 ID',
|
||||
-- audit
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_user_question` (`tenant_id`, `user_id`, `question_id`),
|
||||
KEY `idx_tenant_user_status` (`tenant_id`, `user_id`, `master_status`),
|
||||
KEY `idx_tenant_user_last_wrong` (`tenant_id`, `user_id`, `last_wrong_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-错题本';
|
||||
|
||||
-- =============================================
|
||||
-- 错题流水幂等表
|
||||
-- =============================================
|
||||
-- Purpose: Ensure each (tenant, user, question, report) upserts the
|
||||
-- wrong-question book exactly once. The submitSession transaction
|
||||
-- INSERT IGNOREs into this table BEFORE the wrong question upsert;
|
||||
-- a duplicate means this report already contributed to the count.
|
||||
-- This guards against:
|
||||
-- - Replayed submit (idempotent resubmit) double-counting
|
||||
-- - Concurrent submit races where both threads evaluate the
|
||||
-- same report details
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_tenant_user_question_report — per (tenant, user, question, report) uniqueness.
|
||||
-- INSERT IGNORE provides the idempotency guard BEFORE upserting.
|
||||
-- wrong_question_id is filled after upsert for audit purposes.
|
||||
-- idx_report — fast lookup by report for audit/debug.
|
||||
CREATE TABLE `education_wrong_question_idempotency` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '学生用户编号',
|
||||
`wrong_question_id` BIGINT DEFAULT NULL COMMENT '错题记录 ID(upsert 后填充)',
|
||||
`report_id` BIGINT NOT NULL COMMENT '报告 ID',
|
||||
`question_id` VARCHAR(64) NOT NULL COMMENT '题目 ID',
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_user_question_report` (`tenant_id`, `user_id`, `question_id`, `report_id`),
|
||||
KEY `idx_report` (`report_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-错题流水幂等';
|
||||
|
||||
-- =============================================
|
||||
-- Post-migration verification queries
|
||||
-- =============================================
|
||||
-- Verify new tables exist:
|
||||
-- SHOW CREATE TABLE education_wrong_question;
|
||||
-- SHOW CREATE TABLE education_wrong_question_idempotency;
|
||||
-- Verify unique keys are enforced:
|
||||
-- SHOW INDEX FROM education_wrong_question WHERE Key_name = 'uk_tenant_user_question';
|
||||
-- SHOW INDEX FROM education_wrong_question_idempotency WHERE Key_name = 'uk_tenant_user_question_report';
|
||||
-- Verify no orphan data (should be 0 after fresh migration):
|
||||
-- SELECT COUNT(*) FROM education_wrong_question;
|
||||
-- SELECT COUNT(*) FROM education_wrong_question_idempotency;
|
||||
22
sql/mysql/education/007-education-favorite-rollback.sql
Normal file
22
sql/mysql/education/007-education-favorite-rollback.sql
Normal file
@@ -0,0 +1,22 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 收藏夹 DDL Rollback
|
||||
-- Migration: 007
|
||||
-- =============================================
|
||||
-- IMPORTANT: This is a documentation-only rollback.
|
||||
-- No DROP/ALTER/DELETE statements are executed. The favorite
|
||||
-- table is provenance-safe: it only accumulates user preference
|
||||
-- data. Dropping this table would lose student favorites with
|
||||
-- no recovery path.
|
||||
--
|
||||
-- What this migration created:
|
||||
-- - education_favorite (new table)
|
||||
--
|
||||
-- Manual rollback requires:
|
||||
-- 1. Verified database backup before rollback
|
||||
-- 2. Operator approval (DBA sign-off)
|
||||
-- 3. Provenance of all favorite records preserved (exported)
|
||||
-- 4. Soft-delete via deleted = b'1' before any hard drop
|
||||
--
|
||||
-- These tables are NOT deleted by this script. Favorite history is
|
||||
-- retained; if deletion is required by external policy, consult
|
||||
-- the DBA for a verified rollback procedure.
|
||||
77
sql/mysql/education/007-education-favorite.sql
Normal file
77
sql/mysql/education/007-education-favorite.sql
Normal file
@@ -0,0 +1,77 @@
|
||||
-- =============================================
|
||||
-- Education 模块 — 收藏夹 DDL
|
||||
-- Ticket #10: 学生收藏题目
|
||||
-- Migration: 007
|
||||
-- Prerequisites: 000-education-schema.sql (base tables)
|
||||
-- =============================================
|
||||
|
||||
-- =============================================
|
||||
-- Preconditions
|
||||
-- =============================================
|
||||
-- Operator is expected to verify:
|
||||
-- SELECT COUNT(*) FROM information_schema.tables
|
||||
-- WHERE table_schema = DATABASE()
|
||||
-- AND table_name = 'education_favorite';
|
||||
-- Result MUST be 0 before executing this migration.
|
||||
|
||||
-- =============================================
|
||||
-- 收藏表
|
||||
-- =============================================
|
||||
-- Purpose: Student favorites for questions with safe snapshots.
|
||||
-- Each (tenant, user, target_type, target_id) is a unique entry.
|
||||
-- Logical deletion: setting deleted=1 marks as unfavorited.
|
||||
-- Re-adding after deletion reactivates the row via ON DUPLICATE KEY UPDATE.
|
||||
--
|
||||
-- target_type values: 'QUESTION' (extensible enum)
|
||||
--
|
||||
-- Snapshot fields (stem, type, difficulty, options, content_version):
|
||||
-- populated at creation time from the visible question's safe fields.
|
||||
-- These snapshots preserve the question state as it appeared when favorited,
|
||||
-- and remain stable even if the source question later changes or becomes unavailable.
|
||||
--
|
||||
-- available flag:
|
||||
-- FALSE when the source question becomes hidden/unpublished after being
|
||||
-- favorited. Existing favorites with available=FALSE remain listable but
|
||||
-- display an "unavailable" indicator. New favorites cannot be created for
|
||||
-- unavailable resources.
|
||||
--
|
||||
-- Indexes:
|
||||
-- uk_tenant_user_target — per (tenant, user, target_type, target_id) uniqueness.
|
||||
-- INSERT ... ON DUPLICATE KEY UPDATE is the primary reactivation path.
|
||||
-- idx_tenant_user — covers listing queries filtered by current tenant+user.
|
||||
-- idx_tenant_user_target_type — covers target-type-filtered listing.
|
||||
CREATE TABLE `education_favorite` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`tenant_id` BIGINT NOT NULL COMMENT '租户编号',
|
||||
`user_id` BIGINT NOT NULL COMMENT '学生用户编号',
|
||||
`target_type` VARCHAR(32) NOT NULL COMMENT '目标类型:QUESTION',
|
||||
`target_id` VARCHAR(64) NOT NULL COMMENT '目标 ID(题目 ID)',
|
||||
-- safe snapshot fields
|
||||
`stem` TEXT DEFAULT NULL COMMENT '题干快照',
|
||||
`type` VARCHAR(32) DEFAULT NULL COMMENT '题型快照',
|
||||
`difficulty` VARCHAR(32) DEFAULT NULL COMMENT '难度快照',
|
||||
`options` JSON DEFAULT NULL COMMENT '选项快照 JSON(不含 isCorrect)',
|
||||
`content_version` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '题目内容版本',
|
||||
-- availability
|
||||
`available` BIT(1) NOT NULL DEFAULT b'1' COMMENT '源资源是否可用',
|
||||
-- audit
|
||||
`creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_tenant_user_target` (`tenant_id`, `user_id`, `target_type`, `target_id`),
|
||||
KEY `idx_tenant_user` (`tenant_id`, `user_id`),
|
||||
KEY `idx_tenant_user_target_type` (`tenant_id`, `user_id`, `target_type`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教育-收藏夹';
|
||||
|
||||
-- =============================================
|
||||
-- Post-migration verification queries
|
||||
-- =============================================
|
||||
-- Verify new table exists:
|
||||
-- SHOW CREATE TABLE education_favorite;
|
||||
-- Verify unique key is enforced:
|
||||
-- SHOW INDEX FROM education_favorite WHERE Key_name = 'uk_tenant_user_target';
|
||||
-- Verify no orphan data (should be 0 after fresh migration):
|
||||
-- SELECT COUNT(*) FROM education_favorite;
|
||||
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; });
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.iocoder.yudao.framework.common.biz.system.tenant;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.biz.system.tenant.dto.TenantRespDTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -23,4 +25,28 @@ public interface TenantCommonApi {
|
||||
*/
|
||||
void validateTenant(Long id);
|
||||
|
||||
/**
|
||||
* 根据租户编号获得租户信息
|
||||
*
|
||||
* @param id 租户编号
|
||||
* @return 租户信息,不存在时返回 null
|
||||
*/
|
||||
TenantRespDTO getTenant(Long id);
|
||||
|
||||
/**
|
||||
* 根据租户名获得租户信息
|
||||
*
|
||||
* @param name 租户名
|
||||
* @return 租户信息,不存在时返回 null
|
||||
*/
|
||||
TenantRespDTO getTenantByName(String name);
|
||||
|
||||
/**
|
||||
* 根据域名获得租户信息
|
||||
*
|
||||
* @param website 域名
|
||||
* @return 租户信息,不存在时返回 null
|
||||
*/
|
||||
TenantRespDTO getTenantByWebsite(String website);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package cn.iocoder.yudao.framework.common.biz.system.tenant.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户信息 Response DTO
|
||||
*
|
||||
* @author 恭学教育
|
||||
*/
|
||||
@Data
|
||||
public class TenantRespDTO implements Serializable {
|
||||
|
||||
/**
|
||||
* 租户编号
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 租户名
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 租户状态
|
||||
*
|
||||
* 0 - 开启,1 - 禁用
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 绑定域名列表
|
||||
*/
|
||||
private List<String> websites;
|
||||
|
||||
/**
|
||||
* 过期时间
|
||||
*/
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
}
|
||||
@@ -33,6 +33,7 @@ public class ServiceErrorCodeRange {
|
||||
// 模块 system 错误码区间 [1-002-000-000 ~ 1-003-000-000)
|
||||
// 模块 report 错误码区间 [1-003-000-000 ~ 1-004-000-000)
|
||||
// 模块 member 错误码区间 [1-004-000-000 ~ 1-005-000-000)
|
||||
// 模块 education 错误码区间 [1-005-000-000 ~ 1-006-000-000)
|
||||
// 模块 mp 错误码区间 [1-006-000-000 ~ 1-007-000-000)
|
||||
// 模块 pay 错误码区间 [1-007-000-000 ~ 1-008-000-000)
|
||||
// 模块 bpm 错误码区间 [1-009-000-000 ~ 1-010-000-000)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package cn.iocoder.yudao.framework.tenant.core.security;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.biz.infra.logger.ApiErrorLogCommonApi;
|
||||
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
|
||||
import cn.iocoder.yudao.framework.security.core.LoginUser;
|
||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||
import cn.iocoder.yudao.framework.tenant.config.TenantProperties;
|
||||
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
|
||||
import cn.iocoder.yudao.framework.tenant.core.service.TenantFrameworkService;
|
||||
import cn.iocoder.yudao.framework.web.config.WebProperties;
|
||||
import cn.iocoder.yudao.framework.web.core.handler.GlobalExceptionHandler;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import java.util.HashSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class TenantSecurityWebFilterTest {
|
||||
|
||||
private TenantSecurityWebFilter filter;
|
||||
private TenantFrameworkService tenantFrameworkService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
WebProperties webProperties = new WebProperties();
|
||||
TenantProperties tenantProperties = new TenantProperties();
|
||||
tenantProperties.setIgnoreUrls(new HashSet<>());
|
||||
tenantFrameworkService = mock(TenantFrameworkService.class);
|
||||
filter = new TenantSecurityWebFilter(webProperties, tenantProperties, new HashSet<>(),
|
||||
new GlobalExceptionHandler("test", mock(ApiErrorLogCommonApi.class)), tenantFrameworkService);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
TenantContextHolder.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTenantOnProtectedRequestIsRejected() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/app-api/education/context");
|
||||
MockHttpServletResponse response = doFilter(request);
|
||||
assertEquals(400, jsonCode(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticatedTenantMismatchIsRejected() throws Exception {
|
||||
setLoginUser(1L, 10L);
|
||||
TenantContextHolder.setTenantId(20L);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/app-api/education/context");
|
||||
MockHttpServletResponse response = doFilter(request);
|
||||
assertEquals(403, jsonCode(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticatedTenantFillsMissingRequestTenant() throws Exception {
|
||||
setLoginUser(1L, 10L);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/app-api/education/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals(10L, TenantContextHolder.getTenantId());
|
||||
verify(tenantFrameworkService).validTenant(10L);
|
||||
assertEquals(request, chain.getRequest());
|
||||
}
|
||||
|
||||
private MockHttpServletResponse doFilter(MockHttpServletRequest request) throws Exception {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
return response;
|
||||
}
|
||||
|
||||
private static int jsonCode(MockHttpServletResponse response) throws Exception {
|
||||
String content = response.getContentAsString();
|
||||
int start = content.indexOf("\"code\":") + 7;
|
||||
int end = content.indexOf(',', start);
|
||||
return Integer.parseInt(content.substring(start, end));
|
||||
}
|
||||
|
||||
private static void setLoginUser(Long userId, Long tenantId) {
|
||||
LoginUser user = new LoginUser();
|
||||
user.setId(userId);
|
||||
user.setTenantId(tenantId);
|
||||
user.setUserType(UserTypeEnum.MEMBER.getValue());
|
||||
SecurityFrameworkUtils.setLoginUser(user, new MockHttpServletRequest());
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,6 @@
|
||||
</dependency>
|
||||
|
||||
<!-- DB 相关 -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.oracle.database.jdbc</groupId>
|
||||
<artifactId>ojdbc8</artifactId>
|
||||
@@ -41,7 +37,6 @@
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
|
||||
@@ -42,7 +42,7 @@ public class DesensitizeTest {
|
||||
DesensitizeDemo d = JsonUtils.parseObject(JsonUtils.toJsonString(desensitizeDemo), DesensitizeDemo.class);
|
||||
// 断言
|
||||
assertNotNull(d);
|
||||
assertEquals("芋***", d.getNickname());
|
||||
assertEquals("恭***", d.getNickname());
|
||||
assertEquals("998800********31", d.getBankCard());
|
||||
assertEquals("粤A6***6", d.getCarLicense());
|
||||
assertEquals("0108*****22", d.getFixedPhone());
|
||||
|
||||
61
yudao-module-education/CONTEXT.md
Normal file
61
yudao-module-education/CONTEXT.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Education
|
||||
|
||||
The Education context owns the language for educational content, practice, assessment, and student learning state.
|
||||
|
||||
## Language
|
||||
|
||||
**Question Content**:
|
||||
The complete versioned educational prompt presented for answering, including its stem and any answer choices required by its question type.
|
||||
_Avoid_: Payload, raw question
|
||||
|
||||
**Option-backed Question**:
|
||||
A question whose answer must be selected from a finite, student-visible set of labeled options. The supported family is `choice`, `multi`, `multi_choice`, `judge`, and `image`.
|
||||
_Avoid_: Objective question when referring only to storage shape
|
||||
|
||||
**Optionless Question**:
|
||||
A question answered without selecting from a finite option list. The recognized family includes `fill`, `text`, `terms`, `short_answer`, `composition`, `discuss`, `translation`, `case_analysis`, `brief_analysis`, `calculation`, `analysis_design`, `combination`, and `solution`.
|
||||
_Avoid_: Subjective question when the distinction being made is only whether options are present
|
||||
|
||||
**Composite Question**:
|
||||
A container question, such as `reading`, whose answerable units are sub-questions rather than top-level options. It is not a valid standalone practice question until the sub-question model is supported by the target contract.
|
||||
_Avoid_: Reading question when other composite forms may use the same model
|
||||
|
||||
**Safe Question**:
|
||||
A student-visible projection of Question Content that contains only display fields and never contains an answer, explanation, analysis, scoring rule, correctness flag, or administrative metadata.
|
||||
_Avoid_: Sanitized DO, frontend question
|
||||
|
||||
**Question Option**:
|
||||
One distinct choice in an Option-backed Question, identified by a non-blank label and containing non-blank display content. Labels are unique within the question.
|
||||
_Avoid_: Answer, choice answer
|
||||
|
||||
**Question Snapshot**:
|
||||
The immutable, student-visible Question Content captured when a practice session is created so that later content edits do not change that session. It excludes answers and explanations; protected scoring data is not part of this projection even when stored beside it.
|
||||
_Avoid_: Question cache
|
||||
|
||||
**Protected Answer Key**:
|
||||
Server-only correctness and explanation data captured for stable scoring of a practice session. It is never included in a Safe Question, Question Snapshot JSON, or pre-submit response.
|
||||
_Avoid_: Question Snapshot, frontend answer
|
||||
|
||||
**Unavailable Question Content**:
|
||||
Question Content that cannot safely be displayed or restored because its type, required options, option structure, publication state, or snapshot encoding is invalid or unsupported.
|
||||
_Avoid_: Empty question, best-effort question
|
||||
|
||||
**Tenant Locator Claim**:
|
||||
An unauthenticated pre-login value used to request tenant selection: either a browser-context hostname claim or an explicit Public Tenant Handle. It is not proof of caller identity or tenant authorization.
|
||||
_Avoid_: Trusted identity, authenticated hostname, tenant ID
|
||||
|
||||
**Browser-context Evidence**:
|
||||
A hostname claim derived from `Origin`, falling back to `Referer`, and used to keep browser login-routing inputs consistent. Any HTTP client can forge it, so it is not an authentication boundary.
|
||||
_Avoid_: Trusted browser identity, verified origin
|
||||
|
||||
**Public Tenant Handle**:
|
||||
The exact, published pre-login handle used by a headless client to request one tenant. In the current target it is the System tenant's unique name under a constrained, case-sensitive, operationally immutable contract; it is not the source system's distinct Tenant Code.
|
||||
_Avoid_: Tenant Code, display-name search, tenantName query
|
||||
|
||||
**Student Principal**:
|
||||
An authenticated Member identity acting as a student. An administrator or generic authenticated account is not a Student Principal.
|
||||
_Avoid_: User, account, logged-in principal
|
||||
|
||||
**Public Tenant Resolution**:
|
||||
The unauthenticated pre-login mapping of a Tenant Locator Claim to minimal login-routing fields. A successful result discloses that an available tenant exists; failed unknown, disabled, and expired tenants remain indistinguishable.
|
||||
_Avoid_: Tenant authentication, tenant administration lookup, non-enumerating discovery
|
||||
484
yudao-module-education/README.md
Normal file
484
yudao-module-education/README.md
Normal file
@@ -0,0 +1,484 @@
|
||||
# yudao-module-education
|
||||
|
||||
教育业务模块,提供课程、练习、题库、考试等教育业务功能。
|
||||
|
||||
## 当前状态
|
||||
|
||||
此模块提供教育业务功能骨架、题库目录浏览 tracer bullet,以及题目预览与练习配置预览。
|
||||
|
||||
**已实现**:
|
||||
- 模块骨架与包结构
|
||||
- 能力探测端点 (`/education/capability`)
|
||||
- 租户识别端点 (`/education/tenant/resolve`) — 学生端登录前使用
|
||||
- 教育上下文端点 (`/education/context`) — 学生端已认证状态
|
||||
- 题库目录端点 (见下方 Catalog API) — 学生端已认证
|
||||
- 题目浏览与筛选端点 (见下方 Questions API) — 学生端已认证
|
||||
- 练习配置预览端点 (见下方 Practice API) — 学生端已认证
|
||||
- 答案保存端点 (见下方 Answer API) — 幂等保存,安全重试
|
||||
- 题目安全过滤(答案/解析绝不暴露到前端)
|
||||
- 独立的功能开关配置 + Scalar 数据源配置
|
||||
- 错误码常量(通用 + 租户 + Catalog/Scalar + 题目/练习)
|
||||
- 权限注解(`education:capability`);菜单种子尚未纳入正式 Flyway,管理员授权需在后续产品决策后交付
|
||||
|
||||
## 功能配置
|
||||
|
||||
在 `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`:停止题库数据源读取;已有会话、报告、错题和收藏仍保存在 PostgreSQL。
|
||||
- `practice-write-enabled=false`:拒绝新建练习、保存答案和交卷;会话恢复、报告与历史查询保持可用。
|
||||
- `pilot-tenant-ids`:非空时仅允许列表内租户使用题库和练习写入能力。
|
||||
- 应用回滚只回滚应用版本或开关;不得执行 `*-rollback.sql`。SQL 回滚脚本仅用于明确的数据销毁场景。
|
||||
|
||||
## API
|
||||
|
||||
### 管理后台 - 能力信息
|
||||
|
||||
```
|
||||
GET /admin-api/education/capability
|
||||
```
|
||||
|
||||
- 权限:`education:capability`
|
||||
- 响应示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"msg": "成功",
|
||||
"data": {
|
||||
"module": "education",
|
||||
"enabled": true,
|
||||
"version": "1.0.0",
|
||||
"capabilities": ["shell", "catalog", "questions", "practice-preview"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 用户 APP - 教育租户识别
|
||||
|
||||
```
|
||||
GET /app-api/education/tenant/resolve?hostname=school.example.com
|
||||
GET /app-api/education/tenant/resolve?tenantName=demo-school
|
||||
GET /app-api/education/tenant/resolve?hostname=school.example.com&tenantName=demo-school
|
||||
```
|
||||
|
||||
- 权限:无需认证(`@PermitAll`)
|
||||
- 说明:通过主机名或租户名解析租户,返回学生端登录引导所需的基础字段。
|
||||
hostname 和 tenantName 至少提供一个。解析规则:
|
||||
1. 如果同时提供两者,它们必须解析到同一个租户,否则拒绝请求
|
||||
2. hostname 经过标准化(保留端口并转为小写),先查 `EducationProperties.hostnameTenantMap` 配置映射,再按 `system_tenant.websites` 的精确 authority 值查询
|
||||
- 响应示例(成功):
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"msg": "成功",
|
||||
"data": {
|
||||
"tenantId": 1024,
|
||||
"tenantName": "demo-school",
|
||||
"displayName": "demo-school",
|
||||
"status": "ACTIVE",
|
||||
"loginMethods": ["PASSWORD", "SMS"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- 错误响应:
|
||||
|
||||
| 错误码 | 说明 |
|
||||
|--------|------|
|
||||
| 1_005_001_001 | 租户不存在 |
|
||||
| 1_005_001_002 | 租户已被禁用 |
|
||||
| 1_005_001_003 | 租户识别失败(hostname 格式不合法等) |
|
||||
| 1_005_001_004 | 当前租户不可用(过期等) |
|
||||
|
||||
### 用户 APP - 教育当前上下文
|
||||
|
||||
```
|
||||
GET /app-api/education/context
|
||||
```
|
||||
|
||||
- 权限:需要认证(登录态)
|
||||
- 说明:根据当前认证用户和租户上下文返回教育业务信息。不信任请求体中的 userId,一切从安全上下文和 TenantContext 派生。TenantSecurityWebFilter 前置完成租户校验,此处二次验证确保租户处于活跃状态。
|
||||
- 响应示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"msg": "成功",
|
||||
"data": {
|
||||
"userId": 1024,
|
||||
"tenantId": 2048,
|
||||
"tenantName": "demo-school",
|
||||
"displayName": "demo-school"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 错误码
|
||||
|
||||
| 错误码 | 说明 |
|
||||
|--------|------|
|
||||
| 1_005_001_000 | 教育模块未启用 |
|
||||
| 1_005_001_001 | 租户不存在 |
|
||||
| 1_005_001_002 | 租户已被禁用 |
|
||||
| 1_005_001_003 | 租户识别失败:{原因} |
|
||||
| 1_005_001_004 | 当前租户不可用,请联系管理员 |
|
||||
|
||||
## 构建与运行
|
||||
|
||||
### 单独编译测试
|
||||
|
||||
```bash
|
||||
# 编译 education 模块
|
||||
mvn compile -pl yudao-module-education -am
|
||||
|
||||
# 运行 education 模块单元测试
|
||||
mvn test -pl yudao-module-education -am
|
||||
```
|
||||
|
||||
### 整体编译(含 server)
|
||||
|
||||
```bash
|
||||
# 编译全量(member + education + system + infra + server)
|
||||
mvn compile -pl yudao-server -am
|
||||
|
||||
# 打包(跳过测试加速)
|
||||
mvn package -pl yudao-server -am -DskipTests
|
||||
```
|
||||
|
||||
### 启动验证
|
||||
|
||||
1. 确保 `yudao.education.enabled=true`
|
||||
2. 启动 `yudao-server`
|
||||
3. 访问 Swagger UI 查看 `education` 分组
|
||||
4. 调用 `GET /admin-api/education/capability`
|
||||
|
||||
## 数据库迁移
|
||||
|
||||
Education 运行时 Schema 仅通过模块内 PostgreSQL Flyway migration 交付:
|
||||
|
||||
```text
|
||||
yudao-module-education/src/main/resources/db/migration/education/
|
||||
```
|
||||
|
||||
- `V4010` 和 `V4020` 是不可变迁移历史,不得修改。
|
||||
- `V4030` 创建或接管 Practice 核心闭环表,并在存在旧答案/交卷幂等表时向统一 `education_idempotency` 回填数据。
|
||||
- 旧 `education_answer_idempotency`、`education_submit_idempotency` 在首次接管时保留,后续清理必须使用更高版本的独立向前 migration。
|
||||
- `sql/postgresql/education/` 是手工初始化/设计历史,`sql/mysql/education/` 是过时归档;两者都不是运行时交付入口。
|
||||
- 禁止使用 `flyway clean` 或 `*-rollback.sql` 回退共享环境。应用回滚后如有 Schema 兼容问题,通过更高版本向前修复。
|
||||
|
||||
首次接管已有 PostgreSQL 平台库时使用既定的 `4009` baseline。任何已存在 Education 表的环境都必须先核对实际表结构和 `flyway_schema_history`,不能仅凭表名视为兼容,也不能伪造 V4010/V4020 执行历史。
|
||||
|
||||
编译后确认 migration 已打包:
|
||||
|
||||
```bash
|
||||
mvn -pl yudao-module-education -am -DskipTests clean package
|
||||
find yudao-module-education/target/classes/db/migration/education -type f -print
|
||||
```
|
||||
|
||||
只有真实 PostgreSQL 上的 Flyway migrate、validate 和历史检查成功后,才能报告数据库迁移成功。
|
||||
|
||||
## 前端状态
|
||||
|
||||
**当前工作区未检出完整的前端源码。** `yudao-ui/yudao-ui-admin-vue3/` 仅包含部分 MES 相关文件(`src/api/mes/`、`src/views/mes/`),缺少 `package.json`、`router/`、`store/`、`config/` 等核心框架文件。
|
||||
|
||||
因此:
|
||||
- **管理后台教育菜单项**:当前仅保留 `education:capability` 权限契约,正式 Flyway 尚未写入菜单种子;前端无路由/页面组件可渲染,因此不声明已有可见教育菜单。
|
||||
- **Student Web/H5 应用外壳**:前端源码不存在,无法建立。
|
||||
|
||||
### Student 端前端集成契约
|
||||
|
||||
前端就位后必须实现以下流程(不能伪造静态页面):
|
||||
|
||||
1. **租户识别**(登录前)
|
||||
- URL: `GET /app-api/education/tenant/resolve`
|
||||
- 从浏览器 `window.location.host` 获取 authority(包含非默认端口),传入 `hostname` 参数
|
||||
- 备用:支持手动输入 `tenantName`
|
||||
- 根据返回的 `loginMethods` 决定展示哪种登录方式(PASSWORD/SMS)
|
||||
- 获得 `tenantId` 后,在后续请求中通过 `tenant-id` header 传递
|
||||
|
||||
2. **用户认证**(复用 Member 模块)
|
||||
- 密码登录: `POST /app-api/member/auth/login`
|
||||
- 短信登录: `POST /app-api/member/auth/sms-login`
|
||||
- 刷新令牌: `POST /app-api/member/auth/refresh-token`
|
||||
- 登出: `POST /app-api/member/auth/logout`
|
||||
- 所有请求携带 `tenant-id: {tenantId}` header
|
||||
|
||||
3. **获取上下文**(登录后)
|
||||
- URL: `GET /app-api/education/context`
|
||||
- 携带有效 Bearer Token + `tenant-id` header
|
||||
- 从响应获取 `userId`、`tenantId`、`tenantName` 用于页面展示
|
||||
|
||||
4. **跨租户防护**
|
||||
- 前端不应允许用户手动切换 `tenant-id` header
|
||||
- 后端通过 `TenantSecurityWebFilter` 拒绝认证用户的跨租户 header 操作
|
||||
|
||||
**阻塞项**:完整前端源码(含 router、store、package.json)是上述前端集成的必要前提。一旦前端源码就位,需:
|
||||
1. 在 Vue3 admin 的路由中添加 `/education` 路由项,绑定 Education 菜单组件
|
||||
2. 添加 `src/api/education/` API 封装层(调用上述教育端点)
|
||||
3. Student Web/H5 端如需要独立入口,需新建对应前端项目
|
||||
|
||||
### 用户 APP - 题库目录(Catalog)
|
||||
|
||||
所有端点需要学生登录态(Bearer Token)。`userId` 和 `tenantId` 由安全上下文派生,不接受客户端传参。
|
||||
Scalar 代理层自动注入 `x-tenant-id` header(来自 `TenantContextHolder`),前端不发起任何直达 Scalar 的请求。
|
||||
|
||||
#### 架构边界
|
||||
|
||||
```
|
||||
Browser → Controller(/education/catalog/*) → CatalogService → CatalogProvider → [Scalar]
|
||||
↑ 内部 DTO/VO ↑ Scalar DTO 仅此层
|
||||
```
|
||||
- **业务层**(Controller/Service):仅操作内部 Catalog VO(`CatalogRegionRespVO` 等)
|
||||
- **集成层**(Scalar DTO + ScalarCatalogProvider):封装 Scalar 协议差异,DTO 不泄露到上层
|
||||
|
||||
#### 端点列表
|
||||
|
||||
| 端点 | 说明 | 参数 |
|
||||
|------|------|------|
|
||||
| `GET /app-api/education/catalog/regions` | 查询可用地区 | 无 |
|
||||
| `GET /app-api/education/catalog/categories` | 查询题目分类 | `subjectId` (可选), `nodeId` (可选) |
|
||||
| `GET /app-api/education/catalog/subjects` | 查询科目目录 | `regionId`, `schoolId`, `majorId`, `moduleId`, `type` (均可选) |
|
||||
| `GET /app-api/education/catalog/module-nodes` | 查询模块导航节点 | `regionId`, `moduleId`, `parentId` (均可选) |
|
||||
| `GET /app-api/education/catalog/content-entries` | 查询内容入口 | `regionId`, `entryType`, `includeHidden` (均可选) |
|
||||
| `GET /app-api/education/catalog/content-nodes` | 查询内容导航节点 | `entryId` (必填), `parentId`, `mode`, `includeInactive`, `markerType` (可选) |
|
||||
| `GET /app-api/education/catalog/question-collections` | 查询可用题集 | `regionId`, `entryId`, `nodeId`, `collectionType`, `limit` (均可选) |
|
||||
|
||||
#### 响应格式
|
||||
|
||||
所有成功响应返回 `CommonResult<List<T>>`:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"msg": "成功",
|
||||
"data": [
|
||||
{"id": "uuid", "name": "全国", "order": 1, "active": true}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 错误响应
|
||||
|
||||
| HTTP 状态 | 错误码 | 说明 |
|
||||
|-----------|--------|------|
|
||||
| 401 | 1_016_000_002 | 未登录或会话过期 |
|
||||
| 400 | 自定义 | 请求参数不合法 |
|
||||
| 500 | 1_005_002_000 | 题库数据源未启用 |
|
||||
| 500 | 1_005_002_001 | 上游题库服务异常 |
|
||||
| 500 | 1_005_002_002 | 上游认证失败(配置问题) |
|
||||
| 403 | 1_005_002_003 | 无权限访问上游资源 |
|
||||
| 404 | 1_005_002_004 | 请求的题库资源不存在 |
|
||||
| 409 | 1_005_002_005 | 资源状态冲突 |
|
||||
| 429 | 1_005_002_006 | 请求过于频繁 |
|
||||
| 500 | 1_005_002_007 | 上游超时 |
|
||||
| 500 | 1_005_002_008 | 上游返回异常:{状态码} |
|
||||
| 500 | 1_005_002_009 | 不支持的题库数据源模式 |
|
||||
|
||||
- **上游错误不会被转换为空列表或成功响应** — 每个上游非 2xx 均映射为明确的 `ServiceException`
|
||||
- 日志记录脱敏后的端点名、tenant、上游 requestId、耗时和结果
|
||||
|
||||
#### 前端集成提示
|
||||
|
||||
前端就位后,学生端学习首页应:
|
||||
1. 获取上下文(`/education/context`)确认登录态
|
||||
2. 调用 `/education/catalog/regions` 获取地区筛选器
|
||||
3. 根据地区调用 `subjects` / `categories` 获取科目分类
|
||||
4. 调用 `content-entries` → `content-nodes` 构建目录树
|
||||
5. 叶子节点调用 `question-collections` 获取题集摘要
|
||||
|
||||
**当前阻塞**:完整前端源码不存在,后端目录接口已就绪可通过 Swagger/curl 验证。
|
||||
|
||||
### 用户 APP - 题目与练习预览(Questions & Practice)
|
||||
|
||||
所有端点需要学生登录态(Bearer Token)。`userId` 和 `tenantId` 由安全上下文派生,不接受客户端传参。
|
||||
返回的题目数据经过白名单过滤,绝不包含 `correctAnswer`、`answer`、`explanation`、`analysis` 或选项的 `isCorrect` 字段。
|
||||
|
||||
#### 架构边界
|
||||
|
||||
```
|
||||
Browser -> Controller(/education/questions/*) -> QuestionCatalogService -> QuestionCatalogProvider -> [Scalar]
|
||||
↑ SafeQuestionRespVO ↑ CatalogQuestionDTO
|
||||
```
|
||||
- **业务层**(Controller/Service):仅操作安全 VO(`SafeQuestionRespVO` 等),答案字段在 DTO→VO 转换时被剥离
|
||||
- **集成层**(Scalar DTO + ScalarCatalogProvider):封装 Scalar 协议差异,答案字段在此层被映射但绝不透传到上层
|
||||
|
||||
#### 端点列表
|
||||
|
||||
| 端点 | 说明 | 参数 |
|
||||
|------|------|------|
|
||||
| `GET /app-api/education/questions/page` | 分页查询安全题目 | `collectionId`, `nodeId`, `type`, `difficulty` (可选), `pageNo` (默认1), `pageSize` (默认20) |
|
||||
| `GET /app-api/education/questions/get` | 获取单个安全题目 | `id` (必填) |
|
||||
| `GET /app-api/education/questions/collection-questions` | 查询题集中的安全题目 | `collectionId` (必填), `type`, `difficulty` (可选), `pageNo`, `pageSize` |
|
||||
| `GET /app-api/education/practice-config/preview` | 预览练习配置(不创建会话) | `collectionId` (必填), `nodeId`, `type`, `difficulty` (可选), `questionCount` (默认10, 1-1000) |
|
||||
|
||||
#### 分页响应格式
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"msg": "成功",
|
||||
"data": {
|
||||
"list": [
|
||||
{
|
||||
"id": "q-001",
|
||||
"contentVersion": "v2",
|
||||
"stem": "1+1等于几?",
|
||||
"type": "choice",
|
||||
"difficulty": "easy",
|
||||
"options": [
|
||||
{"label": "A", "content": "2", "order": 1.0}
|
||||
]
|
||||
}
|
||||
],
|
||||
"total": 50
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 练习预览响应格式
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"msg": "成功",
|
||||
"data": {
|
||||
"eligibleCount": 50,
|
||||
"totalCount": 100,
|
||||
"availableTypes": ["choice", "fill"],
|
||||
"availableDifficulties": ["easy", "medium"],
|
||||
"minQuestions": 1,
|
||||
"maxQuestions": 50,
|
||||
"suggestedCount": 20,
|
||||
"normalizedCount": 10,
|
||||
"countWithinRange": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 错误响应
|
||||
|
||||
| HTTP 状态 | 错误码 | 说明 |
|
||||
|-----------|--------|------|
|
||||
| 401 | 1_016_000_002 | 未登录或会话过期 |
|
||||
| 404 | 1_005_003_001 | 题目不存在或不可见 |
|
||||
| 400 | 1_005_003_002 | 无效的练习配置 |
|
||||
| 400 | 1_005_003_003 | 符合条件的题目数量不足 |
|
||||
| 500 | 1_005_003_004 | 题库数据源返回不安全内容 |
|
||||
|
||||
#### 安全字段白名单
|
||||
|
||||
`SafeQuestionRespVO` 仅包含以下字段,前端可安全展示:
|
||||
- `id`, `contentVersion`, `stem`, `type`, `difficulty`
|
||||
- `options[]` 中仅包含 `label`, `content`, `order`
|
||||
|
||||
以下字段**绝不**出现在响应中:
|
||||
- `correctAnswer`, `answer`, `explanation`, `analysis`
|
||||
- 选项的 `isCorrect`
|
||||
- 任何管理元数据
|
||||
|
||||
#### 前端集成提示
|
||||
|
||||
前端就位后,学生端练习入口应:
|
||||
1. 浏览题库目录(Catalog API)选择题集
|
||||
2. 调用 `/education/questions/page` 或 `/education/questions/collection-questions` 预览题目概要
|
||||
3. 调用 `/education/practice-config/preview` 获取可用题量范围和建议配置
|
||||
4. 展示预览结果后,用户在可用范围内选择题量开始练习(Ticket #6 创建持久会话)
|
||||
|
||||
**当前阻塞**:完整前端源码不存在,后端接口已就绪可通过 Swagger/curl 验证。
|
||||
|
||||
### 更新后的错误码
|
||||
|
||||
| 错误码 | 说明 |
|
||||
|--------|------|
|
||||
| 1_005_001_000 | 教育模块未启用 |
|
||||
| 1_005_001_001 | 租户不存在 |
|
||||
| 1_005_001_002 | 租户已被禁用 |
|
||||
| 1_005_001_003 | 租户识别失败:{原因} |
|
||||
| 1_005_001_004 | 当前租户不可用 |
|
||||
| 1_005_002_000 | 题库数据源未启用 |
|
||||
| 1_005_002_001 | 上游题库服务异常 |
|
||||
| 1_005_002_002 | 上游认证失败 |
|
||||
| 1_005_002_003 | 无权限访问上游资源 |
|
||||
| 1_005_002_004 | 题库资源不存在 |
|
||||
| 1_005_002_005 | 资源状态冲突 |
|
||||
| 1_005_002_006 | 请求过于频繁 |
|
||||
| 1_005_002_007 | 上游超时 |
|
||||
| 1_005_002_008 | 上游返回异常:{状态码} |
|
||||
| 1_005_002_009 | 不支持的题库数据源模式 |
|
||||
| 1_005_002_010 | Scalar 数据源未配置 |
|
||||
| 1_005_002_011 | 上游题库返回数据格式异常 |
|
||||
| 1_005_002_012 | 上游题库服务不可达 |
|
||||
| 1_005_003_001 | 题目不存在或不可见 |
|
||||
| 1_005_003_002 | 无效的练习配置 |
|
||||
| 1_005_003_003 | 符合条件的题目数量不足 |
|
||||
| 1_005_003_004 | 题库数据源返回不安全内容 |
|
||||
|
||||
### 用户 APP - 答案保存(Answer)
|
||||
|
||||
需要学生登录态。`userId`/`tenantId` 由安全上下文派生。
|
||||
答案保存具有幂等性:同一 `idempotencyKey` + 相同载荷返回首次结果,相同 key + 不同载荷返回冲突。
|
||||
服务端乐观锁防止旧版本/旧序号覆盖更新答案。
|
||||
|
||||
```
|
||||
PUT /app-api/education/practice-session/answer
|
||||
```
|
||||
|
||||
**请求体:**
|
||||
|
||||
```json
|
||||
{"sessionId":1001,"questionSequence":3,"selectedAnswer":"A","idempotencyKey":"uuid","clientSequence":5,"expectedSessionVersion":1}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| sessionId | Long | 是 | 练习会话 ID |
|
||||
| questionSequence | Integer | 是 | 题目序号(1-based) |
|
||||
| selectedAnswer | String | 否 | 学生选择的答案,null 表示清除 |
|
||||
| idempotencyKey | String | 是 | 客户端幂等键(UUID) |
|
||||
| clientSequence | Integer | 是 | 客户端命令序号(单调递增) |
|
||||
| expectedSessionVersion | Integer | 是 | 客户端期望的会话版本号 |
|
||||
|
||||
**成功响应:** `{"sessionId":1001,"questionSequence":3,"selectedAnswer":"A","serverVersion":2,"acceptedSequence":5}`
|
||||
|
||||
**前端保存状态契约**(客户端根据 API 响应派生,后端不提供状态枚举):
|
||||
|
||||
| 状态 | 条件 | 说明 |
|
||||
|------|------|------|
|
||||
| SAVING | 请求发送中 | 显示保存中指示器 |
|
||||
| SAVED | code=0 | 更新本地版本号和序号 |
|
||||
| RETRYING | 网络超时/5xx | 相同 idempotencyKey 安全重试 |
|
||||
| FAILED | 1\_005\_003\_014/015/016 | 刷新页面获取最新状态后重试 |
|
||||
|
||||
刷新页面通过 `GET /practice-session/current` 恢复服务端最后确认的答案。
|
||||
|
||||
### 答案保存错误码
|
||||
|
||||
| 错误码 | 说明 |
|
||||
|--------|------|
|
||||
| 1\_005\_003\_006 | 练习会话不存在 |
|
||||
| 1\_005\_003\_007 | 无权访问该练习会话 |
|
||||
| 1\_005\_003\_008 | 练习会话已过期 |
|
||||
| 1\_005\_003\_009 | 练习会话已提交 |
|
||||
| 1\_005\_003\_010 | 练习会话已取消 |
|
||||
| 1\_005\_003\_014 | 幂等键相同但请求内容不一致 |
|
||||
| 1\_005\_003\_015 | 会话版本已更新,请刷新后重试 |
|
||||
| 1\_005\_003\_016 | 客户端命令序号已过期 |
|
||||
| 1\_005\_003\_017 | 无效的选项 |
|
||||
| 1\_005\_003\_019 | 题目不属于当前会话 |
|
||||
51
yudao-module-education/pom.xml
Normal file
51
yudao-module-education/pom.xml
Normal file
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>yudao-module-education</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>
|
||||
education 模块,我们放教育业务。
|
||||
例如说:课程、练习、题库、考试等等
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Web 与权限相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-module-system</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Test 测试相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.boot</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,83 @@
|
||||
package cn.iocoder.yudao.module.education.config;
|
||||
|
||||
import cn.iocoder.yudao.module.education.enums.CatalogProviderMode;
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 教育模块配置属性
|
||||
*
|
||||
* @author 恭学教育
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "yudao.education")
|
||||
@Validated
|
||||
@Data
|
||||
public class EducationProperties {
|
||||
|
||||
/**
|
||||
* 是否启用教育模块
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* 教育模块版本号
|
||||
*/
|
||||
private String version = "1.0.0";
|
||||
|
||||
/**
|
||||
* 题库目录数据源模式。
|
||||
* 默认 SCALAR_READ;JAVA_READ 使用本地 PostgreSQL 目录数据源。
|
||||
*/
|
||||
private CatalogProviderMode catalogMode = CatalogProviderMode.SCALAR_READ;
|
||||
|
||||
/**
|
||||
* 是否允许读取题库目录和题目。关闭后不影响已持久化的练习、报告、错题和收藏数据。
|
||||
*/
|
||||
private boolean catalogReadEnabled = true;
|
||||
|
||||
/**
|
||||
* 是否允许创建练习、保存答案和交卷。关闭后仍允许读取已有会话和历史报告。
|
||||
*/
|
||||
private boolean practiceWriteEnabled = true;
|
||||
|
||||
/**
|
||||
* Education Pilot 租户 ID 列表。为空表示不限制租户;配置后仅列表内租户可使用学生端能力。
|
||||
*/
|
||||
private List<Long> pilotTenantIds = List.of();
|
||||
|
||||
/**
|
||||
* 租户识别配置。
|
||||
*/
|
||||
private TenantResolution tenantResolution = new TenantResolution();
|
||||
|
||||
@Data
|
||||
public static class TenantResolution {
|
||||
|
||||
/**
|
||||
* 是否允许开发工作站和自动化测试使用本地主机名识别租户。
|
||||
*/
|
||||
private boolean localDevelopmentEnabled = false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地开发主机名到公开租户句柄的精确映射,仅在 local-development-enabled=true 时使用。
|
||||
* key = 标准化后的本地主机名(小写、无端口),value = 公开租户句柄。
|
||||
* 生产域名始终由 System 的 canonical website 查找负责。
|
||||
*/
|
||||
private Map<String, String> hostnameTenantMap = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 学生端登录方式由 Member 认证模块负责;该配置仅为旧配置绑定兼容,不参与公开租户识别响应。
|
||||
*
|
||||
* @deprecated 请在 Member 认证入口配置登录方式
|
||||
*/
|
||||
@Deprecated
|
||||
private List<String> loginMethods = List.of("PASSWORD", "SMS");
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package cn.iocoder.yudao.module.education.controller.admin;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.module.education.config.EducationProperties;
|
||||
import cn.iocoder.yudao.module.education.controller.admin.vo.EducationCapabilityRespVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
|
||||
|
||||
@Tag(name = "管理后台 - 教育模块")
|
||||
@RestController
|
||||
@RequestMapping("/education")
|
||||
@Validated
|
||||
@ConditionalOnProperty(prefix = "yudao.education", name = "enabled", havingValue = "true")
|
||||
public class EducationCapabilityController {
|
||||
|
||||
@Resource
|
||||
private EducationProperties educationProperties;
|
||||
|
||||
@GetMapping("/capability")
|
||||
@Operation(summary = "获得教育模块能力信息")
|
||||
@PreAuthorize("@ss.hasPermission('education:capability')")
|
||||
public CommonResult<EducationCapabilityRespVO> getCapability() {
|
||||
EducationCapabilityRespVO resp = EducationCapabilityRespVO.builder()
|
||||
.module("education")
|
||||
.enabled(educationProperties.isEnabled())
|
||||
.version(educationProperties.getVersion())
|
||||
.capabilities(List.of("shell", "catalog", "questions", "practice-preview",
|
||||
"answer-save", "session-submit", "practice-report"))
|
||||
.catalogReadEnabled(educationProperties.isCatalogReadEnabled())
|
||||
.practiceWriteEnabled(educationProperties.isPracticeWriteEnabled())
|
||||
.pilotTenantCount(educationProperties.getPilotTenantIds().size())
|
||||
.build();
|
||||
return success(resp);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cn.iocoder.yudao.module.education.controller.admin.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Schema(description = "管理后台 - 教育模块能力信息 Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class EducationCapabilityRespVO {
|
||||
|
||||
@Schema(description = "模块名称", example = "education")
|
||||
private String module;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private boolean enabled;
|
||||
|
||||
@Schema(description = "模块版本", example = "1.0.0")
|
||||
private String version;
|
||||
|
||||
@Schema(description = "支持的能力列表")
|
||||
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;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.biz.system.tenant.TenantCommonApi;
|
||||
import cn.iocoder.yudao.framework.common.biz.system.tenant.dto.TenantRespDTO;
|
||||
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
|
||||
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.tenant.core.context.TenantContextHolder;
|
||||
import cn.iocoder.yudao.module.education.controller.app.vo.EducationContextRespVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.UNAUTHORIZED;
|
||||
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
|
||||
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
|
||||
import static cn.iocoder.yudao.module.education.enums.ErrorCodeConstants.EDUCATION_TENANT_NOT_ACTIVE;
|
||||
|
||||
/**
|
||||
* 教育当前上下文 Controller — 学生端
|
||||
*
|
||||
* <p>根据当前认证用户和安全上下文返回教育业务所需的租户与用户信息。
|
||||
* 该端点需要认证,不信任请求体中的 userId。</p>
|
||||
*
|
||||
* @author 恭学教育
|
||||
*/
|
||||
@Tag(name = "用户 APP - 教育上下文")
|
||||
@RestController
|
||||
@RequestMapping("/education")
|
||||
@Validated
|
||||
@ConditionalOnProperty(prefix = "yudao.education", name = "enabled", havingValue = "true")
|
||||
public class EducationContextController {
|
||||
|
||||
@Resource
|
||||
private TenantCommonApi tenantCommonApi;
|
||||
|
||||
@GetMapping("/context")
|
||||
@Operation(summary = "获取当前教育上下文",
|
||||
description = "根据当前认证用户和租户上下文返回教育业务信息。需要登录态。")
|
||||
public CommonResult<EducationContextRespVO> getContext() {
|
||||
// 1. 从安全上下文获取完整主体,只接受 Member 学生主体
|
||||
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
|
||||
if (loginUser == null || !UserTypeEnum.MEMBER.getValue().equals(loginUser.getUserType())) {
|
||||
throw exception(UNAUTHORIZED);
|
||||
}
|
||||
Long userId = loginUser.getId();
|
||||
|
||||
// 2. 获取当前租户并验证状态(由 TenantSecurityWebFilter 前置完成,此处二次验证)
|
||||
Long tenantId = TenantContextHolder.getRequiredTenantId();
|
||||
tenantCommonApi.validateTenant(tenantId);
|
||||
|
||||
// 3. 获取租户信息用于展示
|
||||
TenantRespDTO tenant = tenantCommonApi.getTenant(tenantId);
|
||||
if (tenant == null) {
|
||||
throw exception(EDUCATION_TENANT_NOT_ACTIVE);
|
||||
}
|
||||
|
||||
// 构建响应
|
||||
EducationContextRespVO resp = EducationContextRespVO.builder()
|
||||
.userId(userId)
|
||||
.tenantId(tenantId)
|
||||
.tenantName(tenant.getName())
|
||||
.displayName(tenant.getName())
|
||||
.build();
|
||||
return success(resp);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog;
|
||||
|
||||
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.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.question.QuestionCatalogService;
|
||||
import cn.iocoder.yudao.module.education.controller.app.question.vo.SafeQuestionRespVO;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.UNAUTHORIZED;
|
||||
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
|
||||
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
|
||||
|
||||
/**
|
||||
* 题库目录 Controller — 学生端已认证接口。
|
||||
*
|
||||
* <p>所有端点需要学生登录态。userId/tenantId 由安全上下文派生,不接受请求参数。</p>
|
||||
*
|
||||
* @author 恭学教育
|
||||
*/
|
||||
@Tag(name = "用户 APP - 题库目录")
|
||||
@RestController
|
||||
@RequestMapping("/education/catalog")
|
||||
@Validated
|
||||
@ConditionalOnProperty(prefix = "yudao.education", name = "enabled", havingValue = "true")
|
||||
public class CatalogController {
|
||||
|
||||
@Resource
|
||||
private CatalogService catalogService;
|
||||
|
||||
@Resource
|
||||
private QuestionCatalogService questionCatalogService;
|
||||
|
||||
@Resource
|
||||
private EducationAccessService educationAccessService;
|
||||
|
||||
@GetMapping("/schools")
|
||||
@Operation(summary = "查询院校目录")
|
||||
public CommonResult<List<CatalogSchoolRespVO>> listSchools(
|
||||
@RequestParam(required = false) String regionId,
|
||||
@RequestParam(required = false) String schoolId) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listSchools(regionId, schoolId));
|
||||
}
|
||||
|
||||
@GetMapping("/majors")
|
||||
@Operation(summary = "查询专业目录")
|
||||
public CommonResult<List<CatalogMajorRespVO>> listMajors(
|
||||
@RequestParam(required = false) String regionId,
|
||||
@RequestParam(required = false) String schoolId,
|
||||
@RequestParam(required = false) String majorId,
|
||||
@RequestParam(required = false) String moduleId,
|
||||
@RequestParam(required = false) String type) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listMajors(regionId, schoolId, majorId, moduleId, type));
|
||||
}
|
||||
|
||||
@GetMapping("/regions")
|
||||
@Operation(summary = "查询可用地区列表")
|
||||
public CommonResult<List<CatalogRegionRespVO>> listRegions() {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listRegions());
|
||||
}
|
||||
|
||||
@GetMapping("/categories")
|
||||
@Operation(summary = "查询题目分类列表")
|
||||
public CommonResult<List<CatalogCategoryRespVO>> listCategories(
|
||||
@Parameter(description = "科目 ID") @RequestParam(required = false) String subjectId,
|
||||
@Parameter(description = "旧导航节点 ID") @RequestParam(required = false) String nodeId) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listCategories(subjectId, nodeId));
|
||||
}
|
||||
|
||||
@GetMapping("/subjects")
|
||||
@Operation(summary = "查询科目目录")
|
||||
public CommonResult<List<CatalogSubjectRespVO>> listSubjects(
|
||||
@Parameter(description = "地区 ID") @RequestParam(required = false) String regionId,
|
||||
@Parameter(description = "院校 ID") @RequestParam(required = false) String schoolId,
|
||||
@Parameter(description = "专业 ID") @RequestParam(required = false) String majorId,
|
||||
@Parameter(description = "模块 ID") @RequestParam(required = false) String moduleId,
|
||||
@Parameter(description = "科目类型") @RequestParam(required = false) String type) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listSubjects(regionId, schoolId, majorId, moduleId, type));
|
||||
}
|
||||
|
||||
@GetMapping("/module-nodes")
|
||||
@Operation(summary = "查询模块导航节点")
|
||||
public CommonResult<List<CatalogModuleNodeRespVO>> listModuleNodes(
|
||||
@Parameter(description = "地区 ID") @RequestParam(required = false) String regionId,
|
||||
@Parameter(description = "模块 ID") @RequestParam(required = false) String moduleId,
|
||||
@Parameter(description = "父节点 ID(传 root 表示根节点)") @RequestParam(required = false) String parentId) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listModuleNodes(regionId, moduleId, parentId));
|
||||
}
|
||||
|
||||
@GetMapping("/content-entries")
|
||||
@Operation(summary = "查询内容入口")
|
||||
public CommonResult<List<CatalogContentEntryRespVO>> listContentEntries(
|
||||
@Parameter(description = "地区 ID") @RequestParam(required = false) String regionId,
|
||||
@Parameter(description = "内容入口类型") @RequestParam(required = false) String entryType) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listContentEntries(regionId, entryType, false));
|
||||
}
|
||||
|
||||
@GetMapping("/content-nodes")
|
||||
@Operation(summary = "查询内容导航节点")
|
||||
public CommonResult<List<CatalogContentNodeRespVO>> listContentNodes(
|
||||
@Parameter(description = "内容入口 ID", required = true) @RequestParam String entryId,
|
||||
@Parameter(description = "父节点 ID(传 root 表示根节点)") @RequestParam(required = false) String parentId,
|
||||
@Parameter(description = "查询模式(children/flat)") @RequestParam(defaultValue = "children") String mode,
|
||||
@Parameter(description = "节点标记类型") @RequestParam(required = false) String markerType) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listContentNodes(entryId, parentId, mode, false, markerType));
|
||||
}
|
||||
|
||||
@GetMapping("/question-collections")
|
||||
@Operation(summary = "查询可用题集")
|
||||
public CommonResult<List<CatalogQuestionCollectionRespVO>> listQuestionCollections(
|
||||
@Parameter(description = "地区 ID") @RequestParam(required = false) String regionId,
|
||||
@Parameter(description = "内容入口 ID") @RequestParam(required = false) String entryId,
|
||||
@Parameter(description = "内容节点 ID") @RequestParam(required = false) String nodeId,
|
||||
@Parameter(description = "题集类型") @RequestParam(required = false) String collectionType,
|
||||
@Parameter(description = "返回条数上限") @RequestParam(required = false) Integer limit) {
|
||||
assertAuthenticated();
|
||||
return success(catalogService.listQuestionCollections(regionId, entryId, nodeId, collectionType, limit));
|
||||
}
|
||||
|
||||
@GetMapping("/question-collections/{id}/questions")
|
||||
@Operation(summary = "查询题集内题目", description = "仅返回学生可见字段,不包含答案、解析或正确性标记。")
|
||||
public CommonResult<PageResult<SafeQuestionRespVO>> listCollectionQuestions(
|
||||
@Parameter(description = "题集 ID", required = true) @PathVariable String id,
|
||||
@Parameter(description = "题型") @RequestParam(required = false) String type,
|
||||
@Parameter(description = "难度") @RequestParam(required = false) String difficulty,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNo,
|
||||
@Parameter(description = "每页条数") @RequestParam(defaultValue = "20") Integer pageSize) {
|
||||
assertAuthenticated();
|
||||
return success(questionCatalogService.listCollectionQuestions(id, type, difficulty, pageNo, pageSize));
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验当前学生的租户上下文和题库读取灰度开关。
|
||||
*/
|
||||
private void assertAuthenticated() {
|
||||
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
|
||||
if (loginUser == null || loginUser.getId() == null || loginUser.getTenantId() == null) {
|
||||
throw exception(UNAUTHORIZED);
|
||||
}
|
||||
educationAccessService.assertCatalogReadAllowed(loginUser.getTenantId());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "用户 APP - 题库目录 Category Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class CatalogCategoryRespVO {
|
||||
|
||||
@Schema(description = "分类 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440001")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "分类名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "高考")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "分类类型", example = "exam_type")
|
||||
private String type;
|
||||
|
||||
@Schema(description = "显示排序", example = "2")
|
||||
private Double order;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean active;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "用户 APP - 题库目录 ContentEntry Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class CatalogContentEntryRespVO {
|
||||
|
||||
@Schema(description = "入口 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440005")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "入口名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "高考数学题库")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "入口唯一键", requiredMode = Schema.RequiredMode.REQUIRED, example = "gaokao-math")
|
||||
private String entryKey;
|
||||
|
||||
@Schema(description = "入口类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "question_bank")
|
||||
private String entryType;
|
||||
|
||||
@Schema(description = "地区 ID", example = "550e8400-e29b-41d4-a716-446655440000")
|
||||
private String regionId;
|
||||
|
||||
@Schema(description = "显示排序", example = "1")
|
||||
private Double order;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean active;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "用户 APP - 题库目录 ContentNode Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class CatalogContentNodeRespVO {
|
||||
|
||||
@Schema(description = "节点 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440004")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "节点名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "1.1 集合")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "节点类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "node")
|
||||
private String nodeType;
|
||||
|
||||
@Schema(description = "内容入口 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440005")
|
||||
private String entryId;
|
||||
|
||||
@Schema(description = "父节点 ID", example = "root")
|
||||
private String parentId;
|
||||
|
||||
@Schema(description = "树深度", example = "1")
|
||||
private Double depth;
|
||||
|
||||
@Schema(description = "是否叶子节点", example = "false")
|
||||
private Boolean leaf;
|
||||
|
||||
@Schema(description = "是否可被选择", example = "true")
|
||||
private Boolean selectable;
|
||||
|
||||
@Schema(description = "显示排序", example = "1")
|
||||
private Double order;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean active;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "专业目录项")
|
||||
public class CatalogMajorRespVO {
|
||||
private String id;
|
||||
private String name;
|
||||
private String regionId;
|
||||
private String schoolId;
|
||||
private Double order;
|
||||
private Boolean active;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "用户 APP - 题库目录 ModuleNode Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class CatalogModuleNodeRespVO {
|
||||
|
||||
@Schema(description = "节点 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440003")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "节点名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "第一章")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "节点类型", example = "chapter")
|
||||
private String type;
|
||||
|
||||
@Schema(description = "地区 ID", example = "550e8400-e29b-41d4-a716-446655440000")
|
||||
private String regionId;
|
||||
|
||||
@Schema(description = "父节点 ID", example = "root")
|
||||
private String parentId;
|
||||
|
||||
@Schema(description = "显示排序", example = "4")
|
||||
private Double order;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean active;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "用户 APP - 题库目录 QuestionCollection Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class CatalogQuestionCollectionRespVO {
|
||||
|
||||
@Schema(description = "题集 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440006")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "题集名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "2024 高考数学真题")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "题集类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "exam_paper")
|
||||
private String collectionType;
|
||||
|
||||
@Schema(description = "题目数量", example = "24")
|
||||
private Long questionCount;
|
||||
|
||||
@Schema(description = "显示排序", example = "1")
|
||||
private Double order;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean active;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "用户 APP - 题库目录 Region Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class CatalogRegionRespVO {
|
||||
|
||||
@Schema(description = "地区 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "550e8400-e29b-41d4-a716-446655440000")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "地区名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "全国")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "显示排序", example = "1")
|
||||
private Double order;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean active;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cn.iocoder.yudao.module.education.controller.app.catalog.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "院校目录项")
|
||||
public class CatalogSchoolRespVO {
|
||||
private String id;
|
||||
private String name;
|
||||
private String regionId;
|
||||
private String moduleId;
|
||||
private Double order;
|
||||
private Boolean active;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user