Files
ruoyi-vue-pro/docs/education/migration/GOAL.md

425 lines
18 KiB
Markdown

# 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 is maintained in [`docs/education/migration/issues/README.md`](issues/README.md). Do not duplicate the live order here; completed bounded tickets remain historical dependencies, while current work follows the ticket index and its blockers.
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.