diff --git a/.agents/skills/modify-example/SKILL.md b/.agents/skills/modify-example/SKILL.md index 2b356dd..c98e2ea 100644 --- a/.agents/skills/modify-example/SKILL.md +++ b/.agents/skills/modify-example/SKILL.md @@ -68,7 +68,7 @@ PATH_MODE=relative ./agile-team-sdd/install.sh example-project --force ./overnight-runner/scripts/install.sh example-project --force ``` -确认 `example-project/.agent/skills/` 无残留 `{{...}}`、路径与新约定一致。 +确认 `example-project/.agents/skills/` 无残留 `{{...}}`、路径与新约定一致。 ### 6. 验证与自检 diff --git a/.agents/skills/modify-harness/SKILL.md b/.agents/skills/modify-harness/SKILL.md index b2dc3bb..89d4245 100644 --- a/.agents/skills/modify-harness/SKILL.md +++ b/.agents/skills/modify-harness/SKILL.md @@ -95,7 +95,7 @@ PATH_MODE=relative ./agile-team-sdd/install.sh example-project --force - 改完模板不 `--force` 重装 example,样例 skills 继续说旧路径 - 把 example 当安装器的输出随便 `--force` 冲掉手写 AGENTS,却不在 Plan 里声明 -- 只改 `example-project/.agent/skills/` 已安装副本,不改 `*-template`(下次安装会盖回去) +- 只改 `example-project/.agents/skills/` 已安装副本,不改 `*-template`(下次安装会盖回去) - 跨模块直接 import 代码 ## 相关 diff --git a/.agents/skills/work-in-example/SKILL.md b/.agents/skills/work-in-example/SKILL.md index 308ae17..0912354 100644 --- a/.agents/skills/work-in-example/SKILL.md +++ b/.agents/skills/work-in-example/SKILL.md @@ -25,7 +25,7 @@ description: 在 example-project 上下文中开发或改约定;结束时若 | 可以改 | 默认不要改(除非用户确认更新 harness) | |---|---| | `example-project/**` | `agile-team-sdd/`、`harness-installer/`、`tool-chain-installer/`、`overnight-runner/`(套件源) | -| 样例内 `.agent/skills/`(仅作本地验证时可改,须知重装会覆盖) | 根 `AGENTS.md` 里套件级约定(可提建议,不擅自改) | +| 样例内 `.agents/skills/`(仅作本地验证时可改,须知重装会覆盖) | 根 `AGENTS.md` 里套件级约定(可提建议,不擅自改) | 本仓库自身的 Plan 仍写在 `.agents/plan/`(若改动触及 harness 仓库规范)。 example 业务 Plan 写在 `example-project/docs/features/.../plan.md` 或 `_chores/`。 @@ -36,7 +36,7 @@ example 业务 Plan 写在 `example-project/docs/features/.../plan.md` 或 `_cho - 路径、命令、自测都以 `example-project/` 为根(如 `apps/backend`、`docs/features/`、`.overnight-runner/`) - 读 `example-project/AGENTS.md` 与相关 docs,按其规范执行 -- 需要安装态 skill 时,以 `example-project/.agent/skills/` 为准 +- 需要安装态 skill 时,以 `example-project/.agents/skills/` 为准 ### 2. 执行用户任务 @@ -54,7 +54,7 @@ example 业务 Plan 写在 `example-project/docs/features/.../plan.md` 或 `_cho | 文档骨架变了 | `docs/` 下新目录、facts/business、`_chores` 语义 | | 流程/检查清单变了 | `example-project/AGENTS.md` 与模板 `AGENTS.md.template` 明显不一致 | | 安装默认值会错 | 新默认路径、端口、测试命令,现有 `placeholders.md` / `install.sh` 对不上 | -| skill 行为以样例为准改过 | 只改了 `.agent/skills/` 已安装副本,模板仍是旧的 | +| skill 行为以样例为准改过 | 只改了 `.agents/skills/` 已安装副本,模板仍是旧的 | **未命中**:正常收尾(验证、文档同步、提交说明),不必提 harness。 diff --git a/.agents/verify.sh b/.agents/verify.sh index 1667187..da5f5e5 100755 --- a/.agents/verify.sh +++ b/.agents/verify.sh @@ -138,7 +138,7 @@ listed = {s['name'] for g in catalog.values() for s in g} tpl_root = pathlib.Path('agile-team-sdd/skills') templates = {p.name.replace('-template', '') for p in tpl_root.iterdir() if p.is_dir()} -installed_root = pathlib.Path('example-project/.agent/skills') +installed_root = pathlib.Path('example-project/.agents/skills') installed = {p.name for p in installed_root.iterdir() if p.is_dir()} if installed_root.exists() else set() if listed != templates: @@ -186,7 +186,7 @@ if [ -n "$PY" ]; then "$PY" - <<'PYEOF' import pathlib, re, sys -root = pathlib.Path('example-project/.agent/skills') +root = pathlib.Path('example-project/.agents/skills') bad = [] files = sorted(root.rglob('*.md')) if root.exists() else [] for f in files: diff --git a/.gitignore b/.gitignore index ac77af5..890eeb5 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,5 @@ venv/ .env .env.local **/src/main/resources/application.yml + +.tmp diff --git a/AGENTS.md b/AGENTS.md index e41c17e..0969f04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ team-harness-suite/ ``` 使用者 ──安装──▶ 目标项目 ──▶ opencode 加载 skill │ - ├─ agile-team-sdd → 目标项目/.agent/skills/ + ├─ agile-team-sdd → 目标项目/.agents/skills/ ├─ harness-installer → 目标项目/AGENTS.md + docs/ ├─ tool-chain-installer→ 目标项目/.mcp.json + opencode.jsonc └─ overnight-runner → 目标项目/.overnight-runner/ @@ -99,7 +99,7 @@ description: <一句话说明"做什么"+"什么时候用",第三人称,前 ``` agile-team-sdd/skills/dev-plan-template/SKILL.md (frontmatter: name: dev-plan-template) ↓ install.sh -<目标项目>/.agent/skills/dev-plan/SKILL.md (frontmatter: name: dev-plan) +<目标项目>/.agents/skills/dev-plan/SKILL.md (frontmatter: name: dev-plan) ``` **原因**:模板本身也要能被 opencode 扫描到,但不能和已安装的同名 skill 冲突。 @@ -222,7 +222,7 @@ agile-team-sdd/skills/dev-plan-template/SKILL.md (frontmatter: name: dev-pla | 先 `--dry-run` | 预览要做什么,再真跑 | | 原子写 | 配置文件用「临时文件 + rename」,避免读到写了一半的内容 | | 不写绝对路径到产物 | 安装到目标项目的文件里 **不能** 出现安装机的路径 | -| 不碰目标项目的业务代码 | 只写自己约定的文件(`.agent/skills/`、`docs/`、配置文件…) | +| 不碰目标项目的业务代码 | 只写自己约定的文件(`.agents/skills/`、`docs/`、配置文件…) | | 密钥不落盘 | 需要密钥的配置写 `{env:VAR}` 引用,真值由使用者注入 | ## 7. 错误处理 @@ -275,7 +275,7 @@ agile-team-sdd/skills/dev-plan-template/SKILL.md (frontmatter: name: dev-pla 模板 skills/-template/SKILL.md │ install.sh(渲染占位符 + 去 -template 后缀 + 删 TEMPLATE-ONLY 块) ▼ -已安装 <目标项目>/.agent/skills//SKILL.md +已安装 <目标项目>/.agents/skills//SKILL.md │ opencode 重启后加载 ▼ 可被触发 diff --git a/README.md b/README.md index cce5c5f..6164780 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ ba-grill-me → ba-write-spec → pm-estimate ```bash cd example-project cat AGENTS.md # 一份填满的工程规范范本 -ls .agent/skills/ # 已安装的 16 个 SDD skills +ls .agents/skills/ # 已安装的 16 个 SDD skills ``` ### 装到自己的新项目 @@ -110,7 +110,7 @@ ls .agent/skills/ # 已安装的 16 个 SDD skills # 1. 铺 harness:生成 AGENTS.md + docs/ 骨架 ./harness-installer/scripts/init-harness.sh ../my-project -# 2. 装 SDD skills(渲染占位符 → 写进 .agent/skills/) +# 2. 装 SDD skills(渲染占位符 → 写进 .agents/skills/) ./agile-team-sdd/install.sh ../my-project # 也可以只装某一组 / 某几个 diff --git a/agile-team-sdd/README.md b/agile-team-sdd/README.md index 0cc3608..0cffb5a 100644 --- a/agile-team-sdd/README.md +++ b/agile-team-sdd/README.md @@ -83,13 +83,13 @@ PATH_MODE=relative ./agile-team-sdd/install.sh ../my-project 安装后目标项目会得到: ``` -<目标项目>/.agent/skills//SKILL.md +<目标项目>/.agents/skills//SKILL.md ``` 以及 `opencode.jsonc` 中新增的: ```json -{ "skills": { "paths": [".agent/skills"] } } +{ "skills": { "paths": [".agents/skills"] } } ``` ## 目录约定 diff --git a/agile-team-sdd/SKILL.md b/agile-team-sdd/SKILL.md index 861e0ec..024d654 100644 --- a/agile-team-sdd/SKILL.md +++ b/agile-team-sdd/SKILL.md @@ -108,8 +108,8 @@ description: 安装 Agile Team SDD 技能套件(16 个 skill,覆盖 BA/开 脚本会做五件事: 1. 把 `skills/-template/**` 渲染(替换 `{{...}}` 占位符、删除 TEMPLATE-ONLY 标记块、把 `name` 去掉 `-template` 后缀) -2. 整个模板目录写入 `<目标项目>/.agent/skills//`(附属文件如 `baseline.md` 一并渲染) -3. 在目标项目的 `opencode.jsonc` 里注册 `skills.paths = [".agent/skills"]`(已存在则不覆盖) +2. 整个模板目录写入 `<目标项目>/.agents/skills//`(附属文件如 `baseline.md` 一并渲染) +3. 在目标项目的 `opencode.jsonc` 里注册 `skills.paths = [".agents/skills"]`(已存在则不覆盖) 4. 检查是否还有未替换的占位符并报警 5. 输出安装/跳过清单 @@ -117,8 +117,8 @@ description: 安装 Agile Team SDD 技能套件(16 个 skill,覆盖 BA/开 安装后确认: -- 目标项目 `.agent/skills/` 下每个 `SKILL.md` 里 **不再有** `{{...}}` -- 目标项目 `opencode.jsonc` 的 `skills.paths` 指向 `.agent/skills` +- 目标项目 `.agents/skills/` 下每个 `SKILL.md` 里 **不再有** `{{...}}` +- 目标项目 `opencode.jsonc` 的 `skills.paths` 指向 `.agents/skills` - 提示用户 **重启 opencode** 后 skill 才会生效 ## 路径约定 @@ -128,7 +128,7 @@ description: 安装 Agile Team SDD 技能套件(16 个 skill,覆盖 BA/开 ``` <项目根>/ ├── AGENTS.md ← {{AGENTS_FILE}} -├── .agent/skills/ ← {{SKILLS_DIR}} +├── .agents/skills/ ← {{SKILLS_DIR}} ├── .mcp.json ← {{MCP_CONFIG_FILE}} ├── apps/ │ ├── backend/ ← {{BACKEND_DIR}} diff --git a/agile-team-sdd/install.sh b/agile-team-sdd/install.sh index 5448dc6..12f3069 100755 --- a/agile-team-sdd/install.sh +++ b/agile-team-sdd/install.sh @@ -77,7 +77,7 @@ PROJECT_ROOT="$(cd "$TARGET" && pwd)" PROJECT_NAME="${PROJECT_NAME:-$(basename "$PROJECT_ROOT")}" # ── 目录与文件 ─────────────────────────────────────────────────────── -SKILLS_DIR="${SKILLS_DIR:-.agent/skills}" +SKILLS_DIR="${SKILLS_DIR:-.agents/skills}" BACKEND_DIR="${BACKEND_DIR:-apps/backend}" FRONTEND_DIR="${FRONTEND_DIR:-apps/frontend}" E2E_DIR="${E2E_DIR:-e2e}" diff --git a/agile-team-sdd/placeholders.md b/agile-team-sdd/placeholders.md index 972f4ae..14f2fc4 100644 --- a/agile-team-sdd/placeholders.md +++ b/agile-team-sdd/placeholders.md @@ -14,7 +14,7 @@ | `{{PROJECT_NAME}}` | 项目名 | 根目录目录名 | `PROJECT_NAME` | | `{{HARNESS_ROOT}}` | harness 套件源码根目录(`pm-retro` 回写用) | 安装脚本所在套件的根 | `HARNESS_ROOT` | | `{{AGENTS_FILE}}` | 工程规范文件 | `AGENTS.md` | `AGENTS_FILE` | -| `{{SKILLS_DIR}}` | skills 安装目录 | `.agent/skills` | `SKILLS_DIR` | +| `{{SKILLS_DIR}}` | skills 安装目录 | `.agents/skills` | `SKILLS_DIR` | | `{{MCP_CONFIG_FILE}}` | MCP 配置文件 | `.mcp.json` | `MCP_CONFIG_FILE` | | `{{BACKEND_DIR}}` | 后端模块目录 | `apps/backend` | `BACKEND_DIR` | | `{{FRONTEND_DIR}}` | 前端模块目录 | `apps/frontend` | `FRONTEND_DIR` | diff --git a/example-project/.agent/skills/ba-gen-facts/SKILL.md b/example-project/.agents/skills/ba-gen-facts/SKILL.md similarity index 100% rename from example-project/.agent/skills/ba-gen-facts/SKILL.md rename to example-project/.agents/skills/ba-gen-facts/SKILL.md diff --git a/example-project/.agent/skills/ba-grill-me/SKILL.md b/example-project/.agents/skills/ba-grill-me/SKILL.md similarity index 100% rename from example-project/.agent/skills/ba-grill-me/SKILL.md rename to example-project/.agents/skills/ba-grill-me/SKILL.md diff --git a/example-project/.agent/skills/ba-write-spec/SKILL.md b/example-project/.agents/skills/ba-write-spec/SKILL.md similarity index 100% rename from example-project/.agent/skills/ba-write-spec/SKILL.md rename to example-project/.agents/skills/ba-write-spec/SKILL.md diff --git a/example-project/.agent/skills/dev-build/SKILL.md b/example-project/.agents/skills/dev-build/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-build/SKILL.md rename to example-project/.agents/skills/dev-build/SKILL.md diff --git a/example-project/.agent/skills/dev-code-review/SKILL.md b/example-project/.agents/skills/dev-code-review/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-code-review/SKILL.md rename to example-project/.agents/skills/dev-code-review/SKILL.md diff --git a/example-project/.agent/skills/dev-create-mr/SKILL.md b/example-project/.agents/skills/dev-create-mr/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-create-mr/SKILL.md rename to example-project/.agents/skills/dev-create-mr/SKILL.md diff --git a/example-project/.agent/skills/dev-debug/SKILL.md b/example-project/.agents/skills/dev-debug/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-debug/SKILL.md rename to example-project/.agents/skills/dev-debug/SKILL.md diff --git a/example-project/.agent/skills/dev-plan/SKILL.md b/example-project/.agents/skills/dev-plan/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-plan/SKILL.md rename to example-project/.agents/skills/dev-plan/SKILL.md diff --git a/example-project/.agent/skills/dev-release-plan/SKILL.md b/example-project/.agents/skills/dev-release-plan/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-release-plan/SKILL.md rename to example-project/.agents/skills/dev-release-plan/SKILL.md diff --git a/example-project/.agent/skills/dev-self-test/SKILL.md b/example-project/.agents/skills/dev-self-test/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-self-test/SKILL.md rename to example-project/.agents/skills/dev-self-test/SKILL.md diff --git a/example-project/.agent/skills/dev-ui-review/SKILL.md b/example-project/.agents/skills/dev-ui-review/SKILL.md similarity index 100% rename from example-project/.agent/skills/dev-ui-review/SKILL.md rename to example-project/.agents/skills/dev-ui-review/SKILL.md diff --git a/example-project/.agent/skills/pm-estimate/SKILL.md b/example-project/.agents/skills/pm-estimate/SKILL.md similarity index 100% rename from example-project/.agent/skills/pm-estimate/SKILL.md rename to example-project/.agents/skills/pm-estimate/SKILL.md diff --git a/example-project/.agent/skills/pm-estimate/baseline.md b/example-project/.agents/skills/pm-estimate/baseline.md similarity index 98% rename from example-project/.agent/skills/pm-estimate/baseline.md rename to example-project/.agents/skills/pm-estimate/baseline.md index cdbc356..1254956 100644 --- a/example-project/.agent/skills/pm-estimate/baseline.md +++ b/example-project/.agents/skills/pm-estimate/baseline.md @@ -93,4 +93,4 @@ 4. 调整要 **改基线表 + 写明原因**,不要只改一次估算 基线表位置:`../agile-team-sdd/skills/pm-estimate-template/baseline.md` -(安装到项目后为 `.agent/skills/pm-estimate/baseline.md`) +(安装到项目后为 `.agents/skills/pm-estimate/baseline.md`) diff --git a/example-project/.agent/skills/pm-retro/SKILL.md b/example-project/.agents/skills/pm-retro/SKILL.md similarity index 98% rename from example-project/.agent/skills/pm-retro/SKILL.md rename to example-project/.agents/skills/pm-retro/SKILL.md index daab8b7..b48e5e2 100644 --- a/example-project/.agent/skills/pm-retro/SKILL.md +++ b/example-project/.agents/skills/pm-retro/SKILL.md @@ -66,7 +66,7 @@ git log --format="%h %s" --since="2 weeks ago" 改进项确认后: 1. 改 **套件源码**:`../agile-team-sdd/skills/-template/SKILL.md` 等 -2. 同步改 **已安装副本**:目标项目的 `.agent/skills//SKILL.md` +2. 同步改 **已安装副本**:目标项目的 `.agents/skills//SKILL.md` 3. 改动要 **重新下发** 才生效: ```bash diff --git a/example-project/.agent/skills/qa-run-e2e/SKILL.md b/example-project/.agents/skills/qa-run-e2e/SKILL.md similarity index 100% rename from example-project/.agent/skills/qa-run-e2e/SKILL.md rename to example-project/.agents/skills/qa-run-e2e/SKILL.md diff --git a/example-project/.agent/skills/qa-write-cases/SKILL.md b/example-project/.agents/skills/qa-write-cases/SKILL.md similarity index 100% rename from example-project/.agent/skills/qa-write-cases/SKILL.md rename to example-project/.agents/skills/qa-write-cases/SKILL.md diff --git a/example-project/.agent/skills/qa-write-manual-plan/SKILL.md b/example-project/.agents/skills/qa-write-manual-plan/SKILL.md similarity index 100% rename from example-project/.agent/skills/qa-write-manual-plan/SKILL.md rename to example-project/.agents/skills/qa-write-manual-plan/SKILL.md diff --git a/example-project/AGENTS.md b/example-project/AGENTS.md index 1635632..a06aef8 100644 --- a/example-project/AGENTS.md +++ b/example-project/AGENTS.md @@ -116,45 +116,22 @@ DTO 约定: ## 8. 领域设计:聚合与规则 -当前定义的聚合: +> **现状(空壳)**:旧示例聚合已清除。目标模型以 `docs/features/iteration1/` 为准,按 feature plan 重建后回写本节与 `docs/facts/domain-model.md`。 -- `User`:用户(email + password + role + status) -- `Consultant`:咨询师(name + title + specialties + status) -- `Appointment`:预约(user + consultant + date + time + status) -- `Branch`:网点(name + address + phone + status) +业务规则引擎(`domain/businessrule/`)— **框架保留、规则未注册**: -业务规则引擎(`domain/businessrule/`): +- `IBusinessRule` 接口:`getRuleName()` / `getDescription()` +- `BusinessRuleConfig` + `BusinessRuleProvider`;注册入口 `BusinessRuleRegistration`(当前为空) +- 规则 YAML 目录:`resources/business-rules/`(可按 feature 新增) -- `IBusinessRule` 接口:getCode() / getDescription() / getCategory() -- 规则以枚举实现 `IBusinessRule`(`AppointmentRule`、`AuthRule`) -- 规则配置 YAML 文件位于 `resources/business-rules/` -- `BusinessRuleController` 提供 GET 查询接口 +数据字典(`domain/datadictionary/`)— **框架保留、类型未注册**: -数据字典(`domain/datadictionary/`): - -- `Description` 接口:枚举实现,提供 getCode() / getDescription() -- 5 个注册字典类型:USER_ROLE / USER_STATUS / APPOINTMENT_STATUS / CONSULTANT_STATUS / BRANCH_STATUS -- `DemoDataDictionaryType` 完成注册 -- `DataDictionaryController` 提供 GET 查询接口 +- `Description` / `DataDictionaryType` / `DataDictionaryUtil` +- 实现 feature 时新增枚举并回写 `docs/facts/tech-topic/data-dict.md` ## 9. 预约状态机 -``` - ┌──────────┐ - ┌────►│ CANCELLED │◄────┐ - │ └──────────┘ │ - ┌─────────┐ │ ┌──────────┐ │ - │ PENDING │─────┼────►│CONFIRMED │────►│ COMPLETED - └─────────┘ │ └──────────┘ │ - │ │ - └──────────────────────┘ -``` - -- PENDING:初始状态 -- CONFIRMED:管理员确认 -- COMPLETED:完成(终态) -- CANCELLED:从任意非终态取消 -- 状态变更由 domain 层 `Appointment.canCancel()` 等守卫方法控制 +> 旧示例状态机已清除。以 `docs/features/iteration1/BKG-booking`(及相关)spec §9 为准,实现后回写 `docs/facts/tech-topic/state-machine.md`。 ## 10. 测试规范 diff --git a/example-project/README.md b/example-project/README.md index 5abbd4a..dae4210 100644 --- a/example-project/README.md +++ b/example-project/README.md @@ -1,6 +1,7 @@ # 咨询预约平台 / Consultation Booking Platform -基于 DDD 四层架构的全栈咨询预约单体应用,支持用户注册登录、咨询师浏览、预约管理及后台管理。 +全栈工程骨架(Java 17 / Spring Boot 3.2 / Vue 3 + TypeScript)。 +**业务实现已清空**;目标需求见 [`docs/features/iteration1/`](docs/features/iteration1/)。 ## 技术栈 @@ -9,104 +10,56 @@ | 前端 | Vue 3 + TypeScript + Vite + Pinia + Vue Router 4 | | 后端 | Java 17 + Spring Boot 3.2 + Spring Security + MyBatis-Plus 3.5 | | 数据库 | MySQL 8.0 + Flyway 迁移 | -| 认证 | JWT(HMAC-SHA256,jjwt 0.12) | -| 测试 | JUnit 5 + RestAssured + MariaDB4j / Playwright | +| 认证 | JWT(HMAC-SHA256)骨架 | +| 测试 | JUnit 5 + RestAssured / Playwright | -## 项目结构 +## 当前状态 -``` -├── apps/ -│ ├── backend/ # Spring Boot 后端 -│ └── frontend/ # Vue 3 前端 -├── e2e/ # Playwright E2E 测试 -├── docs/ -│ ├── features/ # 需求规格 -│ ├── plans/ # 技术方案 -│ ├── facts/ # 事实文档 -│ │ ├── business/ # 业务事实 -│ │ └── tech-topic/ # 技术专题 -│ ├── standards/ # 代码规范 -│ └── test-cases/ # 测试用例文本基线 -├── .overnight-runner/ # 无人值守 runner(代码 + 配置 + 队列) -└── AGENTS.md # AI Agent 工程规范 -``` - -## 环境要求 - -- Java 17+ -- Node.js 18+ / npm 9+ -- MySQL 8.0(或使用 MariaDB4j 自动启动本地实例) +- 后端:`GET /api/v1/health` + JWT / 异常处理 / 规则与字典框架空壳 +- 前端:占位首页 +- 需求与原型:`docs/features/iteration1/`(含独立 Vite 原型,端口 5174) +- 规范:`AGENTS.md`、`docs/standards/` ## 快速开始 -### 1. 配置后端 +### 后端 ```bash cd apps/backend cp src/main/resources/application.yml.example src/main/resources/application.yml -# 编辑 application.yml,填入 MySQL 密码和 JWT 密钥 -``` - -### 2. 启动后端 - -```bash -cd apps/backend +# 填入 MySQL 密码与 JWT 密钥 mvn spring-boot:run -# 后端启动于 http://localhost:8080 +# http://localhost:8080/api/v1/health ``` -### 3. 启动前端 +### 前端 ```bash cd apps/frontend npm install npm run dev -# 前端启动于 http://localhost:5173,/api 请求自动代理到后端 +# http://localhost:5173 +``` + +### iteration1 原型(需求演示,非业务前端) + +```bash +cd docs/features/iteration1/prototypes +npm install && npm run dev +# http://127.0.0.1:5174/ ``` ## 测试 -用例分两层:**开发自测**(对开发负责)与 **QA 测试**(对需求负责,合并闸门)。详见 [`docs/standards/test.md`](docs/standards/test.md)。 - -### 开发自测 - ```bash -cd apps/backend -mvn test -# 使用 MariaDB4j 自动启动临时 MySQL,无需手动建库 - -cd e2e -npm run test:dev -# 只跑开发自测的 E2E 用例(视觉冒烟等),不阻塞合并 +cd apps/backend && mvn test +cd e2e && npm run test:dev # 开发壳冒烟 +cd e2e && npm run test:qa # QA 闸门(用例待按 iteration1 重建) ``` -### QA 测试(合并闸门) - -```bash -cd e2e -npm run test:qa -# QA 验收用例集,与 docs/test-cases/e2e-cases/test-cases.md 的 TC-xxx 一一对应 - -# 一键启动前后端 + 执行全部 E2E -bash e2e-run.sh -``` - -## 架构概览 - -``` -Client → Vue 前端 (:5173) → /api 代理 → Spring Boot 后端 (:8080) → MySQL -``` - -- **adapter**:协议转换与参数校验,不含业务逻辑 -- **application**:用例编排,组合 domain 行为,管理事务边界 -- **domain**:领域模型与业务不变量,不依赖任何基础设施 -- **infrastructure**:持久化实现、安全配置、异常处理 - ## 文档 -详见 [`docs/`](docs/) 目录: - -- **需求与方案**:`docs/features/` — JIRA 风格 feature 文件夹(`spec.md` + `plan*.md`;横切见 `_chores/`) -- **事实文档**:`docs/facts/` — API 定义、数据库设计、领域模型、技术主题 -- **代码规范**:`docs/standards/` — 架构、命名、安全、分层等规范及代码模板 -- **测试用例**:`docs/test-cases/{e2e,manual,smoking,dev-self}-cases/` +- **需求**:`docs/features/iteration1/` +- **事实**:`docs/facts/`(当前为空壳 as-built) +- **规范**:`docs/standards/` +- **清理方案**:`docs/features/_chores/plan-20261117-purge-demo-impl-for-iteration1.md` diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AdminController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AdminController.java deleted file mode 100644 index cf4a541..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AdminController.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.assembler.AppointmentAssembler; -import com.consultation.application.assembler.BranchAssembler; -import com.consultation.application.assembler.ConsultantAssembler; -import com.consultation.application.assembler.UserAssembler; -import com.consultation.application.service.AdminService; -import com.consultation.application.service.AppointmentService; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/api/v1/admin") -@RequiredArgsConstructor -@PreAuthorize("hasRole('ADMIN')") -public class AdminController { - - private final AdminService adminService; - private final AppointmentService appointmentService; - private final ConsultantAssembler consultantAssembler; - private final UserAssembler userAssembler; - private final BranchAssembler branchAssembler; - private final AppointmentAssembler appointmentAssembler; - - - @GetMapping("/dashboard") - public Map dashboard() { return adminService.dashboard(); } - - @GetMapping("/users") - public List users() { return adminService.allUsers(); } - - @PutMapping("/users/{id}/toggle-status") - public ResponseEntity toggleUserStatus(@PathVariable String id) { adminService.toggleUserStatus(id); return ResponseEntity.ok().build(); } - - @GetMapping("/consultants") - public ResponseEntity> consultants() { - return ResponseEntity.ok(adminService.allConsultants().stream().map(consultantAssembler::toResponse).toList()); - } - - @GetMapping("/appointments") - public List appointments() { - return appointmentService.getAllAppointments(); - } - - @GetMapping("/branches") - public List branches() { - return adminService.allBranches(); - } - - @PostMapping("/branches") - public BranchAssembler.BranchResponse createBranch(@RequestBody Map body) { - return adminService.createBranch(body.get("name"), body.get("address"), body.get("phone")); - } - - @PutMapping("/branches/{id}") - public ResponseEntity updateBranch(@PathVariable String id, @RequestBody Map body) { - adminService.updateBranch(id, body.get("name"), body.get("address"), body.get("phone")); return ResponseEntity.ok().build(); - } - - @DeleteMapping("/branches/{id}") - public ResponseEntity deleteBranch(@PathVariable String id) { adminService.deleteBranch(id); return ResponseEntity.ok().build(); } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AppointmentController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AppointmentController.java deleted file mode 100644 index 62a1354..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AppointmentController.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.service.AppointmentService; -import com.consultation.infrastructure.security.SecurityUtils; -import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -@RestController -@RequestMapping("/api/v1/appointments") -@RequiredArgsConstructor -public class AppointmentController { - - private final AppointmentService appointmentService; - - @GetMapping - public ResponseEntity list() { - return ResponseEntity.ok(appointmentService.getMyAppointments(SecurityUtils.currentUserId())); - } - - @GetMapping("/{id}") - public ResponseEntity get(@PathVariable String id) { return ResponseEntity.ok(appointmentService.getById(id)); } - - @PostMapping - public ResponseEntity create(@Valid @RequestBody CreateRequest r) { - return ResponseEntity.ok(appointmentService.create(SecurityUtils.currentUserId(), - r.consultantId, r.branchId, r.date, r.startTime, r.endTime, r.note)); - } - - @PutMapping("/{id}/cancel") - public ResponseEntity cancel(@PathVariable String id, @RequestBody Map body) { - appointmentService.cancel(id, SecurityUtils.currentUserId(), body.getOrDefault("reason", "用户取消")); - return ResponseEntity.ok().build(); - } - - @Data - public static class CreateRequest { - @NotBlank String consultantId; - String branchId; - @NotBlank String date; - @NotBlank String startTime; - @NotBlank String endTime; - String note; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AuthController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AuthController.java deleted file mode 100644 index b9a49d2..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/AuthController.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.service.AuthService; -import jakarta.validation.Valid; -import jakarta.validation.constraints.Email; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.Size; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@RequestMapping("/api/v1/auth") -@RequiredArgsConstructor -public class AuthController { - - private final AuthService authService; - - @PostMapping("/register") - public ResponseEntity register(@Valid @RequestBody RegisterRequest r) { - return ResponseEntity.ok(authService.register(r.email, r.password, r.name, r.phone)); - } - - @PostMapping("/login") - public ResponseEntity login(@Valid @RequestBody LoginRequest r) { - return ResponseEntity.ok(authService.login(r.email, r.password)); - } - - @Data - public static class RegisterRequest { - @NotBlank @Email String email; - @NotBlank @Size(min = 8) String password; - @NotBlank String name; - String phone; - } - - @Data - public static class LoginRequest { - @NotBlank @Email String email; - @NotBlank String password; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/BusinessRuleController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/BusinessRuleController.java deleted file mode 100644 index b994d59..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/BusinessRuleController.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.service.BusinessRuleAppService; -import lombok.RequiredArgsConstructor; -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 java.util.Map; - -@RestController -@RequestMapping("/api/v1/business-rules") -@RequiredArgsConstructor -public class BusinessRuleController { - - private final BusinessRuleAppService service; - - @GetMapping - public List> list() { - return service.getAllRules(); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/ConsultantController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/ConsultantController.java deleted file mode 100644 index d707c7b..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/ConsultantController.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.service.ConsultantService; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/api/v1/consultants") -@RequiredArgsConstructor -public class ConsultantController { - - private final ConsultantService consultantService; - - @GetMapping - public ResponseEntity list() { return ResponseEntity.ok(consultantService.findAllActive()); } - - @GetMapping("/{id}") - public ResponseEntity get(@PathVariable String id) { return ResponseEntity.ok(consultantService.getById(id)); } - - @GetMapping("/{id}/slots") - public ResponseEntity>> slots(@PathVariable String id, @RequestParam String date) { - return ResponseEntity.ok(consultantService.getAvailableSlots(id, date)); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/DataDictionaryController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/DataDictionaryController.java deleted file mode 100644 index 44c0557..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/DataDictionaryController.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.service.DataDictionaryAppService; -import com.consultation.domain.datadictionary.DataDictionary; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -@RequestMapping("/api/v1/data-dictionaries") -@RequiredArgsConstructor -public class DataDictionaryController { - - private final DataDictionaryAppService service; - - @GetMapping - public List list() { - return service.getAll(); - } - - @GetMapping("/{type}") - public DataDictionary getByType(@PathVariable String type) { - return service.getByType(type); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/HealthController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/HealthController.java new file mode 100644 index 0000000..a9e1f36 --- /dev/null +++ b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/HealthController.java @@ -0,0 +1,17 @@ +package com.consultation.adapter.rest; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +@RequestMapping("/api/v1/health") +public class HealthController { + + @GetMapping + public Map health() { + return Map.of("status", "UP"); + } +} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/HomeController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/HomeController.java deleted file mode 100644 index 62aff90..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/HomeController.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.consultation.adapter.rest; - -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Map; - -@RestController -@RequestMapping("/api/v1/home") -public class HomeController { - - @GetMapping("/info") - public ResponseEntity> info() { - return ResponseEntity.ok(Map.of( - "title", "专业咨询服务", - "description", "我们提供专业的在线咨询服务,预约方便快捷。", - "consultants", java.util.List.of() - )); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/UserController.java b/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/UserController.java deleted file mode 100644 index 3db8d55..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/adapter/rest/UserController.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.application.service.UserService; -import com.consultation.infrastructure.security.SecurityUtils; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -@RestController -@RequestMapping("/api/v1/users") -@RequiredArgsConstructor -public class UserController { - - private final UserService userService; - - @GetMapping("/me") - public ResponseEntity profile() { return ResponseEntity.ok(userService.getProfile(SecurityUtils.currentUserId())); } - - @PutMapping("/me") - public ResponseEntity update(@RequestBody Map body) { - return ResponseEntity.ok(userService.updateProfile(SecurityUtils.currentUserId(), body.get("name"), body.get("phone"))); - } - - @PutMapping("/me/password") - public ResponseEntity changePw(@RequestBody Map body) { - userService.changePassword(SecurityUtils.currentUserId(), body.get("oldPassword"), body.get("newPassword")); - return ResponseEntity.ok().build(); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/AppointmentAssembler.java b/example-project/apps/backend/src/main/java/com/consultation/application/assembler/AppointmentAssembler.java deleted file mode 100644 index 1949972..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/AppointmentAssembler.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.consultation.application.assembler; - -import com.consultation.domain.aggregate.Appointment; -import lombok.Builder; -import lombok.Data; -import org.springframework.stereotype.Component; - -@Component -public class AppointmentAssembler { - public AppointmentResponse toResponse(Appointment a) { - if (a == null) return null; - return AppointmentResponse.builder().id(a.getId()).userId(a.getUserId()).consultantId(a.getConsultantId()) - .branchId(a.getBranchId()).appointmentDate(a.getAppointmentDate().toString()) - .startTime(a.getStartTime()).endTime(a.getEndTime()).durationMinutes(a.getDurationMinutes()) - .status(a.getStatus().name()).note(a.getNote()).cancelReason(a.getCancelReason()).build(); - } - - @Data @Builder - public static class AppointmentResponse { - String id; String userId; String consultantId; String branchId; - String appointmentDate; String startTime; String endTime; - int durationMinutes; String status; String note; String cancelReason; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/BranchAssembler.java b/example-project/apps/backend/src/main/java/com/consultation/application/assembler/BranchAssembler.java deleted file mode 100644 index c6cfef3..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/BranchAssembler.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.consultation.application.assembler; - -import com.consultation.domain.aggregate.Branch; -import lombok.Builder; -import lombok.Data; -import org.springframework.stereotype.Component; - -@Component -public class BranchAssembler { - public BranchResponse toResponse(Branch b) { - if (b == null) return null; - return BranchResponse.builder().id(b.getId()).name(b.getName()).address(b.getAddress()) - .phone(b.getPhone()).status(b.getStatus().name()).build(); - } - - @Data @Builder - public static class BranchResponse { String id; String name; String address; String phone; String status; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/ConsultantAssembler.java b/example-project/apps/backend/src/main/java/com/consultation/application/assembler/ConsultantAssembler.java deleted file mode 100644 index 2314612..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/ConsultantAssembler.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.consultation.application.assembler; - -import com.consultation.domain.aggregate.Consultant; -import lombok.Builder; -import lombok.Data; -import org.springframework.stereotype.Component; - -@Component -public class ConsultantAssembler { - public ConsultantResponse toResponse(Consultant c) { - if (c == null) return null; - return ConsultantResponse.builder().id(c.getId()).name(c.getName()).title(c.getTitle()).bio(c.getBio()) - .specialties(c.getSpecialties()).avatar(c.getAvatar()).branchId(c.getBranchId()) - .status(c.getStatus().name()).sortOrder(c.getSortOrder()).build(); - } - - @Data @Builder - public static class ConsultantResponse { - String id; String name; String title; String bio; String specialties; - String avatar; String branchId; String status; int sortOrder; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/UserAssembler.java b/example-project/apps/backend/src/main/java/com/consultation/application/assembler/UserAssembler.java deleted file mode 100644 index 2a8b4a6..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/assembler/UserAssembler.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.consultation.application.assembler; - -import com.consultation.domain.aggregate.User; -import lombok.Builder; -import lombok.Data; -import org.springframework.stereotype.Component; - -@Component -public class UserAssembler { - public UserResponse toResponse(User u) { - if (u == null) return null; - return UserResponse.builder().id(u.getId()).email(u.getEmail()).name(u.getName()) - .phone(u.getPhone()).role(u.getRole().name()).status(u.getStatus().name()).build(); - } - public AuthResponse toAuth(User u, String token) { - return AuthResponse.builder().token(token).user(toResponse(u)).build(); - } - - @Data @Builder - public static class UserResponse { String id; String email; String name; String phone; String role; String status; } - @Data @Builder - public static class AuthResponse { String token; UserResponse user; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/AdminService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/AdminService.java deleted file mode 100644 index 399f156..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/AdminService.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.application.assembler.BranchAssembler; -import com.consultation.application.assembler.UserAssembler; -import com.consultation.domain.aggregate.Branch; -import com.consultation.domain.aggregate.Consultant; -import com.consultation.domain.aggregate.User; -import com.consultation.domain.repository.AppointmentRepository; -import com.consultation.domain.repository.BranchRepository; -import com.consultation.domain.repository.ConsultantRepository; -import com.consultation.domain.repository.UserRepository; -import com.consultation.domain.vo.UserStatus; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.*; - -@Service -@RequiredArgsConstructor -public class AdminService { - - private final UserRepository userRepo; - private final BranchRepository branchRepo; - private final ConsultantRepository consultantRepo; - private final AppointmentRepository appointmentRepo; - private final BranchAssembler branchAssembler; - private final UserAssembler userAssembler; - - public Map dashboard() { - return Map.of("totalUsers", userRepo.findAll().size(), "totalConsultants", consultantRepo.count(), - "totalAppointments", appointmentRepo.count(), "pendingAppointments", appointmentRepo.countByStatus("PENDING"), - "totalBranches", branchRepo.count()); - } - - public List allUsers() { return userRepo.findAll().stream().map(userAssembler::toResponse).toList(); } - public List allConsultants() { return consultantRepo.findAll(); } - public List allBranches() { return branchRepo.findAll().stream().map(branchAssembler::toResponse).toList(); } - - @Transactional - public void toggleUserStatus(String id) { - User u = userRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("用户不存在")); - User upd = User.builder().id(u.getId()).email(u.getEmail()).password(u.getPassword()) - .name(u.getName()).phone(u.getPhone()).role(u.getRole()) - .status(u.getStatus() == UserStatus.ACTIVE ? UserStatus.DISABLED : UserStatus.ACTIVE).build(); - userRepo.update(upd); - } - - @Transactional - public BranchAssembler.BranchResponse createBranch(String name, String address, String phone) { - return branchAssembler.toResponse(branchRepo.save(Branch.builder().id(UUID.randomUUID().toString()) - .name(name).address(address).phone(phone).status(Branch.BranchStatus.ACTIVE).build())); - } - - @Transactional - public void updateBranch(String id, String name, String address, String phone) { - Branch b = branchRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("网点不存在")); - branchRepo.update(Branch.builder().id(id).name(name != null ? name : b.getName()) - .address(address != null ? address : b.getAddress()).phone(phone != null ? phone : b.getPhone()) - .status(b.getStatus()).build()); - } - - @Transactional - public void deleteBranch(String id) { branchRepo.deleteById(id); } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/AppointmentService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/AppointmentService.java deleted file mode 100644 index b9e0e83..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/AppointmentService.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.application.assembler.AppointmentAssembler; -import com.consultation.domain.aggregate.Appointment; -import com.consultation.domain.aggregate.Consultant; -import com.consultation.domain.repository.AppointmentRepository; -import com.consultation.domain.repository.ConsultantRepository; -import com.consultation.domain.service.AppointmentConflictService; -import com.consultation.domain.vo.AppointmentStatus; -import com.consultation.domain.vo.TimeSlot; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.List; -import java.util.UUID; - -@Service -@RequiredArgsConstructor -public class AppointmentService { - - private final AppointmentRepository appointmentRepo; - private final ConsultantRepository consultantRepo; - private final AppointmentConflictService conflictService = new AppointmentConflictService(); - private final AppointmentAssembler assembler; - - public AppointmentAssembler.AppointmentResponse getById(String id) { - return assembler.toResponse(appointmentRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("预约不存在"))); - } - - public List getMyAppointments(String userId) { - return appointmentRepo.findByUserId(userId, 1, 100).stream().map(assembler::toResponse).toList(); - } - - public List getAllAppointments() { - return appointmentRepo.findAll(1, 1000).stream().map(assembler::toResponse).toList(); - } - - @Transactional - public AppointmentAssembler.AppointmentResponse create(String userId, String consultantId, String branchId, - String date, String startTime, String endTime, String note) { - Consultant consultant = consultantRepo.findById(consultantId) - .orElseThrow(() -> new IllegalArgumentException("咨询师不存在")); - if (!consultant.isAvailable()) throw new IllegalStateException("该咨询师当前不可预约"); - - LocalDate ld = LocalDate.parse(date); - LocalTime st = LocalTime.parse(startTime); - LocalTime et = LocalTime.parse(endTime); - var existing = appointmentRepo.findByConsultantIdAndDate(consultantId, ld); - conflictService.validateNoConflict(existing, new TimeSlot(ld, st, et)); - - Appointment a = appointmentRepo.save(Appointment.builder().id(UUID.randomUUID().toString()) - .userId(userId).consultantId(consultantId).branchId(branchId) - .appointmentDate(ld).startTime(startTime).endTime(endTime) - .durationMinutes((int) java.time.Duration.between(st, et).toMinutes()) - .status(AppointmentStatus.PENDING).note(note).build()); - return assembler.toResponse(a); - } - - @Transactional - public void cancel(String id, String userId, String reason) { - Appointment a = appointmentRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("预约不存在")); - if (!a.canCancel()) throw new IllegalStateException("当前状态不允许取消"); - Appointment upd = Appointment.builder().id(a.getId()).userId(a.getUserId()).consultantId(a.getConsultantId()) - .branchId(a.getBranchId()).appointmentDate(a.getAppointmentDate()).startTime(a.getStartTime()) - .endTime(a.getEndTime()).durationMinutes(a.getDurationMinutes()).status(AppointmentStatus.CANCELLED) - .note(a.getNote()).cancelReason(reason != null ? reason : "用户取消").build(); - appointmentRepo.update(upd); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/AuthService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/AuthService.java deleted file mode 100644 index da1a105..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/AuthService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.application.assembler.UserAssembler; -import com.consultation.domain.aggregate.User; -import com.consultation.domain.repository.UserRepository; -import com.consultation.domain.service.PasswordService; -import com.consultation.domain.vo.UserRole; -import com.consultation.domain.vo.UserStatus; -import com.consultation.infrastructure.security.JwtTokenProvider; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import java.util.UUID; - -@Service -@RequiredArgsConstructor -public class AuthService { - - private final UserRepository userRepo; - private final PasswordService passwordService; - private final JwtTokenProvider tokenProvider; - private final UserAssembler assembler; - - @Transactional - public UserAssembler.AuthResponse register(String email, String password, String name, String phone) { - if (userRepo.existsByEmail(email)) throw new IllegalArgumentException("邮箱已被注册"); - User user = userRepo.save(User.builder().id(UUID.randomUUID().toString()).email(email) - .password(passwordService.encode(password)).name(name).phone(phone) - .role(UserRole.ROLE_USER).status(UserStatus.ACTIVE).build()); - return assembler.toAuth(user, tokenProvider.generate(user.getId(), user.getEmail(), user.getRole().name())); - } - - @Transactional - public UserAssembler.AuthResponse login(String email, String password) { - User user = userRepo.findByEmail(email).orElseThrow(() -> new IllegalArgumentException("邮箱或密码错误")); - if (!user.isActive()) throw new IllegalStateException("账户已被停用"); - if (!passwordService.matches(password, user.getPassword())) throw new IllegalArgumentException("邮箱或密码错误"); - return assembler.toAuth(user, tokenProvider.generate(user.getId(), user.getEmail(), user.getRole().name())); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/BusinessRuleAppService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/BusinessRuleAppService.java deleted file mode 100644 index 63394be..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/BusinessRuleAppService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.infrastructure.config.BusinessRuleProvider; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; - -@Service -@RequiredArgsConstructor -public class BusinessRuleAppService { - - private final BusinessRuleProvider provider; - - public List> getAllRules() { - return provider.getAllRules(); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/ConsultantService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/ConsultantService.java deleted file mode 100644 index 69c0473..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/ConsultantService.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.application.assembler.ConsultantAssembler; -import com.consultation.domain.aggregate.Consultant; -import com.consultation.domain.repository.AppointmentRepository; -import com.consultation.domain.repository.ConsultantRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDate; -import java.util.*; - -@Service -@RequiredArgsConstructor -public class ConsultantService { - - private final ConsultantRepository consultantRepo; - private final AppointmentRepository appointmentRepo; - private final ConsultantAssembler assembler; - - public List findAllActive() { - return consultantRepo.findAllActive().stream().map(assembler::toResponse).toList(); - } - - public ConsultantAssembler.ConsultantResponse getById(String id) { - return assembler.toResponse(consultantRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("咨询师不存在"))); - } - - public List> getAvailableSlots(String consultantId, String date) { - if (!consultantRepo.existsById(consultantId)) return List.of(); - LocalDate localDate = LocalDate.parse(date); - var booked = new HashSet(); - appointmentRepo.findByConsultantIdAndDate(consultantId, localDate).stream() - .filter(a -> a.getStatus() != com.consultation.domain.vo.AppointmentStatus.CANCELLED) - .forEach(a -> booked.add(a.getStartTime())); - - List> slots = new ArrayList<>(); - for (int h = 9; h < 18; h++) { - String s = String.format("%02d:00", h); - String e = String.format("%02d:00", h + 1); - if (!booked.contains(s)) slots.add(Map.of("startTime", s, "endTime", e)); - } - return slots; - } - - @Transactional - public ConsultantAssembler.ConsultantResponse create(String name, String title, String bio, String specialties, String avatar, String branchId, int sortOrder) { - Consultant c = consultantRepo.save(Consultant.builder().id(UUID.randomUUID().toString()).name(name) - .title(title).bio(bio).specialties(specialties).avatar(avatar).branchId(branchId) - .status(Consultant.ConsultantStatus.ACTIVE).sortOrder(sortOrder).build()); - return assembler.toResponse(c); - } - - @Transactional - public ConsultantAssembler.ConsultantResponse update(String id, String name, String title, String bio, String specialties) { - Consultant existing = consultantRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("咨询师不存在")); - Consultant upd = Consultant.builder().id(id).name(name != null ? name : existing.getName()) - .title(title != null ? title : existing.getTitle()).bio(bio != null ? bio : existing.getBio()) - .specialties(specialties != null ? specialties : existing.getSpecialties()) - .avatar(existing.getAvatar()).branchId(existing.getBranchId()).status(existing.getStatus()) - .sortOrder(existing.getSortOrder()).build(); - consultantRepo.update(upd); - return assembler.toResponse(upd); - } - - @Transactional - public void delete(String id) { consultantRepo.deleteById(id); } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/DataDictionaryAppService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/DataDictionaryAppService.java deleted file mode 100644 index 790e6fe..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/DataDictionaryAppService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.domain.datadictionary.DataDictionary; -import com.consultation.domain.datadictionary.DataDictionaryUtil; -import com.consultation.domain.datadictionary.DemoDataDictionaryType; -import org.springframework.stereotype.Service; - -import java.util.Arrays; -import java.util.List; - -@Service -public class DataDictionaryAppService { - - public List getAll() { - return DataDictionaryUtil.allDictionaries(DemoDataDictionaryType.values()); - } - - public DataDictionary getByType(String typeName) { - return Arrays.stream(DemoDataDictionaryType.values()) - .filter(t -> t.name().equalsIgnoreCase(typeName)) - .findFirst() - .map(DataDictionaryUtil::toDataDictionary) - .orElseThrow(() -> new IllegalArgumentException("字典类型不存在: " + typeName)); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/application/service/UserService.java b/example-project/apps/backend/src/main/java/com/consultation/application/service/UserService.java deleted file mode 100644 index cb50c86..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/application/service/UserService.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.consultation.application.service; - -import com.consultation.application.assembler.UserAssembler; -import com.consultation.domain.aggregate.User; -import com.consultation.domain.repository.UserRepository; -import com.consultation.domain.service.PasswordService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@RequiredArgsConstructor -public class UserService { - - private final UserRepository userRepo; - private final PasswordService passwordService; - private final UserAssembler assembler; - - public UserAssembler.UserResponse getProfile(String userId) { - return assembler.toResponse(userRepo.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在"))); - } - - @Transactional - public UserAssembler.UserResponse updateProfile(String userId, String name, String phone) { - User u = userRepo.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在")); - User upd = User.builder().id(u.getId()).email(u.getEmail()).password(u.getPassword()) - .name(name != null ? name : u.getName()).phone(phone != null ? phone : u.getPhone()) - .role(u.getRole()).status(u.getStatus()).build(); - userRepo.update(upd); - return assembler.toResponse(upd); - } - - @Transactional - public void changePassword(String userId, String oldPw, String newPw) { - User u = userRepo.findById(userId).orElseThrow(() -> new IllegalArgumentException("用户不存在")); - if (!passwordService.matches(oldPw, u.getPassword())) throw new IllegalArgumentException("原密码错误"); - User upd = User.builder().id(u.getId()).email(u.getEmail()).password(passwordService.encode(newPw)) - .name(u.getName()).phone(u.getPhone()).role(u.getRole()).status(u.getStatus()).build(); - userRepo.update(upd); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Appointment.java b/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Appointment.java deleted file mode 100644 index 7d1bd7b..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Appointment.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.consultation.domain.aggregate; - -import com.consultation.domain.vo.AppointmentStatus; -import lombok.Builder; -import lombok.Value; -import java.time.LocalDate; - -@Value @Builder -public class Appointment { - String id; String userId; String consultantId; String branchId; - LocalDate appointmentDate; String startTime; String endTime; - int durationMinutes; AppointmentStatus status; String note; String cancelReason; - - public boolean isOwnedBy(String uid) { return userId.equals(uid); } - public boolean canCancel() { return status == AppointmentStatus.PENDING || status == AppointmentStatus.CONFIRMED; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Branch.java b/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Branch.java deleted file mode 100644 index a632d46..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Branch.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.consultation.domain.aggregate; - -import lombok.Builder; -import lombok.Value; - -@Value @Builder -public class Branch { - String id; String name; String address; String phone; BranchStatus status; - public enum BranchStatus implements com.consultation.domain.datadictionary.Description { - ACTIVE("营业中"), DISABLED("已关闭"); - private final String description; - BranchStatus(String description) { this.description = description; } - @Override public String getCode() { return name(); } - @Override public String getDescription() { return description; } - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Consultant.java b/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Consultant.java deleted file mode 100644 index db8935f..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/Consultant.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.consultation.domain.aggregate; - -import lombok.Builder; -import lombok.Value; - -@Value @Builder -public class Consultant { - String id; String name; String title; String bio; String specialties; - String avatar; String branchId; ConsultantStatus status; int sortOrder; - - public enum ConsultantStatus implements com.consultation.domain.datadictionary.Description { - ACTIVE("可预约"), DISABLED("不可预约"); - private final String description; - ConsultantStatus(String description) { this.description = description; } - @Override public String getCode() { return name(); } - @Override public String getDescription() { return description; } - } - public boolean isAvailable() { return status == ConsultantStatus.ACTIVE; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/User.java b/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/User.java deleted file mode 100644 index e225e9d..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/aggregate/User.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.consultation.domain.aggregate; - -import com.consultation.domain.vo.UserRole; -import com.consultation.domain.vo.UserStatus; -import lombok.Builder; -import lombok.Value; - -@Value @Builder -public class User { - String id; - String email; - String password; - String name; - String phone; - UserRole role; - UserStatus status; - - public boolean isAdmin() { return role == UserRole.ROLE_ADMIN; } - public boolean isActive() { return status == UserStatus.ACTIVE; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/AppointmentRule.java b/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/AppointmentRule.java deleted file mode 100644 index 404f66c..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/AppointmentRule.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.consultation.domain.businessrule; - -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -public enum AppointmentRule implements IBusinessRule { - CONFLICT_DETECTION("appointment_conflict_detection", "同一咨询师同一时段不可重复预约"), - SLOT_INTERVAL("appointment_slot_interval", "预约时段间隔为 60 分钟"), - AVAILABLE_HOURS("appointment_available_hours", "可预约时段为 09:00-18:00"), - CANCEL_WINDOW("appointment_cancel_window", "PENDING / CONFIRMED 状态可取消"); - - private final String ruleName; - private final String description; - - @Override public String getRuleName() { return ruleName; } - @Override public String getDescription() { return description; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/AuthRule.java b/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/AuthRule.java deleted file mode 100644 index 9d955ae..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/AuthRule.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.consultation.domain.businessrule; - -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -public enum AuthRule implements IBusinessRule { - PASSWORD_MIN_LENGTH("auth_password_min_length", "密码最少 8 位"), - TOKEN_EXPIRATION("auth_token_expiration", "JWT 有效期 24 小时"), - PASSWORD_ALGORITHM("auth_password_algorithm", "密码使用 BCrypt 加密"); - - private final String ruleName; - private final String description; - - @Override public String getRuleName() { return ruleName; } - @Override public String getDescription() { return description; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/BusinessRuleConfig.java b/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/BusinessRuleConfig.java index f34ffdc..97d893f 100644 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/BusinessRuleConfig.java +++ b/example-project/apps/backend/src/main/java/com/consultation/domain/businessrule/BusinessRuleConfig.java @@ -9,47 +9,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +/** + * 业务规则配置空壳。后续按 feature 扩展字段,并由 YAML 绑定。 + */ @Data @Component -@ConfigurationProperties +@ConfigurationProperties(prefix = "business-rules") public class BusinessRuleConfig { - private Map appointment = new HashMap<>(); + private Map rules = new HashMap<>(); - private AuthConfig auth = new AuthConfig(); - - @Data - public static class AuthConfig { - - private PasswordConfig password = new PasswordConfig(); - - private TokenConfig token = new TokenConfig(); - - /** - * 免鉴权端点列表。YAML 里写成序列,若这里声明为 Map<String, Object>, - * 会被 Spring Boot 的 binder 绑成以 0/1/2… 为键的 Map,序列化出错误结构。 - */ - private List publicEndpoints = new ArrayList<>(List.of( - "/api/v1/auth/**", - "/api/v1/home/**", - "/api/v1/consultants/**", - "/api/v1/data-dictionaries/**", - "/api/v1/business-rules/**")); - } - - @Data - public static class PasswordConfig { - - private int minLength = 8; - - private String algorithm = "BCrypt"; - } - - @Data - public static class TokenConfig { - - private long expirationMs = 86400000L; - - private String algorithm = "HMAC-SHA256"; - } + private List publicEndpoints = new ArrayList<>(List.of( + "/api/v1/health" + )); } diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/datadictionary/DemoDataDictionaryType.java b/example-project/apps/backend/src/main/java/com/consultation/domain/datadictionary/DemoDataDictionaryType.java deleted file mode 100644 index 7a65947..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/datadictionary/DemoDataDictionaryType.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.consultation.domain.datadictionary; - -import com.consultation.domain.aggregate.Branch; -import com.consultation.domain.aggregate.Consultant; -import com.consultation.domain.vo.AppointmentStatus; -import com.consultation.domain.vo.UserRole; -import com.consultation.domain.vo.UserStatus; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -public enum DemoDataDictionaryType implements DataDictionaryType { - USER_ROLE(UserRole.class, "用户角色"), - USER_STATUS(UserStatus.class, "用户状态"), - APPOINTMENT_STATUS(AppointmentStatus.class, "预约状态"), - CONSULTANT_STATUS(Consultant.ConsultantStatus.class, "咨询师状态"), - BRANCH_STATUS(Branch.BranchStatus.class, "网点状态"); - - private final Class clazz; - private final String description; - - @Override public Class getClazz() { return clazz; } - @Override public String getDescription() { return description; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/AppointmentRepository.java b/example-project/apps/backend/src/main/java/com/consultation/domain/repository/AppointmentRepository.java deleted file mode 100644 index b9e995f..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/AppointmentRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.consultation.domain.repository; - -import com.consultation.domain.aggregate.Appointment; -import java.time.LocalDate; -import java.util.List; -import java.util.Optional; - -public interface AppointmentRepository { - Optional findById(String id); - List findByUserId(String userId, int page, int pageSize); - List findByConsultantIdAndDate(String consultantId, LocalDate date); - List findAll(int page, int pageSize); - Appointment save(Appointment a); - void update(Appointment a); - long count(); - long countByStatus(String status); - long countByUserId(String userId); -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/BranchRepository.java b/example-project/apps/backend/src/main/java/com/consultation/domain/repository/BranchRepository.java deleted file mode 100644 index 34e2ac4..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/BranchRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.consultation.domain.repository; - -import com.consultation.domain.aggregate.Branch; -import java.util.List; -import java.util.Optional; - -public interface BranchRepository { - Optional findById(String id); - List findAll(); - Branch save(Branch b); - void update(Branch b); - void deleteById(String id); - long count(); -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/ConsultantRepository.java b/example-project/apps/backend/src/main/java/com/consultation/domain/repository/ConsultantRepository.java deleted file mode 100644 index 5e3faa0..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/ConsultantRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.consultation.domain.repository; - -import com.consultation.domain.aggregate.Consultant; -import java.util.List; -import java.util.Optional; - -public interface ConsultantRepository { - Optional findById(String id); - List findAllActive(); - List findAll(); - Consultant save(Consultant c); - void update(Consultant c); - void deleteById(String id); - long count(); - boolean existsById(String id); -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/UserRepository.java b/example-project/apps/backend/src/main/java/com/consultation/domain/repository/UserRepository.java deleted file mode 100644 index d74337d..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/repository/UserRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.consultation.domain.repository; - -import com.consultation.domain.aggregate.User; -import java.util.List; -import java.util.Optional; - -public interface UserRepository { - Optional findById(String id); - Optional findByEmail(String email); - List findAll(); - User save(User user); - void update(User user); - boolean existsByEmail(String email); -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/service/AppointmentConflictService.java b/example-project/apps/backend/src/main/java/com/consultation/domain/service/AppointmentConflictService.java deleted file mode 100644 index 37dc0d7..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/service/AppointmentConflictService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.consultation.domain.service; - -import com.consultation.domain.aggregate.Appointment; -import com.consultation.domain.vo.AppointmentStatus; -import com.consultation.domain.vo.TimeSlot; -import java.util.List; - -public class AppointmentConflictService { - - public void validateNoConflict(List existing, TimeSlot requested) { - boolean conflict = existing.stream().anyMatch(a -> - a.getAppointmentDate().equals(requested.date()) && - a.getStartTime().equals(requested.startTime().toString()) && - a.getStatus() != AppointmentStatus.CANCELLED); - if (conflict) throw new IllegalStateException("该时间段已被预约"); - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/AppointmentStatus.java b/example-project/apps/backend/src/main/java/com/consultation/domain/vo/AppointmentStatus.java deleted file mode 100644 index d0dc2a0..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/AppointmentStatus.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.consultation.domain.vo; - -import com.consultation.domain.datadictionary.Description; - -public enum AppointmentStatus implements Description { - PENDING("待确认"), - CONFIRMED("已确认"), - COMPLETED("已完成"), - CANCELLED("已取消"); - - private final String description; - AppointmentStatus(String description) { this.description = description; } - @Override public String getCode() { return name(); } - @Override public String getDescription() { return description; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/TimeSlot.java b/example-project/apps/backend/src/main/java/com/consultation/domain/vo/TimeSlot.java deleted file mode 100644 index b9a4003..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/TimeSlot.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.consultation.domain.vo; - -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalTime; - -public record TimeSlot(LocalDate date, LocalTime startTime, LocalTime endTime) { - public int durationMinutes() { return (int) Duration.between(startTime, endTime).toMinutes(); } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/UserRole.java b/example-project/apps/backend/src/main/java/com/consultation/domain/vo/UserRole.java deleted file mode 100644 index e2dd8d7..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/UserRole.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.consultation.domain.vo; - -import com.consultation.domain.datadictionary.Description; - -public enum UserRole implements Description { - ROLE_USER("普通用户"), - ROLE_ADMIN("管理员"); - - private final String description; - UserRole(String description) { this.description = description; } - @Override public String getCode() { return name(); } - @Override public String getDescription() { return description; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/UserStatus.java b/example-project/apps/backend/src/main/java/com/consultation/domain/vo/UserStatus.java deleted file mode 100644 index ed0c2ac..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/domain/vo/UserStatus.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.consultation.domain.vo; - -import com.consultation.domain.datadictionary.Description; - -public enum UserStatus implements Description { - ACTIVE("正常"), - DISABLED("已停用"); - - private final String description; - UserStatus(String description) { this.description = description; } - @Override public String getCode() { return name(); } - @Override public String getDescription() { return description; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleProvider.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleProvider.java index b2af23d..c2de827 100644 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleProvider.java +++ b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleProvider.java @@ -8,7 +8,10 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; @Component @RequiredArgsConstructor @@ -26,30 +29,19 @@ public class BusinessRuleProvider { Map detail = new LinkedHashMap<>(); detail.put("ruleName", rule.getRuleName()); detail.put("description", rule.getDescription()); - - Map ruleConfig = new LinkedHashMap<>(); - addIfPresent(ruleConfig, "appointment", projected.get("appointment")); - addIfPresent(ruleConfig, "auth", projected.get("auth")); - if (!ruleConfig.isEmpty()) detail.put("config", ruleConfig); - + if (!projected.isEmpty()) { + detail.put("config", projected); + } ruleCache.put(rule.getRuleName(), detail); } } public List> getAllRules() { - return new ArrayList>(ruleCache.values()); + return new ArrayList<>(ruleCache.values()); } - /** - * 把强类型的配置对象投影成 Map,保持对外返回结构为 {@code List>}。 - * JSON 形状属于基础设施关注点,故投影放在 infrastructure 层,domain 不依赖 ObjectMapper。 - */ private Map projectConfig() { return objectMapper.convertValue(config, new TypeReference>() { }); } - - private void addIfPresent(Map target, String key, Object source) { - if (source instanceof Map map && !map.isEmpty()) target.put(key, map); - } } diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleRegistration.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleRegistration.java index 4e38d65..d8f33c4 100644 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleRegistration.java +++ b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleRegistration.java @@ -1,46 +1,11 @@ package com.consultation.infrastructure.config; -import com.consultation.domain.businessrule.AppointmentRule; -import com.consultation.domain.businessrule.AuthRule; -import com.consultation.domain.businessrule.IBusinessRule; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +/** + * 业务规则 Bean 注册入口(当前为空壳)。 + * iteration1 实现时在此注册 {@link com.consultation.domain.businessrule.IBusinessRule} 实现。 + */ @Configuration public class BusinessRuleRegistration { - - @Bean - public IBusinessRule appointmentConflictDetection() { - return AppointmentRule.CONFLICT_DETECTION; - } - - @Bean - public IBusinessRule appointmentSlotInterval() { - return AppointmentRule.SLOT_INTERVAL; - } - - @Bean - public IBusinessRule appointmentAvailableHours() { - return AppointmentRule.AVAILABLE_HOURS; - } - - @Bean - public IBusinessRule appointmentCancelWindow() { - return AppointmentRule.CANCEL_WINDOW; - } - - @Bean - public IBusinessRule authPasswordMinLength() { - return AuthRule.PASSWORD_MIN_LENGTH; - } - - @Bean - public IBusinessRule authTokenExpiration() { - return AuthRule.TOKEN_EXPIRATION; - } - - @Bean - public IBusinessRule authPasswordAlgorithm() { - return AuthRule.PASSWORD_ALGORITHM; - } } diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/SecurityConfig.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/SecurityConfig.java index 2fbbe23..b3ae1e1 100644 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/SecurityConfig.java +++ b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/config/SecurityConfig.java @@ -4,7 +4,6 @@ import com.consultation.infrastructure.security.JwtAuthenticationFilter; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -25,13 +24,7 @@ public class SecurityConfig { http.csrf(c -> c.disable()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(a -> a - .requestMatchers("/api/v1/auth/**").permitAll() - .requestMatchers("/api/v1/home/**").permitAll() - .requestMatchers("/api/v1/data-dictionaries/**").permitAll() - .requestMatchers("/api/v1/business-rules/**").permitAll() - .requestMatchers(HttpMethod.GET, "/api/v1/consultants", "/api/v1/consultants/*/slots").permitAll() - .requestMatchers("/api/v1/admin/**").hasRole("ADMIN") - .requestMatchers("/admin/**").hasRole("ADMIN") + .requestMatchers("/api/v1/health").permitAll() .anyRequest().authenticated() ) .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/AppointmentConverter.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/AppointmentConverter.java deleted file mode 100644 index 0e0c004..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/AppointmentConverter.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.consultation.infrastructure.persistence.converter; - -import com.consultation.domain.aggregate.Appointment; -import com.consultation.domain.vo.AppointmentStatus; -import com.consultation.infrastructure.persistence.po.AppointmentPO; -import org.springframework.stereotype.Component; - -@Component -public class AppointmentConverter { - public Appointment toDomain(AppointmentPO po) { - if (po == null) return null; - return Appointment.builder().id(po.getId()).userId(po.getUserId()).consultantId(po.getConsultantId()) - .branchId(po.getBranchId()).appointmentDate(po.getAppointmentDate()) - .startTime(po.getStartTime()).endTime(po.getEndTime()).durationMinutes(po.getDurationMinutes()) - .status(AppointmentStatus.valueOf(po.getStatus())).note(po.getNote()).cancelReason(po.getCancelReason()).build(); - } - public AppointmentPO toPO(Appointment a) { - if (a == null) return null; - AppointmentPO po = new AppointmentPO(); - po.setId(a.getId()); po.setUserId(a.getUserId()); po.setConsultantId(a.getConsultantId()); - po.setBranchId(a.getBranchId()); po.setAppointmentDate(a.getAppointmentDate()); - po.setStartTime(a.getStartTime()); po.setEndTime(a.getEndTime()); po.setDurationMinutes(a.getDurationMinutes()); - po.setStatus(a.getStatus().name()); po.setNote(a.getNote()); po.setCancelReason(a.getCancelReason()); - return po; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/BranchConverter.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/BranchConverter.java deleted file mode 100644 index 1fe209f..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/BranchConverter.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.consultation.infrastructure.persistence.converter; - -import com.consultation.domain.aggregate.Branch; -import com.consultation.infrastructure.persistence.po.BranchPO; -import org.springframework.stereotype.Component; - -@Component -public class BranchConverter { - public Branch toDomain(BranchPO po) { - if (po == null) return null; - return Branch.builder().id(po.getId()).name(po.getName()).address(po.getAddress()) - .phone(po.getPhone()).status(Branch.BranchStatus.valueOf(po.getStatus())).build(); - } - public BranchPO toPO(Branch b) { - if (b == null) return null; - BranchPO po = new BranchPO(); - po.setId(b.getId()); po.setName(b.getName()); po.setAddress(b.getAddress()); - po.setPhone(b.getPhone()); po.setStatus(b.getStatus().name()); - return po; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/ConsultantConverter.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/ConsultantConverter.java deleted file mode 100644 index b940b0e..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/ConsultantConverter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.consultation.infrastructure.persistence.converter; - -import com.consultation.domain.aggregate.Consultant; -import com.consultation.infrastructure.persistence.po.ConsultantPO; -import org.springframework.stereotype.Component; - -@Component -public class ConsultantConverter { - public Consultant toDomain(ConsultantPO po) { - if (po == null) return null; - return Consultant.builder().id(po.getId()).name(po.getName()).title(po.getTitle()).bio(po.getBio()) - .specialties(po.getSpecialties()).avatar(po.getAvatar()).branchId(po.getBranchId()) - .status(Consultant.ConsultantStatus.valueOf(po.getStatus())).sortOrder(po.getSortOrder()).build(); - } - public ConsultantPO toPO(Consultant c) { - if (c == null) return null; - ConsultantPO po = new ConsultantPO(); - po.setId(c.getId()); po.setName(c.getName()); po.setTitle(c.getTitle()); po.setBio(c.getBio()); - po.setSpecialties(c.getSpecialties()); po.setAvatar(c.getAvatar()); po.setBranchId(c.getBranchId()); - po.setStatus(c.getStatus().name()); po.setSortOrder(c.getSortOrder()); - return po; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/UserConverter.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/UserConverter.java deleted file mode 100644 index ae430b3..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/converter/UserConverter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.consultation.infrastructure.persistence.converter; - -import com.consultation.domain.aggregate.User; -import com.consultation.domain.vo.UserRole; -import com.consultation.domain.vo.UserStatus; -import com.consultation.infrastructure.persistence.po.UserPO; -import org.springframework.stereotype.Component; - -@Component -public class UserConverter { - public User toDomain(UserPO po) { - if (po == null) return null; - return User.builder().id(po.getId()).email(po.getEmail()).password(po.getPassword()) - .name(po.getName()).phone(po.getPhone()) - .role(UserRole.valueOf(po.getRole())).status(UserStatus.valueOf(po.getStatus())).build(); - } - public UserPO toPO(User u) { - if (u == null) return null; - UserPO po = new UserPO(); - po.setId(u.getId()); po.setEmail(u.getEmail()); po.setPassword(u.getPassword()); - po.setName(u.getName()); po.setPhone(u.getPhone()); - po.setRole(u.getRole().name()); po.setStatus(u.getStatus().name()); - return po; - } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/AppointmentMapper.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/AppointmentMapper.java deleted file mode 100644 index 7a827c1..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/AppointmentMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.consultation.infrastructure.persistence.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.consultation.infrastructure.persistence.po.AppointmentPO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface AppointmentMapper extends BaseMapper {} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/BranchMapper.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/BranchMapper.java deleted file mode 100644 index b413372..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/BranchMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.consultation.infrastructure.persistence.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.consultation.infrastructure.persistence.po.BranchPO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface BranchMapper extends BaseMapper {} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/ConsultantMapper.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/ConsultantMapper.java deleted file mode 100644 index ec9e0c5..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/ConsultantMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.consultation.infrastructure.persistence.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.consultation.infrastructure.persistence.po.ConsultantPO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface ConsultantMapper extends BaseMapper {} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/UserMapper.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/UserMapper.java deleted file mode 100644 index 4fa6820..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/mapper/UserMapper.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.consultation.infrastructure.persistence.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.consultation.infrastructure.persistence.po.UserPO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface UserMapper extends BaseMapper {} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/AppointmentPO.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/AppointmentPO.java deleted file mode 100644 index f4f8955..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/AppointmentPO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.consultation.infrastructure.persistence.po; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("appointment") -public class AppointmentPO { - private String id; private String userId; private String consultantId; private String branchId; - private LocalDate appointmentDate; private String startTime; private String endTime; - private Integer durationMinutes; private String status; private String note; private String cancelReason; - private String createdBy; private LocalDateTime createdTime; - private String updatedBy; private LocalDateTime updatedTime; -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/BranchPO.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/BranchPO.java deleted file mode 100644 index 3345cce..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/BranchPO.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.consultation.infrastructure.persistence.po; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import java.time.LocalDateTime; - -@Data -@TableName("branch") -public class BranchPO { - private String id; private String name; private String address; private String phone; - private String status; - private String createdBy; private LocalDateTime createdTime; - private String updatedBy; private LocalDateTime updatedTime; -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/ConsultantPO.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/ConsultantPO.java deleted file mode 100644 index 51db98a..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/ConsultantPO.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.consultation.infrastructure.persistence.po; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import java.time.LocalDateTime; - -@Data -@TableName("consultant") -public class ConsultantPO { - private String id; private String name; private String title; private String bio; - private String specialties; private String avatar; private String branchId; - private String status; private Integer sortOrder; - private String createdBy; private LocalDateTime createdTime; - private String updatedBy; private LocalDateTime updatedTime; -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/UserPO.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/UserPO.java deleted file mode 100644 index 9787dab..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/persistence/po/UserPO.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.consultation.infrastructure.persistence.po; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import java.time.LocalDateTime; - -@Data -@TableName("user") -public class UserPO { - private String id; private String email; private String password; private String name; - private String phone; private String role; private String status; private Integer deleted; - private String createdBy; private LocalDateTime createdTime; - private String updatedBy; private LocalDateTime updatedTime; -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/AppointmentRepositoryImpl.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/AppointmentRepositoryImpl.java deleted file mode 100644 index 7ffb5c6..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/AppointmentRepositoryImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.consultation.infrastructure.repositoryimpl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.consultation.domain.aggregate.Appointment; -import com.consultation.domain.repository.AppointmentRepository; -import com.consultation.infrastructure.persistence.converter.AppointmentConverter; -import com.consultation.infrastructure.persistence.mapper.AppointmentMapper; -import com.consultation.infrastructure.persistence.po.AppointmentPO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Repository; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -@Repository -@RequiredArgsConstructor -public class AppointmentRepositoryImpl implements AppointmentRepository { - - private final AppointmentMapper mapper; - private final AppointmentConverter converter; - - @Override public Optional findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); } - - @Override - public List findByUserId(String userId, int page, int pageSize) { - return mapper.selectPage(new Page<>(page, pageSize), - new LambdaQueryWrapper().eq(AppointmentPO::getUserId, userId).orderByDesc(AppointmentPO::getCreatedTime)) - .getRecords().stream().map(converter::toDomain).toList(); - } - - @Override - public List findByConsultantIdAndDate(String consultantId, LocalDate date) { - return mapper.selectList(new LambdaQueryWrapper() - .eq(AppointmentPO::getConsultantId, consultantId).eq(AppointmentPO::getAppointmentDate, date)) - .stream().map(converter::toDomain).toList(); - } - - @Override - public List findAll(int page, int pageSize) { - return mapper.selectPage(new Page<>(page, pageSize), null).getRecords().stream().map(converter::toDomain).toList(); - } - - @Override - public Appointment save(Appointment a) { - AppointmentPO po = converter.toPO(a); - po.setCreatedBy(a.getUserId()); po.setCreatedTime(LocalDateTime.now()); - po.setUpdatedBy(a.getUserId()); po.setUpdatedTime(LocalDateTime.now()); - mapper.insert(po); return a; - } - - @Override public void update(Appointment a) { AppointmentPO po = converter.toPO(a); po.setUpdatedTime(LocalDateTime.now()); mapper.updateById(po); } - - @Override public long count() { return mapper.selectCount(null); } - @Override public long countByStatus(String s) { return mapper.selectCount(new LambdaQueryWrapper().eq(AppointmentPO::getStatus, s)); } - @Override public long countByUserId(String u) { return mapper.selectCount(new LambdaQueryWrapper().eq(AppointmentPO::getUserId, u)); } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/BranchRepositoryImpl.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/BranchRepositoryImpl.java deleted file mode 100644 index b0123f1..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/BranchRepositoryImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.consultation.infrastructure.repositoryimpl; - -import com.consultation.domain.aggregate.Branch; -import com.consultation.domain.repository.BranchRepository; -import com.consultation.infrastructure.persistence.converter.BranchConverter; -import com.consultation.infrastructure.persistence.mapper.BranchMapper; -import com.consultation.infrastructure.persistence.po.BranchPO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Repository; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -@Repository -@RequiredArgsConstructor -public class BranchRepositoryImpl implements BranchRepository { - - private final BranchMapper mapper; - private final BranchConverter converter; - - @Override public Optional findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); } - @Override public List findAll() { return mapper.selectList(null).stream().map(converter::toDomain).toList(); } - - @Override - public Branch save(Branch b) { - BranchPO po = converter.toPO(b); - po.setCreatedBy(b.getId()); po.setCreatedTime(LocalDateTime.now()); po.setUpdatedBy(b.getId()); po.setUpdatedTime(LocalDateTime.now()); - mapper.insert(po); return b; - } - - @Override public void update(Branch b) { BranchPO po = converter.toPO(b); po.setUpdatedTime(LocalDateTime.now()); mapper.updateById(po); } - @Override public void deleteById(String id) { mapper.deleteById(id); } - @Override public long count() { return mapper.selectCount(null); } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/ConsultantRepositoryImpl.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/ConsultantRepositoryImpl.java deleted file mode 100644 index 97cf795..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/ConsultantRepositoryImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.consultation.infrastructure.repositoryimpl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.consultation.domain.aggregate.Consultant; -import com.consultation.domain.repository.ConsultantRepository; -import com.consultation.infrastructure.persistence.converter.ConsultantConverter; -import com.consultation.infrastructure.persistence.mapper.ConsultantMapper; -import com.consultation.infrastructure.persistence.po.ConsultantPO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Repository; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -@Repository -@RequiredArgsConstructor -public class ConsultantRepositoryImpl implements ConsultantRepository { - - private final ConsultantMapper mapper; - private final ConsultantConverter converter; - - @Override public Optional findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); } - @Override public List findAll() { return mapper.selectList(null).stream().map(converter::toDomain).toList(); } - - @Override - public List findAllActive() { - return mapper.selectList(new LambdaQueryWrapper() - .eq(ConsultantPO::getStatus, Consultant.ConsultantStatus.ACTIVE.name()) - .orderByAsc(ConsultantPO::getSortOrder)).stream().map(converter::toDomain).toList(); - } - - @Override - public Consultant save(Consultant c) { - ConsultantPO po = converter.toPO(c); - po.setCreatedBy(c.getId()); po.setCreatedTime(LocalDateTime.now()); po.setUpdatedBy(c.getId()); po.setUpdatedTime(LocalDateTime.now()); - mapper.insert(po); return c; - } - - @Override public void update(Consultant c) { ConsultantPO po = converter.toPO(c); po.setUpdatedTime(LocalDateTime.now()); mapper.updateById(po); } - @Override public void deleteById(String id) { mapper.deleteById(id); } - @Override public long count() { return mapper.selectCount(null); } - @Override public boolean existsById(String id) { return mapper.selectCount(new LambdaQueryWrapper().eq(ConsultantPO::getId, id)) > 0; } -} diff --git a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/UserRepositoryImpl.java b/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/UserRepositoryImpl.java deleted file mode 100644 index e5121ae..0000000 --- a/example-project/apps/backend/src/main/java/com/consultation/infrastructure/repositoryimpl/UserRepositoryImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.consultation.infrastructure.repositoryimpl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.consultation.domain.aggregate.User; -import com.consultation.domain.repository.UserRepository; -import com.consultation.infrastructure.persistence.converter.UserConverter; -import com.consultation.infrastructure.persistence.mapper.UserMapper; -import com.consultation.infrastructure.persistence.po.UserPO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Repository; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Optional; - -@Repository -@RequiredArgsConstructor -public class UserRepositoryImpl implements UserRepository { - - private final UserMapper mapper; - private final UserConverter converter; - - @Override - public Optional findById(String id) { return Optional.ofNullable(converter.toDomain(mapper.selectById(id))); } - - @Override - public Optional findByEmail(String email) { - return Optional.ofNullable(converter.toDomain(mapper.selectOne(new LambdaQueryWrapper().eq(UserPO::getEmail, email)))); - } - - @Override - public List findAll() { return mapper.selectList(null).stream().map(converter::toDomain).toList(); } - - @Override - public User save(User u) { - UserPO po = converter.toPO(u); - po.setCreatedBy(u.getId()); po.setCreatedTime(LocalDateTime.now()); - po.setUpdatedBy(u.getId()); po.setUpdatedTime(LocalDateTime.now()); - mapper.insert(po); - return u; - } - - @Override - public void update(User u) { - UserPO po = converter.toPO(u); - po.setUpdatedTime(LocalDateTime.now()); - mapper.updateById(po); - } - - @Override - public boolean existsByEmail(String email) { return mapper.selectCount(new LambdaQueryWrapper().eq(UserPO::getEmail, email)) > 0; } -} diff --git a/example-project/apps/backend/src/main/resources/application.yml.example b/example-project/apps/backend/src/main/resources/application.yml.example index 2fa9e2e..bc251ca 100644 --- a/example-project/apps/backend/src/main/resources/application.yml.example +++ b/example-project/apps/backend/src/main/resources/application.yml.example @@ -3,8 +3,6 @@ server: spring: application: name: consultation-backend - config: - import: "classpath:/business-rules/appointment.yml,classpath:/business-rules/auth.yml" datasource: url: jdbc:mysql://localhost:3306/consultation?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai username: root @@ -26,3 +24,6 @@ mybatis-plus: jwt: secret: expiration: 86400000 +business-rules: + public-endpoints: + - /api/v1/health diff --git a/example-project/apps/backend/src/main/resources/business-rules/.gitkeep b/example-project/apps/backend/src/main/resources/business-rules/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/example-project/apps/backend/src/main/resources/business-rules/appointment.yml b/example-project/apps/backend/src/main/resources/business-rules/appointment.yml deleted file mode 100644 index b926dd3..0000000 --- a/example-project/apps/backend/src/main/resources/business-rules/appointment.yml +++ /dev/null @@ -1,14 +0,0 @@ -appointment: - conflict: - detection: "同一咨询师同一时段不可重复预约" - enforcement: "uk_appointment_slot 唯一索引 + AppointmentConflictService 双重校验" - slot: - minMinutes: 30 - maxMinutes: 120 - intervalMinutes: 60 - available: - start: "09:00" - end: "18:00" - cancel: - allowedStatuses: "PENDING, CONFIRMED" - reasonRequired: true diff --git a/example-project/apps/backend/src/main/resources/business-rules/auth.yml b/example-project/apps/backend/src/main/resources/business-rules/auth.yml deleted file mode 100644 index 4db8040..0000000 --- a/example-project/apps/backend/src/main/resources/business-rules/auth.yml +++ /dev/null @@ -1,13 +0,0 @@ -auth: - password: - minLength: 8 - algorithm: "BCrypt" - token: - expirationMs: 86400000 - algorithm: "HMAC-SHA256" - publicEndpoints: - - "/api/v1/auth/**" - - "/api/v1/home/**" - - "/api/v1/consultants/**" - - "/api/v1/data-dictionaries/**" - - "/api/v1/business-rules/**" diff --git a/example-project/apps/backend/src/main/resources/db/migration/.gitkeep b/example-project/apps/backend/src/main/resources/db/migration/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/example-project/apps/backend/src/main/resources/db/migration/V20260619__init_user.sql b/example-project/apps/backend/src/main/resources/db/migration/V20260619__init_user.sql deleted file mode 100644 index 9370016..0000000 --- a/example-project/apps/backend/src/main/resources/db/migration/V20260619__init_user.sql +++ /dev/null @@ -1,22 +0,0 @@ -create table user -( - id varchar(64) not null primary key comment '用户ID', - email varchar(128) not null comment '邮箱', - password varchar(256) not null comment '密码(BCrypt)', - name varchar(64) not null comment '姓名', - phone varchar(20) null comment '手机号', - role varchar(20) not null default 'ROLE_USER' comment '角色', - status varchar(12) not null default 'ACTIVE' comment '状态', - deleted tinyint(1) default 0 not null, - created_by varchar(64) not null, - created_time datetime default CURRENT_TIMESTAMP not null, - updated_by varchar(64) not null, - updated_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP -) comment '用户表' charset = utf8mb4; - -create unique index uk_user_email on user(email); - -insert into user (id, email, password, name, phone, role, status, created_by, updated_by) -values ('admin-001', 'admin@test.com', - '$2a$10$4rDXdT56xLoF0LajF1fKRuZFxxdAd6rM9CuCcZdRrb/k7eRHMTKQq', - '管理员', '13800000000', 'ROLE_ADMIN', 'ACTIVE', 'admin-001', 'admin-001'); diff --git a/example-project/apps/backend/src/main/resources/db/migration/V20260620__consultant_appointment.sql b/example-project/apps/backend/src/main/resources/db/migration/V20260620__consultant_appointment.sql deleted file mode 100644 index 86235a8..0000000 --- a/example-project/apps/backend/src/main/resources/db/migration/V20260620__consultant_appointment.sql +++ /dev/null @@ -1,47 +0,0 @@ -create table consultant -( - id varchar(64) not null primary key comment '咨询师ID', - name varchar(64) not null comment '姓名', - title varchar(128) null comment '头衔', - bio text null comment '简介', - specialties varchar(256) null comment '专长', - avatar varchar(256) null comment '头像', - branch_id varchar(64) null comment '网点ID', - status varchar(12) not null default 'ACTIVE' comment '状态', - sort_order int default 0 not null comment '排序', - created_by varchar(64) not null, - created_time datetime default CURRENT_TIMESTAMP not null, - updated_by varchar(64) not null, - updated_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP -) comment '咨询师表' charset = utf8mb4; - -create index idx_consultant_status on consultant(status); - -insert into consultant (id, name, title, bio, specialties, sort_order, created_by, updated_by) -values ('c-001', '张医生', '资深心理咨询师', '拥有15年心理咨询经验。', '焦虑症,抑郁症,人际关系', 1, 'admin-001', 'admin-001'), - ('c-002', '李律师', '企业法律顾问', '10年企业法律顾问经验。', '合同法,劳动法,公司治理', 2, 'admin-001', 'admin-001'), - ('c-003', '王教练', '职业规划导师', '帮助超过500人实现职业转型。', '职业规划,简历优化', 3, 'admin-001', 'admin-001'); - -create table appointment -( - id varchar(64) not null primary key comment '预约ID', - user_id varchar(64) not null comment '用户ID', - consultant_id varchar(64) not null comment '咨询师ID', - branch_id varchar(64) null comment '网点ID', - appointment_date date not null comment '预约日期', - start_time varchar(10) not null comment '开始时间', - end_time varchar(10) not null comment '结束时间', - duration_minutes int not null comment '时长(分钟)', - status varchar(20) not null default 'PENDING' comment '状态', - note text null comment '备注', - cancel_reason varchar(256) null comment '取消原因', - created_by varchar(64) not null, - created_time datetime default CURRENT_TIMESTAMP not null, - updated_by varchar(64) not null, - updated_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP -) comment '预约表' charset = utf8mb4; - -create index idx_appointment_user on appointment(user_id); -create index idx_appointment_consultant on appointment(consultant_id); -create index idx_appointment_date on appointment(appointment_date); -create unique index uk_appointment_slot on appointment(consultant_id, appointment_date, start_time); diff --git a/example-project/apps/backend/src/main/resources/db/migration/V20260621__branch.sql b/example-project/apps/backend/src/main/resources/db/migration/V20260621__branch.sql deleted file mode 100644 index 5d97a31..0000000 --- a/example-project/apps/backend/src/main/resources/db/migration/V20260621__branch.sql +++ /dev/null @@ -1,17 +0,0 @@ -CREATE TABLE IF NOT EXISTS branch ( - id VARCHAR(64) PRIMARY KEY, - name VARCHAR(100) NOT NULL, - address VARCHAR(255), - phone VARCHAR(20), - status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE', - created_by VARCHAR(64), - created_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_by VARCHAR(64), - updated_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP -); - -INSERT INTO branch (id, name, address, phone, status) VALUES -('b-001', '朝阳咨询中心', '北京市朝阳区建国路88号', '010-88880001', 'ACTIVE'), -('b-002', '海淀咨询中心', '北京市海淀区中关村大街66号', '010-88880002', 'ACTIVE'), -('b-003', '浦东咨询中心', '上海市浦东新区陆家嘴路100号', '021-68880003', 'ACTIVE') -ON DUPLICATE KEY UPDATE name=VALUES(name); diff --git a/example-project/apps/backend/src/test/java/com/consultation/TestBase.java b/example-project/apps/backend/src/test/java/com/consultation/TestBase.java index d472e94..cca108b 100644 --- a/example-project/apps/backend/src/test/java/com/consultation/TestBase.java +++ b/example-project/apps/backend/src/test/java/com/consultation/TestBase.java @@ -2,12 +2,10 @@ package com.consultation; import com.consultation.config.ResetDbService; import io.restassured.RestAssured; -import io.restassured.http.ContentType; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; -import static io.restassured.RestAssured.given; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public abstract class TestBase { @@ -24,37 +22,4 @@ public abstract class TestBase { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); resetDbService.resetAll(); } - - protected String loginAsUser() { - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"test@test.com\",\"password\":\"password123\",\"name\":\"测试用户\"}") - .when() - .post("/api/v1/auth/register") - .then() - .statusCode(200); - var r = given() - .contentType(ContentType.JSON) - .body("{\"email\":\"test@test.com\",\"password\":\"password123\"}") - .when() - .post("/api/v1/auth/login") - .then() - .statusCode(200); - return r.extract().jsonPath().getString("token"); - } - - protected String loginAsAdmin() { - var r = given() - .contentType(ContentType.JSON) - .body("{\"email\":\"admin@test.com\",\"password\":\"password\"}") - .when() - .post("/api/v1/auth/login") - .then() - .statusCode(200); - return r.extract().jsonPath().getString("token"); - } - - protected String authHeader(String token) { - return "Bearer " + token; - } } diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AdminControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AdminControllerTest.java deleted file mode 100644 index 9440b36..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AdminControllerTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import io.restassured.http.ContentType; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -class AdminControllerTest extends TestBase { - - String adminToken; - - @BeforeEach - void initToken() { - adminToken = loginAsAdmin(); - } - - @Test - void should_get_dashboard() { - given() - .header("Authorization", authHeader(adminToken)) - .when() - .get("/api/v1/admin/dashboard") - .then() - .statusCode(200) - .body("totalUsers", notNullValue()) - .body("totalConsultants", notNullValue()) - .body("totalAppointments", notNullValue()); - } - - @Test - void should_list_users() { - given() - .header("Authorization", authHeader(adminToken)) - .when() - .get("/api/v1/admin/users") - .then() - .statusCode(200) - .body("$", not(empty())); - } - - @Test - void should_toggle_user_status() { - var firstUserId = given() - .header("Authorization", authHeader(adminToken)) - .when() - .get("/api/v1/admin/users") - .then() - .statusCode(200) - .extract().jsonPath().getString("[0].id"); - - given() - .header("Authorization", authHeader(adminToken)) - .when() - .put("/api/v1/admin/users/{id}/toggle-status", firstUserId) - .then() - .statusCode(200); - } - - @Test - void should_branch_crud() { - var branchId = given() - .header("Authorization", authHeader(adminToken)) - .contentType(ContentType.JSON) - .body("{\"name\":\"测试网点\",\"address\":\"测试地址\",\"phone\":\"010-88888888\"}") - .when() - .post("/api/v1/admin/branches") - .then() - .statusCode(200) - .extract().jsonPath().getString("id"); - - given() - .header("Authorization", authHeader(adminToken)) - .contentType(ContentType.JSON) - .body("{\"name\":\"更新网点\"}") - .when() - .put("/api/v1/admin/branches/{id}", branchId) - .then() - .statusCode(200); - - given() - .header("Authorization", authHeader(adminToken)) - .when() - .delete("/api/v1/admin/branches/{id}", branchId) - .then() - .statusCode(200); - } - - @Test - void should_crud_data_dictionary() { - given() - .when() - .get("/api/v1/data-dictionaries") - .then() - .statusCode(200) - .body("$", not(empty())); - - given() - .when() - .get("/api/v1/data-dictionaries/USER_ROLE") - .then() - .statusCode(200) - .body("typeName", equalTo("USER_ROLE")) - .body("items", not(empty())); - } - - @Test - void should_list_business_rules() { - given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .body("$", not(empty())); - } -} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AppointmentControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AppointmentControllerTest.java deleted file mode 100644 index 788b81b..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AppointmentControllerTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import io.restassured.http.ContentType; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -class AppointmentControllerTest extends TestBase { - - String userToken; - - @BeforeEach - void initToken() { - userToken = loginAsUser(); - } - - @Test - void should_create_and_list() { - given() - .header("Authorization", authHeader(userToken)) - .contentType(ContentType.JSON) - .body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"10:00\",\"endTime\":\"11:00\",\"note\":\"测试预约\"}") - .when() - .post("/api/v1/appointments") - .then() - .statusCode(200) - .body("id", notNullValue()) - .body("status", equalTo("PENDING")); - - given() - .header("Authorization", authHeader(userToken)) - .when() - .get("/api/v1/appointments") - .then() - .statusCode(200) - .body("$", not(empty())); - } - - @Test - void should_reject_conflict() { - given() - .header("Authorization", authHeader(userToken)) - .contentType(ContentType.JSON) - .body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"11:00\",\"endTime\":\"12:00\"}") - .when() - .post("/api/v1/appointments") - .then() - .statusCode(200); - - given() - .header("Authorization", authHeader(userToken)) - .contentType(ContentType.JSON) - .body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"11:00\",\"endTime\":\"12:00\"}") - .when() - .post("/api/v1/appointments") - .then() - .statusCode(409); - } - - @Test - void should_cancel_appointment() { - var id = given() - .header("Authorization", authHeader(userToken)) - .contentType(ContentType.JSON) - .body("{\"consultantId\":\"c-001\",\"date\":\"2026-12-10\",\"startTime\":\"14:00\",\"endTime\":\"15:00\"}") - .when() - .post("/api/v1/appointments") - .then() - .statusCode(200) - .extract().jsonPath().getString("id"); - - given() - .header("Authorization", authHeader(userToken)) - .contentType(ContentType.JSON) - .body("{\"reason\":\"测试取消\"}") - .when() - .put("/api/v1/appointments/{id}/cancel", id) - .then() - .statusCode(200); - } -} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AuthControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AuthControllerTest.java deleted file mode 100644 index c99a539..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/AuthControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import io.restassured.http.ContentType; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -class AuthControllerTest extends TestBase { - - @Test - void should_register_and_login() { - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"new@test.com\",\"password\":\"password123\",\"name\":\"新用户\"}") - .when() - .post("/api/v1/auth/register") - .then() - .statusCode(200) - .body("token", notNullValue()) - .body("user.email", equalTo("new@test.com")); - - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"new@test.com\",\"password\":\"password123\"}") - .when() - .post("/api/v1/auth/login") - .then() - .statusCode(200) - .body("token", notNullValue()); - } - - @Test - void should_fail_duplicate_email() { - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"dup@test.com\",\"password\":\"password123\",\"name\":\"用户1\"}") - .when() - .post("/api/v1/auth/register") - .then() - .statusCode(200); - - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"dup@test.com\",\"password\":\"password123\",\"name\":\"用户2\"}") - .when() - .post("/api/v1/auth/register") - .then() - .statusCode(400) - .body("errorCode", notNullValue()); - } - - @Test - void should_fail_wrong_password() { - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"fail@test.com\",\"password\":\"password123\",\"name\":\"用户\"}") - .when() - .post("/api/v1/auth/register") - .then() - .statusCode(200); - - given() - .contentType(ContentType.JSON) - .body("{\"email\":\"fail@test.com\",\"password\":\"wrongpass\"}") - .when() - .post("/api/v1/auth/login") - .then() - .statusCode(400); - } -} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java deleted file mode 100644 index d19b639..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - -class BusinessRuleControllerTest extends TestBase { - - @Test - void should_list_all_business_rules() { - given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .body("$", not(empty())) - .body("$", hasSize(7)); - } - - @Test - void should_contain_appointment_conflict_detection_rule() { - given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .body("ruleName", hasItem("appointment_conflict_detection")); - - assertThat(descriptionOf("appointment_conflict_detection"), not(isEmptyOrNullString())); - } - - @Test - void should_contain_auth_token_expiration_rule() { - given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .body("ruleName", hasItem("auth_token_expiration")); - } - - @Test - void should_expose_yaml_config_for_each_rule() { - given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .body("config", everyItem(notNullValue())) - .body("config.appointment.slot.minMinutes", everyItem(equalTo(30))) - .body("config.auth.token.expirationMs", everyItem(equalTo(86400000))); - } - - @Test - void should_access_without_token() { - given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .body("$", not(empty())); - } - - @Test - void should_expose_public_endpoints_as_json_array() { - Object publicEndpoints = authConfig().get("publicEndpoints"); - - assertThat(publicEndpoints, notNullValue()); - assertThat(publicEndpoints, instanceOf(List.class)); - - @SuppressWarnings("unchecked") - List endpoints = (List) publicEndpoints; - assertThat(endpoints, hasSize(5)); - assertThat(endpoints, hasItems("/api/v1/auth/**", "/api/v1/business-rules/**")); - for (Object endpoint : endpoints) { - assertThat((String) endpoint, startsWith("/api/v1/")); - } - } - - @Test - void should_expose_auth_scalar_config_without_type_drift() { - Map auth = authConfig(); - - Map password = child(auth, "password"); - Map token = child(auth, "token"); - - assertThat(((Number) password.get("minLength")).intValue(), is(8)); - assertThat(password.get("algorithm"), is("BCrypt")); - assertThat(((Number) token.get("expirationMs")).longValue(), is(86400000L)); - assertThat(token.get("algorithm"), is("HMAC-SHA256")); - } - - private String descriptionOf(String ruleName) { - List> rules = given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .extract().jsonPath().getList("$"); - return rules.stream() - .filter(rule -> ruleName.equals(rule.get("ruleName"))) - .map(rule -> (String) rule.get("description")) - .findFirst() - .orElse(null); - } - - @SuppressWarnings("unchecked") - private Map authConfig() { - List> rules = given() - .when() - .get("/api/v1/business-rules") - .then() - .statusCode(200) - .extract().jsonPath().getList("$"); - for (Map rule : rules) { - Object config = rule.get("config"); - if (!(config instanceof Map configMap)) continue; - Object auth = configMap.get("auth"); - if (auth instanceof Map authMap) { - return (Map) authMap; - } - } - throw new AssertionError("no rule exposes config.auth"); - } - - @SuppressWarnings("unchecked") - private Map child(Map parent, String key) { - Object value = parent.get(key); - assertThat(value, instanceOf(Map.class)); - return (Map) value; - } -} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/ConsultantControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/ConsultantControllerTest.java deleted file mode 100644 index 68371a2..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/ConsultantControllerTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -class ConsultantControllerTest extends TestBase { - - @Test - void should_list_consultants() { - given() - .when() - .get("/api/v1/consultants") - .then() - .statusCode(200) - .body("$", not(empty())); - } - - @Test - void should_return_slots() { - given() - .queryParam("date", "2026-12-01") - .when() - .get("/api/v1/consultants/c-001/slots") - .then() - .statusCode(200) - .body("$", not(empty())) - .body("[0].startTime", notNullValue()); - } - - @Test - void should_return_empty_for_invalid_consultant() { - given() - .queryParam("date", "2026-12-01") - .when() - .get("/api/v1/consultants/invalid-id/slots") - .then() - .statusCode(200) - .body("$", empty()); - } -} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java deleted file mode 100644 index 1c2dd73..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -class DataDictionaryControllerTest extends TestBase { - - @Test - void should_list_all_data_dictionary_types() { - given() - .when() - .get("/api/v1/data-dictionaries") - .then() - .statusCode(200) - .body("$", not(empty())) - .body("$", hasSize(5)) - .body("typeName", everyItem(not(isEmptyOrNullString()))) - .body("description", everyItem(not(isEmptyOrNullString()))) - .body("items", everyItem(hasSize(greaterThan(0)))); - } - - @Test - void should_get_data_dictionary_by_type() { - given() - .when() - .get("/api/v1/data-dictionaries/USER_ROLE") - .then() - .statusCode(200) - .body("typeName", equalTo("USER_ROLE")) - .body("description", not(isEmptyOrNullString())) - .body("items.code", hasItems("ROLE_USER", "ROLE_ADMIN")) - .body("items.description", everyItem(not(isEmptyOrNullString()))); - } - - @Test - void should_get_data_dictionary_by_type_ignoring_case() { - given() - .when() - .get("/api/v1/data-dictionaries/user_role") - .then() - .statusCode(200) - .body("typeName", equalTo("USER_ROLE")) - .body("items.code", hasItems("ROLE_USER", "ROLE_ADMIN")); - } - - @Test - void should_list_all_appointment_status_codes() { - given() - .when() - .get("/api/v1/data-dictionaries/APPOINTMENT_STATUS") - .then() - .statusCode(200) - .body("typeName", equalTo("APPOINTMENT_STATUS")) - .body("items.code", hasItems("PENDING", "CONFIRMED", "COMPLETED", "CANCELLED")); - } - - @Test - void should_fail_for_unknown_dictionary_type() { - given() - .when() - .get("/api/v1/data-dictionaries/NOT_EXIST") - .then() - .statusCode(400) - .body("errorCode", equalTo("PARAM_ERROR")) - .body("errorMessage", containsString("字典类型不存在")) - .body("data", nullValue()); - } -} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/HealthControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/HealthControllerTest.java new file mode 100644 index 0000000..40fa12f --- /dev/null +++ b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/HealthControllerTest.java @@ -0,0 +1,14 @@ +package com.consultation.adapter.rest; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HealthControllerTest { + + @Test + void should_return_up_when_get_health() { + var body = new HealthController().health(); + assertEquals("UP", body.get("status")); + } +} diff --git a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/UserControllerTest.java b/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/UserControllerTest.java deleted file mode 100644 index 16048ea..0000000 --- a/example-project/apps/backend/src/test/java/com/consultation/adapter/rest/UserControllerTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.consultation.adapter.rest; - -import com.consultation.TestBase; -import io.restassured.http.ContentType; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -class UserControllerTest extends TestBase { - - String token; - - @BeforeEach - void initToken() { - token = loginAsUser(); - } - - @Test - void should_get_profile() { - given() - .header("Authorization", authHeader(token)) - .when() - .get("/api/v1/users/me") - .then() - .statusCode(200) - .body("email", equalTo("test@test.com")) - .body("name", equalTo("测试用户")); - } - - @Test - void should_update_profile() { - given() - .header("Authorization", authHeader(token)) - .contentType(ContentType.JSON) - .body("{\"name\":\"更新姓名\",\"phone\":\"13900000000\"}") - .when() - .put("/api/v1/users/me") - .then() - .statusCode(200) - .body("name", equalTo("更新姓名")) - .body("phone", equalTo("13900000000")); - } - - @Test - void should_change_password() { - given() - .header("Authorization", authHeader(token)) - .contentType(ContentType.JSON) - .body("{\"oldPassword\":\"password123\",\"newPassword\":\"newpassword123\"}") - .when() - .put("/api/v1/users/me/password") - .then() - .statusCode(200); - } -} diff --git a/example-project/apps/backend/src/test/resources/application.yml b/example-project/apps/backend/src/test/resources/application.yml index f61e9b9..27f5c89 100644 --- a/example-project/apps/backend/src/test/resources/application.yml +++ b/example-project/apps/backend/src/test/resources/application.yml @@ -1,6 +1,4 @@ spring: - config: - import: "classpath:/business-rules/appointment.yml,classpath:/business-rules/auth.yml" datasource: url: jdbc:mysql://localhost:3306/consultation_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true username: root @@ -16,3 +14,6 @@ spring: jwt: secret: test-secret-key-for-mysql-tests-only expiration: 86400000 +business-rules: + public-endpoints: + - /api/v1/health diff --git a/example-project/apps/backend/src/test/resources/data.sql b/example-project/apps/backend/src/test/resources/data.sql index c726309..9a36e63 100644 --- a/example-project/apps/backend/src/test/resources/data.sql +++ b/example-project/apps/backend/src/test/resources/data.sql @@ -1,17 +1 @@ --- Seed admin user (password: password) -insert into user (id, email, password, name, phone, role, status, created_by, updated_by) -values ('admin-001', 'admin@test.com', - '$2a$10$4rDXdT56xLoF0LajF1fKRuZFxxdAd6rM9CuCcZdRrb/k7eRHMTKQq', - '管理员', '13800000000', 'ROLE_ADMIN', 'ACTIVE', 'admin-001', 'admin-001'); - --- Seed consultants -insert into consultant (id, name, title, bio, specialties, sort_order, created_by, updated_by) -values ('c-001', '张医生', '资深心理咨询师', '拥有15年心理咨询经验。', '焦虑症,抑郁症,人际关系', 1, 'admin-001', 'admin-001'), - ('c-002', '李律师', '企业法律顾问', '10年企业法律顾问经验。', '合同法,劳动法,公司治理', 2, 'admin-001', 'admin-001'), - ('c-003', '王教练', '职业规划导师', '帮助超过500人实现职业转型。', '职业规划,简历优化', 3, 'admin-001', 'admin-001'); - --- Seed branches -insert into branch (id, name, address, phone, status, created_by, updated_by) -values ('b-001', '朝阳咨询中心', '北京市朝阳区建国路88号', '010-88880001', 'ACTIVE', 'admin-001', 'admin-001'), - ('b-002', '海淀咨询中心', '北京市海淀区中关村大街66号', '010-88880002', 'ACTIVE', 'admin-001', 'admin-001'), - ('b-003', '浦东咨询中心', '上海市浦东新区陆家嘴路100号', '021-68880003', 'ACTIVE', 'admin-001', 'admin-001'); +-- Skeleton: no seed data. diff --git a/example-project/apps/backend/src/test/resources/schema.sql b/example-project/apps/backend/src/test/resources/schema.sql index ef4b196..64f28bd 100644 --- a/example-project/apps/backend/src/test/resources/schema.sql +++ b/example-project/apps/backend/src/test/resources/schema.sql @@ -1,72 +1 @@ -drop table if exists branch; -drop table if exists appointment; -drop table if exists consultant; -drop table if exists user; - -create table user ( - id varchar(64) not null primary key, - email varchar(128) not null, - password varchar(256) not null, - name varchar(64) not null, - phone varchar(20), - role varchar(20) not null default 'ROLE_USER', - status varchar(12) not null default 'ACTIVE', - deleted tinyint default 0 not null, - created_by varchar(64) not null, - created_time datetime default CURRENT_TIMESTAMP not null, - updated_by varchar(64) not null, - updated_time datetime default CURRENT_TIMESTAMP not null -); - -create unique index uk_user_email on user(email); - -create table consultant ( - id varchar(64) not null primary key, - name varchar(64) not null, - title varchar(128), - bio text, - specialties varchar(256), - avatar varchar(256), - branch_id varchar(64), - status varchar(12) not null default 'ACTIVE', - sort_order int default 0 not null, - created_by varchar(64) not null, - created_time datetime default CURRENT_TIMESTAMP not null, - updated_by varchar(64) not null, - updated_time datetime default CURRENT_TIMESTAMP not null -); - -create table appointment ( - id varchar(64) not null primary key, - user_id varchar(64) not null, - consultant_id varchar(64) not null, - branch_id varchar(64), - appointment_date date not null, - start_time varchar(10) not null, - end_time varchar(10) not null, - duration_minutes int not null, - status varchar(20) not null default 'PENDING', - note text, - cancel_reason varchar(256), - created_by varchar(64) not null, - created_time datetime default CURRENT_TIMESTAMP not null, - updated_by varchar(64) not null, - updated_time datetime default CURRENT_TIMESTAMP not null -); - -create index idx_appointment_user on appointment(user_id); -create index idx_appointment_consultant on appointment(consultant_id); -create index idx_appointment_date on appointment(appointment_date); -create unique index uk_appointment_slot on appointment(consultant_id, appointment_date, start_time); - -create table branch ( - id varchar(64) primary key, - name varchar(100) not null, - address varchar(255), - phone varchar(20), - status varchar(20) not null default 'ACTIVE', - created_by varchar(64), - created_time datetime not null default CURRENT_TIMESTAMP, - updated_by varchar(64), - updated_time datetime not null default CURRENT_TIMESTAMP -); +-- Skeleton: no business tables. Recreate via Flyway when implementing iteration1 features. diff --git a/example-project/apps/frontend/src/components/layout/AdminLayout.vue b/example-project/apps/frontend/src/components/layout/AdminLayout.vue deleted file mode 100644 index b8f51c3..0000000 --- a/example-project/apps/frontend/src/components/layout/AdminLayout.vue +++ /dev/null @@ -1,34 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/components/layout/AppHeader.vue b/example-project/apps/frontend/src/components/layout/AppHeader.vue deleted file mode 100644 index da3133d..0000000 --- a/example-project/apps/frontend/src/components/layout/AppHeader.vue +++ /dev/null @@ -1,37 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/components/layout/UserLayout.vue b/example-project/apps/frontend/src/components/layout/UserLayout.vue deleted file mode 100644 index 15782c4..0000000 --- a/example-project/apps/frontend/src/components/layout/UserLayout.vue +++ /dev/null @@ -1,10 +0,0 @@ - - - diff --git a/example-project/apps/frontend/src/router/index.ts b/example-project/apps/frontend/src/router/index.ts index 5242bce..86d6186 100644 --- a/example-project/apps/frontend/src/router/index.ts +++ b/example-project/apps/frontend/src/router/index.ts @@ -4,31 +4,6 @@ const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', name: 'home', component: () => import('@/views/home/HomePage.vue') }, - { path: '/login', name: 'login', component: () => import('@/views/auth/Login.vue') }, - { path: '/register', name: 'register', component: () => import('@/views/auth/Register.vue') }, - { - path: '/user', - component: () => import('@/components/layout/UserLayout.vue'), - children: [ - { path: '', redirect: '/user/dashboard' }, - { path: 'dashboard', component: () => import('@/views/user/Dashboard.vue') }, - { path: 'appointments', component: () => import('@/views/user/MyAppointments.vue') }, - { path: 'book', component: () => import('@/views/user/BookAppointment.vue') }, - { path: 'profile', component: () => import('@/views/user/Profile.vue') }, - ], - }, - { - path: '/admin', - component: () => import('@/components/layout/AdminLayout.vue'), - children: [ - { path: '', redirect: '/admin/dashboard' }, - { path: 'dashboard', component: () => import('@/views/admin/Dashboard.vue') }, - { path: 'appointments', component: () => import('@/views/admin/Appointments.vue') }, - { path: 'consultants', component: () => import('@/views/admin/Consultants.vue') }, - { path: 'users', component: () => import('@/views/admin/Users.vue') }, - { path: 'branches', component: () => import('@/views/admin/Branches.vue') }, - ], - }, ], }) diff --git a/example-project/apps/frontend/src/stores/auth.ts b/example-project/apps/frontend/src/stores/auth.ts index f7f646a..772feeb 100644 --- a/example-project/apps/frontend/src/stores/auth.ts +++ b/example-project/apps/frontend/src/stores/auth.ts @@ -1,35 +1,16 @@ import { defineStore } from 'pinia' import { ref, computed } from 'vue' -import type { AuthResponse, User } from '@/types' -import http from '@/utils/request' +/** Auth store shell — wire login/register when ACC is implemented. */ export const useAuthStore = defineStore('auth', () => { const token = ref(localStorage.getItem('token') || '') - const user = ref(JSON.parse(localStorage.getItem('user') || 'null')) const isLoggedIn = computed(() => !!token.value) - const isAdmin = computed(() => user.value?.role === 'ROLE_ADMIN') - - function setAuth(t: string, u: User) { - token.value = t; user.value = u - localStorage.setItem('token', t); localStorage.setItem('user', JSON.stringify(u)) - } - - async function login(email: string, password: string) { - const r = await http.post('/auth/login', { email, password }) - setAuth(r.data.token, r.data.user) - return r.data - } - - async function register(email: string, password: string, name: string, phone?: string) { - const r = await http.post('/auth/register', { email, password, name, phone }) - setAuth(r.data.token, r.data.user) - return r.data - } function logout() { - token.value = ''; user.value = null - localStorage.removeItem('token'); localStorage.removeItem('user') + token.value = '' + localStorage.removeItem('token') + localStorage.removeItem('user') } - return { token, user, isLoggedIn, isAdmin, login, register, logout } + return { token, isLoggedIn, logout } }) diff --git a/example-project/apps/frontend/src/types/index.ts b/example-project/apps/frontend/src/types/index.ts index e9540c3..80ef7a2 100644 --- a/example-project/apps/frontend/src/types/index.ts +++ b/example-project/apps/frontend/src/types/index.ts @@ -1,17 +1,5 @@ -export interface User { - id: string; email: string; name: string; phone: string; role: string; status: string +/** Shared frontend types — extend when implementing iteration1 features. */ + +export interface HealthResponse { + status: string } -export interface AuthResponse { token: string; user: User } -export interface Appointment { - id: string; userId: string; consultantId: string; branchId: string; - appointmentDate: string; startTime: string; endTime: string; - durationMinutes: number; status: string; note: string; cancelReason: string -} -export interface Consultant { - id: string; name: string; title: string; bio: string; specialties: string; - avatar: string; branchId: string; status: string; sortOrder: number -} -export interface Branch { - id: string; name: string; address: string; phone: string; status: string -} -export interface TimeSlot { startTime: string; endTime: string } diff --git a/example-project/apps/frontend/src/utils/date.ts b/example-project/apps/frontend/src/utils/date.ts deleted file mode 100644 index 0891402..0000000 --- a/example-project/apps/frontend/src/utils/date.ts +++ /dev/null @@ -1,9 +0,0 @@ -export function getWeekDates(): string[] { - const dates: string[] = [] - const today = new Date() - for (let i = 0; i < 7; i++) { - const d = new Date(today); d.setDate(d.getDate() + i) - dates.push(d.toISOString().split('T')[0]) - } - return dates -} diff --git a/example-project/apps/frontend/src/utils/request.ts b/example-project/apps/frontend/src/utils/request.ts index a3e8981..ff2ed32 100644 --- a/example-project/apps/frontend/src/utils/request.ts +++ b/example-project/apps/frontend/src/utils/request.ts @@ -14,10 +14,7 @@ http.interceptors.request.use(cfg => { http.interceptors.response.use( r => r, - e => { - if (e.response?.status === 401) { localStorage.removeItem('token'); localStorage.removeItem('user'); window.location.href = '/login' } - return Promise.reject(e) - } + e => Promise.reject(e) ) export default http diff --git a/example-project/apps/frontend/src/views/admin/Appointments.vue b/example-project/apps/frontend/src/views/admin/Appointments.vue deleted file mode 100644 index f7075be..0000000 --- a/example-project/apps/frontend/src/views/admin/Appointments.vue +++ /dev/null @@ -1,31 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/admin/Branches.vue b/example-project/apps/frontend/src/views/admin/Branches.vue deleted file mode 100644 index 383c6b4..0000000 --- a/example-project/apps/frontend/src/views/admin/Branches.vue +++ /dev/null @@ -1,65 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/admin/Consultants.vue b/example-project/apps/frontend/src/views/admin/Consultants.vue deleted file mode 100644 index 673c01e..0000000 --- a/example-project/apps/frontend/src/views/admin/Consultants.vue +++ /dev/null @@ -1,29 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/admin/Dashboard.vue b/example-project/apps/frontend/src/views/admin/Dashboard.vue deleted file mode 100644 index edc99eb..0000000 --- a/example-project/apps/frontend/src/views/admin/Dashboard.vue +++ /dev/null @@ -1,28 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/admin/Users.vue b/example-project/apps/frontend/src/views/admin/Users.vue deleted file mode 100644 index b5e67ea..0000000 --- a/example-project/apps/frontend/src/views/admin/Users.vue +++ /dev/null @@ -1,32 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/auth/Login.vue b/example-project/apps/frontend/src/views/auth/Login.vue deleted file mode 100644 index c9835a4..0000000 --- a/example-project/apps/frontend/src/views/auth/Login.vue +++ /dev/null @@ -1,46 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/auth/Register.vue b/example-project/apps/frontend/src/views/auth/Register.vue deleted file mode 100644 index 8cc782f..0000000 --- a/example-project/apps/frontend/src/views/auth/Register.vue +++ /dev/null @@ -1,44 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/home/HomePage.vue b/example-project/apps/frontend/src/views/home/HomePage.vue index 8a79633..4494817 100644 --- a/example-project/apps/frontend/src/views/home/HomePage.vue +++ b/example-project/apps/frontend/src/views/home/HomePage.vue @@ -1,39 +1,25 @@ - - diff --git a/example-project/apps/frontend/src/views/user/BookAppointment.vue b/example-project/apps/frontend/src/views/user/BookAppointment.vue deleted file mode 100644 index 34124c4..0000000 --- a/example-project/apps/frontend/src/views/user/BookAppointment.vue +++ /dev/null @@ -1,96 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/user/Dashboard.vue b/example-project/apps/frontend/src/views/user/Dashboard.vue deleted file mode 100644 index 4cc3cfa..0000000 --- a/example-project/apps/frontend/src/views/user/Dashboard.vue +++ /dev/null @@ -1,41 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/user/MyAppointments.vue b/example-project/apps/frontend/src/views/user/MyAppointments.vue deleted file mode 100644 index 6e723a9..0000000 --- a/example-project/apps/frontend/src/views/user/MyAppointments.vue +++ /dev/null @@ -1,69 +0,0 @@ - - - - - diff --git a/example-project/apps/frontend/src/views/user/Profile.vue b/example-project/apps/frontend/src/views/user/Profile.vue deleted file mode 100644 index 61e2b69..0000000 --- a/example-project/apps/frontend/src/views/user/Profile.vue +++ /dev/null @@ -1,56 +0,0 @@ - - - - - diff --git a/example-project/docs/facts/README.md b/example-project/docs/facts/README.md index 798bb3f..8122119 100644 --- a/example-project/docs/facts/README.md +++ b/example-project/docs/facts/README.md @@ -2,15 +2,17 @@ 描述系统 **当前真实状态** 的文档,随代码同步更新。 +> 当前为 **工程空壳 as-built**。目标需求:`docs/features/iteration1/`。 + | 位置 | 内容 | |---|---| -| 本目录根 | 可从代码校准的技术事实:`api.yaml`、`db-schema.md`、`domain-model.md` | +| 本目录根 | `api.yaml`、`db-schema.md`、`domain-model.md` | | [`business/`](./business/) | 业务事实(流程等) | | [`tech-topic/`](./tech-topic/) | 技术专题 / ADR / 实现说明 | ## 现有文档 -- [api.yaml](./api.yaml) — API 接口定义 -- [db-schema.md](./db-schema.md) — 数据库规格 -- [domain-model.md](./domain-model.md) — 领域模型 -- [business/booking-flow.md](./business/booking-flow.md) — 预约业务流程 +- [api.yaml](./api.yaml) — API(仅 health) +- [db-schema.md](./db-schema.md) — 数据库(无业务表) +- [domain-model.md](./domain-model.md) — 领域模型(无业务聚合) +- [business/](./business/) — 业务事实目录(待补充) diff --git a/example-project/docs/facts/api.yaml b/example-project/docs/facts/api.yaml index 239dfc9..5f5ac7a 100644 --- a/example-project/docs/facts/api.yaml +++ b/example-project/docs/facts/api.yaml @@ -1,406 +1,22 @@ -openapi: "3.0.3" +openapi: 3.0.0 info: - title: 咨询预约平台 API - version: 0.1.0 - + title: Consultation Platform API (skeleton) + version: 0.0.0 + description: | + 业务 API 尚未实现。目标需求见 docs/features/iteration1/。 + 当前仅保留健康探针。 paths: - /api/v1/auth/register: - post: - tags: [Auth] - summary: 用户注册 - requestBody: - required: true - content: - application/json: - schema: - type: object - required: [email, password, name] - properties: - email: { type: string, format: email } - password: { type: string, minLength: 8 } - name: { type: string } - phone: { type: string } - responses: - "200": { description: 注册成功, content: { application/json: { schema: { $ref: "#/components/schemas/AuthResponse" } } } } - "400": { $ref: "#/components/responses/Error400" } - - /api/v1/auth/login: - post: - tags: [Auth] - summary: 用户登录 - requestBody: - required: true - content: - application/json: - schema: - type: object - required: [email, password] - properties: - email: { type: string, format: email } - password: { type: string } - responses: - "200": { description: 登录成功, content: { application/json: { schema: { $ref: "#/components/schemas/AuthResponse" } } } } - "400": { $ref: "#/components/responses/Error400" } - - /api/v1/home/info: + /api/v1/health: get: - tags: [Home] - summary: 首页信息 + summary: 存活探针 responses: - "200": { description: 首页内容, content: { application/json: { schema: { type: object, properties: { title: { type: string }, description: { type: string } } } } } } - - /api/v1/users/me: - get: - tags: [User] - summary: 获取个人资料 - security: [{ BearerAuth: [] }] - responses: - "200": { description: 用户信息, content: { application/json: { schema: { $ref: "#/components/schemas/UserResponse" } } } } - "401": { $ref: "#/components/responses/Error401" } - put: - tags: [User] - summary: 更新个人资料 - security: [{ BearerAuth: [] }] - requestBody: - content: { application/json: { schema: { type: object, properties: { name: { type: string }, phone: { type: string } } } } } - responses: - "200": { description: 更新后的用户信息, content: { application/json: { schema: { $ref: "#/components/schemas/UserResponse" } } } } - - /api/v1/users/me/password: - put: - tags: [User] - summary: 修改密码 - security: [{ BearerAuth: [] }] - requestBody: - required: true - content: - application/json: - schema: - type: object - required: [oldPassword, newPassword] - properties: - oldPassword: { type: string } - newPassword: { type: string, minLength: 8 } - responses: - "200": { description: 密码修改成功 } - "400": { $ref: "#/components/responses/Error400" } - - /api/v1/consultants: - get: - tags: [Consultant] - summary: 获取咨询师列表 - responses: - "200": { description: 咨询师列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/ConsultantResponse" } } } } } - - /api/v1/consultants/{id}/slots: - get: - tags: [Consultant] - summary: 获取咨询师可预约时间段 - parameters: - - name: id - in: path - required: true - schema: { type: string } - - name: date - in: query - required: true - schema: { type: string, format: date } - responses: - "200": { description: 可用时间段列表, content: { application/json: { schema: { type: array, items: { type: object, properties: { startTime: { type: string }, endTime: { type: string } } } } } } } - - /api/v1/appointments: - get: - tags: [Appointment] - summary: 获取我的预约列表 - security: [{ BearerAuth: [] }] - responses: - "200": { description: 预约列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/AppointmentResponse" } } } } } - post: - tags: [Appointment] - summary: 创建预约 - security: [{ BearerAuth: [] }] - requestBody: - required: true - content: - application/json: - schema: - type: object - required: [consultantId, date, startTime, endTime] - properties: - consultantId: { type: string } - branchId: { type: string } - date: { type: string, format: date } - startTime: { type: string } - endTime: { type: string } - note: { type: string } - responses: - "200": { description: 创建成功, content: { application/json: { schema: { $ref: "#/components/schemas/AppointmentResponse" } } } } - "409": { $ref: "#/components/responses/Error409" } - - /api/v1/appointments/{id}: - get: - tags: [Appointment] - summary: 获取预约详情 - security: [{ BearerAuth: [] }] - parameters: - - name: id - in: path - required: true - schema: { type: string } - responses: - "200": { description: 预约详情, content: { application/json: { schema: { $ref: "#/components/schemas/AppointmentResponse" } } } } - - /api/v1/appointments/{id}/cancel: - put: - tags: [Appointment] - summary: 取消预约 - security: [{ BearerAuth: [] }] - parameters: - - name: id - in: path - required: true - schema: { type: string } - requestBody: - content: { application/json: { schema: { type: object, properties: { reason: { type: string } } } } } - responses: - "200": { description: 取消成功 } - "409": { $ref: "#/components/responses/Error409" } - - /admin/dashboard: - get: - tags: [Admin] - summary: 管理仪表盘 - security: [{ BearerAuth: [] }] - responses: - "200": { description: 统计数据, content: { application/json: { schema: { type: object, properties: { totalUsers: { type: integer }, totalConsultants: { type: integer }, totalAppointments: { type: integer }, pendingAppointments: { type: integer }, totalBranches: { type: integer } } } } } } - - /admin/users: - get: - tags: [Admin] - summary: 用户列表(管理员) - security: [{ BearerAuth: [] }] - responses: - "200": { description: 用户列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/UserResponse" } } } } } - - /admin/users/{id}/toggle-status: - put: - tags: [Admin] - summary: 启用/禁用用户 - security: [{ BearerAuth: [] }] - parameters: - - name: id - in: path - required: true - schema: { type: string } - responses: - "200": { description: 操作成功 } - - /admin/consultants: - get: - tags: [Admin] - summary: 咨询师列表(管理员) - security: [{ BearerAuth: [] }] - responses: - "200": { description: 咨询师列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/ConsultantResponse" } } } } } - - /admin/appointments: - get: - tags: [Admin] - summary: 预约列表(管理员,全量) - security: [{ BearerAuth: [] }] - responses: - "200": { description: 预约列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/AppointmentResponse" } } } } } - - /admin/branches: - get: - tags: [Admin] - summary: 网点列表 - security: [{ BearerAuth: [] }] - responses: - "200": { description: 网点列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/BranchResponse" } } } } } - post: - tags: [Admin] - summary: 创建网点 - security: [{ BearerAuth: [] }] - requestBody: - required: true - content: - application/json: - schema: - type: object - required: [name] - properties: - name: { type: string } - address: { type: string } - phone: { type: string } - responses: - "200": { description: 创建成功, content: { application/json: { schema: { $ref: "#/components/schemas/BranchResponse" } } } } - - /admin/branches/{id}: - put: - tags: [Admin] - summary: 更新网点 - security: [{ BearerAuth: [] }] - parameters: - - name: id - in: path - required: true - schema: { type: string } - requestBody: - content: - application/json: - schema: - type: object - properties: - name: { type: string } - address: { type: string } - phone: { type: string } - responses: - "200": { description: 更新成功 } - delete: - tags: [Admin] - summary: 删除网点 - security: [{ BearerAuth: [] }] - parameters: - - name: id - in: path - required: true - schema: { type: string } - responses: - "200": { description: 删除成功 } - - /api/v1/data-dictionaries: - get: - tags: [DataDictionary] - summary: 获取所有数据字典类型列表 - responses: - "200": { description: 字典类型列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/DataDictionaryResponse" } } } } } - - /api/v1/data-dictionaries/{type}: - get: - tags: [DataDictionary] - summary: 获取指定字典类型的条目列表 - parameters: - - name: type - in: path - required: true - schema: { type: string } - responses: - "200": { description: 字典条目列表, content: { application/json: { schema: { type: array, items: { type: object, properties: { code: { type: string }, description: { type: string } } } } } } } - - /api/v1/business-rules: - get: - tags: [BusinessRule] - summary: 获取所有业务规则 - responses: - "200": { description: 业务规则列表, content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/BusinessRuleResponse" } } } } } - -components: - securitySchemes: - BearerAuth: - type: http - scheme: bearer - bearerFormat: JWT - - schemas: - UserResponse: - type: object - properties: - id: { type: string } - email: { type: string } - name: { type: string } - phone: { type: string } - role: { type: string, enum: [ROLE_USER, ROLE_ADMIN] } - status: { type: string, enum: [ACTIVE, DISABLED] } - - AuthResponse: - type: object - properties: - token: { type: string } - user: { $ref: "#/components/schemas/UserResponse" } - - ConsultantResponse: - type: object - properties: - id: { type: string } - name: { type: string } - title: { type: string } - bio: { type: string } - specialties: { type: string } - avatar: { type: string } - branchId: { type: string } - status: { type: string, enum: [ACTIVE, DISABLED] } - sortOrder: { type: integer } - - AppointmentResponse: - type: object - properties: - id: { type: string } - userId: { type: string } - consultantId: { type: string } - branchId: { type: string } - appointmentDate: { type: string, format: date } - startTime: { type: string } - endTime: { type: string } - durationMinutes: { type: integer } - status: { type: string, enum: [PENDING, CONFIRMED, COMPLETED, CANCELLED] } - note: { type: string } - cancelReason: { type: string } - - BranchResponse: - type: object - properties: - id: { type: string } - name: { type: string } - address: { type: string } - phone: { type: string } - status: { type: string, enum: [ACTIVE, DISABLED] } - - DataDictionaryResponse: - type: object - properties: - typeName: { type: string } - description: { type: string } - items: - type: array - items: - type: object - properties: - code: { type: string } - description: { type: string } - - BusinessRuleResponse: - type: object - properties: - ruleName: { type: string } - description: { type: string } - config: { type: object } - - ErrorResponse: - type: object - properties: - errorCode: { type: string } - errorMessage: { type: string } - data: { type: object, nullable: true } - - responses: - Error400: - description: 请求参数错误 - content: - application/json: - schema: { $ref: "#/components/schemas/ErrorResponse" } - Error401: - description: 未授权 - content: - application/json: - schema: { $ref: "#/components/schemas/ErrorResponse" } - Error404: - description: 资源不存在 - content: - application/json: - schema: { $ref: "#/components/schemas/ErrorResponse" } - Error409: - description: 业务冲突 - content: - application/json: - schema: { $ref: "#/components/schemas/ErrorResponse" } + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: UP diff --git a/example-project/docs/facts/business/README.md b/example-project/docs/facts/business/README.md index 8e89aa3..8f0083a 100644 --- a/example-project/docs/facts/business/README.md +++ b/example-project/docs/facts/business/README.md @@ -2,14 +2,10 @@ 存放与业务语义直接相关的事实文档:流程、业务侧说明等。 -与 `../` 根目录的技术事实(API / 库表 / 领域模型)以及 `../tech-topic/` 技术专题区分开: +> 旧示例业务文档已清除。实现 iteration1 后在此补充(或从 spec 同步关键流程)。 | 目录 | 内容 | |---|---| | `docs/facts/` | 可从代码校准的技术事实 | | `docs/facts/tech-topic/` | 技术专题 / ADR / 实现说明 | | `docs/facts/business/` | 业务事实(本目录) | - -## 现有文档 - -- [booking-flow.md](./booking-flow.md) — 预约业务流程 diff --git a/example-project/docs/facts/business/booking-flow.md b/example-project/docs/facts/business/booking-flow.md deleted file mode 100644 index 3c0a429..0000000 --- a/example-project/docs/facts/business/booking-flow.md +++ /dev/null @@ -1,100 +0,0 @@ -# 预约业务流程事实 - -## 1. 角色定义 - -| 角色 | 说明 | 系统表示 | -|------|------|----------| -| 普通用户(访客) | 未登录,可浏览首页与咨询师列表 | 无认证 / ROLE_USER | -| 注册用户 | 已登录,可预约、查看/取消自己的预约、编辑资料 | ROLE_USER | -| 管理员 | 已登录,可查看仪表盘统计、管理用户/咨询师/预约/网点 | ROLE_ADMIN | - -## 2. 预约流程(4 步) - -``` -Step 1: 选择咨询师 - - 系统展示所有 ACTIVE 状态的咨询师,按 sortOrder 升序 - - 用户点击选中一个 - -Step 2: 选择日期 - - 系统展示未来 7 天(含今日)的日期按钮 - - 日期连续,无间隔 - - 用户点击选中一个 - -Step 3: 选择时间 - - 系统根据选中的咨询师 + 日期,查询可用时段 - - 可用时段 = 09:00-18:00 内,每小时一个 slot(09:00, 10:00, ..., 17:00) - - 排除已存在非取消状态的预约 - - 用户点击选中一个 - -Step 4: 确认预约 - - 用户可填写备注(选填) - - 提交后系统创建预约,状态为 PENDING(待确认) - - 系统检查同一咨询师、同一日期、同一时段是否已有非取消预约 → 冲突则拒绝(409) -``` - -## 3. 预约状态机 - -``` -PENDING ──► CONFIRMED ──► COMPLETED - │ │ - └──────┬───────┘ - ▼ - CANCELLED -``` - -| 状态 | 含义 | 可操作 | -|------|------|--------| -| PENDING | 待确认(用户已提交,管理员未确认) | 取消 | -| CONFIRMED | 已确认(管理员已确认) | 取消、完成 | -| COMPLETED | 已完成(终态) | 无 | -| CANCELLED | 已取消(终态) | 无 | - -注:从 PENDING 和 CONFIRMED 可取消,取消时需要填写原因。 - -## 4. 业务规则 - -### 预约相关 - -| 规则 | 描述 | 实施方式 | -|------|------|----------| -| 冲突检测 | 同一咨询师同一时段不可重复预约 | `uk_appointment_slot` 唯一索引 + `AppointmentConflictService` | -| 时段间隔 | 预约时段间隔为 60 分钟 | 前端 time slot 按 1h 步进,后端 slot.intervalMinutes = 60 | -| 可用时段 | 可预约时段为 09:00-18:00 | 前端展示 09:00-17:00,后端 slot.available.start/end | -| 取消窗口 | PENDING 和 CONFIRMED 状态可取消 | `Appointment.canCancel()` 守卫方法 | - -### 认证相关 - -| 规则 | 描述 | 实施方式 | -|------|------|----------| -| 密码最小长度 | 密码最少 8 位 | 前端 + 后端校验 | -| JWT 有效期 | JWT 有效期 24 小时 | `jwt.expiration=86400000` | -| 密码算法 | 密码使用 BCrypt 加密 | `PasswordService` → `BCryptPasswordEncoder` | - -## 5. 前台 vs 后台功能划分 - -### 前台(/user/*,需 ROLE_USER) - -| 页面 | 功能 | -|------|------| -| 仪表盘 | 展示本人预约统计:总预约数、待确认数、已完成数 | -| 预约管理 | 列出本人预约,可取消 PENDING/CONFIRMED 状态的预约 | -| 预约咨询 | 4 步预约流程 | -| 个人中心 | 编辑姓名、手机号;修改密码 | - -### 后台(/admin/*,需 ROLE_ADMIN) - -| 页面 | 功能 | -|------|------| -| 仪表盘 | 全局统计:用户数、咨询师数、总预约数、待确认数、网点数 | -| 用户管理 | 列出所有用户,可启用/禁用用户 | -| 咨询师管理 | 列出所有咨询师 | -| 预约管理 | 列出所有预约 | -| 网点管理 | CRUD 网点(新增、编辑、删除) | - -## 6. 种子数据 - -| 类型 | 数据 | -|------|------| -| 管理员账号 | admin@test.com / password | -| 咨询师 | 张医生(资深心理咨询师)、李律师(法律顾问)、王教练(职业规划师) | -| 网点 | 朝阳咨询中心、海淀咨询中心、浦东咨询中心 | diff --git a/example-project/docs/facts/db-schema.md b/example-project/docs/facts/db-schema.md index 97f2367..9c8de18 100644 --- a/example-project/docs/facts/db-schema.md +++ b/example-project/docs/facts/db-schema.md @@ -1,77 +1,9 @@ -# 数据库设计 +# 数据库规格 -> 所有表使用 InnoDB 引擎,字符集 utf8mb4,排序 utf8mb4_bin。 +> 当前为工程空壳:**无业务表**。 +> 目标需求:`docs/features/iteration1/`。实现各 feature 时通过 Flyway 新增表,并同步本文档。 -## 公共字段 +## 迁移 -| 字段 | 类型 | 说明 | -|------|------|------| -| created_by | VARCHAR(64) | 创建者 ID | -| created_time | DATETIME | 创建时间,默认 CURRENT_TIMESTAMP | -| updated_by | VARCHAR(64) | 最后修改者 ID | -| updated_time | DATETIME | 最后修改时间,默认 CURRENT_TIMESTAMP,ON UPDATE 自动更新 | - -## user — 用户表 - -| 字段 | 类型 | 约束 | 说明 | -|------|------|------|------| -| id | VARCHAR(64) | PK | UUID 主键 | -| email | VARCHAR(100) | UNIQUE, NOT NULL | 邮箱 | -| password | VARCHAR(255) | NOT NULL | BCrypt 加密密码 | -| name | VARCHAR(50) | NOT NULL | 姓名 | -| phone | VARCHAR(20) | | 手机号 | -| role | VARCHAR(20) | NOT NULL, DEFAULT 'ROLE_USER' | 角色 | -| status | VARCHAR(20) | NOT NULL, DEFAULT 'ACTIVE' | 状态 | - -**索引**:`uk_user_email` UNIQUE on (email) - -## consultant — 咨询师表 - -| 字段 | 类型 | 约束 | 说明 | -|------|------|------|------| -| id | VARCHAR(64) | PK | UUID 主键 | -| name | VARCHAR(50) | NOT NULL | 姓名 | -| title | VARCHAR(100) | NOT NULL | 职称 | -| bio | TEXT | | 简介 | -| specialties | VARCHAR(255) | | 专长领域 | -| avatar | VARCHAR(255) | | 头像 URL | -| branch_id | VARCHAR(64) | FK → branch(id) | 所属网点 | -| status | VARCHAR(20) | NOT NULL, DEFAULT 'ACTIVE' | 状态 | -| sort_order | INT | NOT NULL, DEFAULT 0 | 排序权重 | - -## appointment — 预约表 - -| 字段 | 类型 | 约束 | 说明 | -|------|------|------|------| -| id | VARCHAR(64) | PK | UUID 主键 | -| user_id | VARCHAR(64) | FK → user(id) | 预约用户 | -| consultant_id | VARCHAR(64) | FK → consultant(id) | 咨询师 | -| branch_id | VARCHAR(64) | FK → branch(id) | 所属网点 | -| appointment_date | DATE | NOT NULL | 预约日期 | -| start_time | VARCHAR(5) | NOT NULL | 开始时间 (HH:mm) | -| end_time | VARCHAR(5) | NOT NULL | 结束时间 (HH:mm) | -| duration_minutes | INT | NOT NULL | 时长(分钟) | -| status | VARCHAR(20) | NOT NULL, DEFAULT 'PENDING' | 状态 | -| note | VARCHAR(500) | | 备注 | -| cancel_reason | VARCHAR(200) | | 取消原因 | - -**索引**: -- `uk_appointment_slot` UNIQUE on (consultant_id, appointment_date, start_time) -- `idx_user_id` on (user_id) -- `idx_consultant_date` on (consultant_id, appointment_date) - -## branch — 网点表 - -| 字段 | 类型 | 约束 | 说明 | -|------|------|------|------| -| id | VARCHAR(64) | PK | UUID 主键 | -| name | VARCHAR(100) | NOT NULL | 网点名称 | -| address | VARCHAR(255) | | 地址 | -| phone | VARCHAR(20) | | 电话 | -| status | VARCHAR(20) | NOT NULL, DEFAULT 'ACTIVE' | 状态 | - -## 表关系图 - -``` -user (1) ──→ (N) appointment (N) ←── (1) consultant (N) ←── (1) branch -``` +- 目录:`apps/backend/src/main/resources/db/migration/` +- 现状:无 migration 脚本(仅占位) diff --git a/example-project/docs/facts/domain-model.md b/example-project/docs/facts/domain-model.md index 56669f6..59a170e 100644 --- a/example-project/docs/facts/domain-model.md +++ b/example-project/docs/facts/domain-model.md @@ -1,107 +1,13 @@ -# 领域模型设计 +# 领域模型 -> 本文档描述咨询预约平台的领域模型事实(as-built)。 +> 当前为工程空壳:**无业务聚合**。 +> 目标需求:`docs/features/iteration1/`(ACC~PLT)。按 feature plan 落地后回写本文档。 -## 聚合根 (Aggregate Root) +## 平台骨架(非业务聚合) -### User - -| 字段 | 类型 | 说明 | -|------|------|------| -| id | String | UUID | -| email | String | 邮箱(登录名),唯一 | -| password | String | BCrypt 编码 | -| name | String | 姓名 | -| phone | String | 手机号 | -| role | UserRole | ROLE_USER / ROLE_ADMIN | -| status | UserStatus | ACTIVE / DISABLED | - -**方法**: -- `isAdmin()` — role == ROLE_ADMIN -- `isActive()` — status == ACTIVE - -### Consultant - -| 字段 | 类型 | 说明 | -|------|------|------| -| id | String | UUID | -| name | String | 姓名 | -| title | String | 职称 | -| bio | String | 简介 | -| specialties | String | 专长(逗号分隔) | -| avatar | String | 头像 URL | -| branchId | String | 所属网点 ID | -| status | ConsultantStatus | ACTIVE / DISABLED | -| sortOrder | int | 排序权重 | - -**内联枚举**:`ConsultantStatus { ACTIVE, DISABLED }` - -**方法**: -- `isAvailable()` — status == ACTIVE - -### Appointment - -| 字段 | 类型 | 说明 | -|------|------|------| -| id | String | UUID | -| userId | String | 预约用户 ID | -| consultantId | String | 咨询师 ID | -| branchId | String | 网点 ID(可选) | -| appointmentDate | LocalDate | 预约日期 | -| startTime | String | 开始时间 HH:mm | -| endTime | String | 结束时间 HH:mm | -| durationMinutes | int | 时长 | -| status | AppointmentStatus | PENDING / CONFIRMED / COMPLETED / CANCELLED | -| note | String | 用户备注 | -| cancelReason | String | 取消原因 | - -**方法**: -- `isOwnedBy(userId)` — 判断是否属于该用户 -- `canCancel()` — status 不是 COMPLETED 也不是 CANCELLED - -### Branch - -| 字段 | 类型 | 说明 | -|------|------|------| -| id | String | UUID | -| name | String | 网点名称 | -| address | String | 地址 | -| phone | String | 电话 | -| status | BranchStatus | ACTIVE / DISABLED | - -**内联枚举**:`BranchStatus { ACTIVE, DISABLED }` - -## 值对象 (Value Object) - -| 类 | 字段 | 说明 | -|----|------|------| -| UserRole | ROLE_USER, ROLE_ADMIN | 用户角色枚举 | -| UserStatus | ACTIVE, DISABLED | 用户状态枚举 | -| AppointmentStatus | PENDING, CONFIRMED, COMPLETED, CANCELLED | 预约状态枚举 | -| TimeSlot | date, startTime, endTime | 时间段 VO,用于冲突检测 | - -## 领域服务 (Domain Service) - -| 服务 | 方法 | 说明 | -|------|------|------| -| PasswordService | encode(raw), matches(raw, encoded) | 密码编码/校验接口(infrastructure 实现 BCrypt) | -| AppointmentConflictService | validateNoConflict(existing, requested) | 校验同一咨询师同一时段无冲突预约 | - -## 仓储接口 (Repository) - -| 接口 | 核心方法 | 说明 | -|------|----------|------| -| UserRepository | findById, findByEmail, findAll, save, update, existsByEmail | 用户持久化 | -| ConsultantRepository | findById, findAllActive, findAll, save, update, deleteById, count | 咨询师持久化 | -| AppointmentRepository | findById, findByUserId, findByConsultantIdAndDate, findAll, save, update, count, countByStatus, countByUserId | 预约持久化 | -| BranchRepository | findById, findAll, save, update, deleteById, count | 网点持久化 | - -## 聚合关系 - -``` -User (1) ──→ (N) Appointment (N) ←── (1) Consultant (N) ←── (1) Branch -``` - -- User 创建 Appointment,Appointment 关联一个 User 和一个 Consultant -- Consultant 属于一个 Branch -- Branch 独立创建/停用,Consultant 依赖 Branch 存在 +| 组件 | 说明 | +|------|------| +| JWT / UserContext | 无状态鉴权骨架,待 ACC 接入登录签发 | +| IBusinessRule / BusinessRuleConfig | 业务规则框架空注册 | +| DataDictionary* | 数据字典框架类型,暂无注册枚举 | +| PasswordService | 密码编码接口(BCrypt 实现) | diff --git a/example-project/docs/facts/tech-topic/businessrule.md b/example-project/docs/facts/tech-topic/businessrule.md index b16dd57..7b68db1 100644 --- a/example-project/docs/facts/tech-topic/businessrule.md +++ b/example-project/docs/facts/tech-topic/businessrule.md @@ -1,44 +1,6 @@ -# 业务规则清单(事实方案) +# 业务规则 -> 所有业务规则通过 `IBusinessRule` 接口定义,可通过 `GET /api/v1/business-rules` 动态查询。 -> 规则配置存储在 `resources/business-rules/*.yml` 中。 +> 空壳:示例规则已清除。框架类型保留(`IBusinessRule` / `BusinessRuleConfig` / `BusinessRuleProvider`)。 +> 实现 iteration1 时按 `docs/standards/business-rule.md` 注册规则并回写本文档。 -## 认证规则 - -| 规则名 | 描述 | 当前值 | 配置路径 | -|--------|------|--------|----------| -| auth.password.minLength | 密码最小长度 | 8 | `auth.yml` → password.minLength | -| auth.token.expirationMs | JWT Token 有效期(毫秒) | 86400000 (24h) | `auth.yml` → token.expirationMs | -| auth.password.algorithm | 密码加密算法 | BCrypt | `auth.yml` → password.algorithm | - -> 认证规则的取值来自 `business-rules/auth.yml`,通过 `GET /api/v1/business-rules` -> 的 `config.auth` 子树对外暴露(结构见 `BusinessRuleConfig.AuthConfig`)。 -> 运行时真正生效的 JWT 有效期取 `application.yml` → `jwt.expiration`(`JwtTokenProvider` 读取), -> 密码加密算法为 `PasswordServiceImpl` 里的 `BCryptPasswordEncoder`; -> 这两处当前与 YAML 取值一致,改动时需同步。 - -## 预约规则 - -| 规则名 | 描述 | 当前值 | 代码位置 | -|--------|------|--------|----------| -| appointment.conflict.detection | 同一咨询师同一时段不可重复预约 | 唯一索引 + 代码校验 | AppointmentConflictService + uk_appointment_slot | -| appointment.slot.minMinutes | 最短预约时长 | 30 (implicit) | TimeSlot 业务约定 | -| appointment.slot.maxMinutes | 最长预约时长 | 120 (implicit) | TimeSlot 业务约定 | -| appointment.available.start | 每日可预约开始时间 | 09:00 | ConsultantService.getAvailableSlots | -| appointment.available.end | 每日可预约结束时间 | 18:00 | ConsultantService.getAvailableSlots | -| appointment.slot.intervalMinutes | 时间段间隔 | 60 | ConsultantService.getAvailableSlots | - -## 管理规则 - -| 规则名 | 描述 | 当前值 | 代码位置 | -|--------|------|--------|----------| -| admin.access.role | 管理后台权限角色 | ROLE_ADMIN | SecurityConfig + JwtAuthenticationFilter | -| user.status.toggle | 用户启用/停用 | 允许,不可操作自身 | AdminService.toggleUserStatus | -| branch.delete.guard | 删除网点前检查关联咨询师 | 暂未实现 | AdminService (待补充) | - -## 字典规则 - -| 规则名 | 描述 | 当前值 | 代码位置 | -|--------|------|----------|----------| -| data.dictionary.queryable | 数据字典可通过 API 查询 | 所有注册的 DataDictionaryType | DataDictionaryController (Phase 3) | -| enum.self.describing | 所有业务枚举实现 Description 接口 | 提供 getCode() / getDescription() | 各 enum 文件 (Phase 3) | +当前注册规则:**无**。 diff --git a/example-project/docs/facts/tech-topic/data-dict.md b/example-project/docs/facts/tech-topic/data-dict.md index cf867d0..47ad045 100644 --- a/example-project/docs/facts/tech-topic/data-dict.md +++ b/example-project/docs/facts/tech-topic/data-dict.md @@ -1,62 +1,6 @@ -# 数据字典清单(事实方案) +# 数据字典 -> 所有枚举类型均实现 `Description` 接口,可通过 `GET /api/v1/data-dictionaries/{type}` 动态查询。 +> 空壳:示例字典枚举已清除。框架类型保留(`Description` / `DataDictionaryType` / `DataDictionaryUtil`)。 +> 实现 iteration1 时注册字典并回写本文档。 -## UserRole — 用户角色 - -| Code | 描述 | 说明 | -|------|------|------| -| ROLE_USER | 普通用户 | 默认角色,可预约咨询 | -| ROLE_ADMIN | 管理员 | 可访问管理后台 | - -## UserStatus — 用户状态 - -| Code | 描述 | 说明 | -|------|------|------| -| ACTIVE | 正常 | 可用 | -| DISABLED | 已停用 | 不可登录和操作 | - -## AppointmentStatus — 预约状态 - -| Code | 描述 | 业务含义 | -|------|------|----------| -| PENDING | 待确认 | 初始状态,等待咨询师确认 | -| CONFIRMED | 已确认 | 咨询师已确认,预约生效 | -| COMPLETED | 已完成 | 咨询已结束,终态 | -| CANCELLED | 已取消 | 用户或管理员取消,终态 | - -**状态机流转**: - -``` -PENDING ──→ CONFIRMED ──→ COMPLETED - │ │ - └── CANCELLED ←──┘ -``` - -## ConsultantStatus — 咨询师状态 - -| Code | 描述 | 说明 | -|------|------|------| -| ACTIVE | 可预约 | 可在预约列表展示和选择 | -| DISABLED | 不可预约 | 不展示在预约列表 | - -## BranchStatus — 网点状态 - -| Code | 描述 | 说明 | -|------|------|------| -| ACTIVE | 营业中 | 正常运营 | -| DISABLED | 已关闭 | 停止运营 | - -## DataDictionaryType — 字典类型注册表 - -| Code | 关联枚举 | 描述 | 查询端点 | -|------|----------|------|----------| -| USER_ROLE | UserRole | 用户角色字典 | `/api/v1/data-dictionaries/USER_ROLE` | -| USER_STATUS | UserStatus | 用户状态字典 | `/api/v1/data-dictionaries/USER_STATUS` | -| APPOINTMENT_STATUS | AppointmentStatus | 预约状态字典 | `/api/v1/data-dictionaries/APPOINTMENT_STATUS` | -| CONSULTANT_STATUS | Consultant.ConsultantStatus | 咨询师状态字典 | `/api/v1/data-dictionaries/CONSULTANT_STATUS` | -| BRANCH_STATUS | Branch.BranchStatus | 网点状态字典 | `/api/v1/data-dictionaries/BRANCH_STATUS` | - -## 同步策略 - -修改枚举后,运行 `DataDictionaryUtil.generateMarkdown()` 更新本文档。 +当前注册字典类型:**无**。 diff --git a/example-project/docs/facts/tech-topic/error-code.md b/example-project/docs/facts/tech-topic/error-code.md index d49f5b7..e866fdd 100644 --- a/example-project/docs/facts/tech-topic/error-code.md +++ b/example-project/docs/facts/tech-topic/error-code.md @@ -1,84 +1,17 @@ # 错误码清单 -> 本文档描述咨询预约平台的错误码体系事实(as-built)。 +> 框架约定(空壳 as-built)。业务专属错误码待 iteration1 实现后补充。 +> 与 `GlobalExceptionHandler` 及 `docs/standards/error.md` 对齐。 -## 错误码结构 +## 当前 Handler 映射 -``` -{ErrorGroup}_{SubCode} -``` +| 抛出 | HTTP | errorCode | 说明 | +|------|------|-----------|------| +| `IllegalArgumentException` | 400 | `PARAM_ERROR` | 参数/资源不合法 | +| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` | 业务状态冲突 | +| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` | `@Valid` 失败 | +| 其它 `Exception` | 500 | `SYSTEM_ERROR` | 兜底(对外「系统繁忙」) | -- ErrorGroup(错误组):错误的来源分类 -- SubCode(子码):具体错误标识,可读性强 +鉴权失败由 Spring Security 直接返回 **401 / 403**,不走 `ErrorResponse`。 -## ErrorGroup 定义 - -| Group | HTTP Status | 说明 | -|-------|-------------|------| -| COMMON | 400/404 | 通用参数/资源错误 | -| AUTH | 401/400 | 认证/鉴权错误 | -| BUSINESS | 409/400 | 业务逻辑冲突/错误 | -| SYSTEM | 500 | 系统内部错误 | - -## 全量错误码 - -### COMMON 组 - -| ErrorCode | HTTP Status | 说明 | 触发场景 | -|-----------|-------------|------|----------| -| COMMON_PARAM_ERROR | 400 | 参数校验失败 | @Valid 校验不通过 | -| COMMON_RESOURCE_NOT_FOUND | 404 | 资源不存在 | 根据 ID 查询无结果 | -| COMMON_VALIDATION_ERROR | 400 | 参数格式错误 | 字段级校验失败 | - -### AUTH 组 - -| ErrorCode | HTTP Status | 说明 | 触发场景 | -|-----------|-------------|------|----------| -| AUTH_EMAIL_EXISTS | 400 | 邮箱已注册 | 重复 email 调用 register | -| AUTH_WEAK_PASSWORD | 400 | 密码强度不足 | 密码 < 8 位 | -| AUTH_INVALID_CREDENTIALS | 400 | 邮箱或密码错误 | login 时密码不匹配 | -| AUTH_INVALID_TOKEN | 401 | Token 无效或过期 | JWT 解析失败 | -| AUTH_TOKEN_EXPIRED | 401 | Token 已过期 | JWT 超时 | -| AUTH_FORBIDDEN | 403 | 无权限 | 非 ADMIN 访问 /admin | -| AUTH_USER_DISABLED | 401 | 用户已被停用 | status == DISABLED | - -### BUSINESS 组 - -| ErrorCode | HTTP Status | 说明 | 触发场景 | -|-----------|-------------|------|----------| -| BUSINESS_CONFLICT_SLOT | 409 | 该时段已被预约 | 同一咨询师同一时段重复预约 | -| BUSINESS_CONSULTANT_UNAVAILABLE | 400 | 咨询师不可预约 | consultant.isAvailable() == false | -| BUSINESS_APPOINTMENT_CANNOT_CANCEL | 409 | 当前状态不允许取消 | status 为 COMPLETED 或 CANCELLED | -| BUSINESS_APPOINTMENT_NOT_OWNER | 403 | 非本人预约不可操作 | userId 不匹配 | -| BUSINESS_USER_DISABLED | 400 | 用户已被停用 | 尝试操作已 DISABLED 的用户 | -| BUSINESS_BRANCH_HAS_CONSULTANTS | 409 | 网点有咨询师不可删除 | branch 关联的 consultant > 0 | - -### SYSTEM 组 - -| ErrorCode | HTTP Status | 说明 | 触发场景 | -|-----------|-------------|------|----------| -| SYSTEM_INTERNAL_ERROR | 500 | 系统内部错误 | 未捕获的异常 | -| SYSTEM_DB_ERROR | 500 | 数据库错误 | SQL 执行失败 | - -## 返回格式 - -```json -{ - "errorCode": "BUSINESS_CONFLICT_SLOT", - "errorMessage": "该时间段已被预约", - "data": null -} -``` - -## 当前实现映射 - -当前 `GlobalExceptionHandler` 使用简化 errorCode(无 ErrorGroup 前缀),映射关系: - -| 当前 errorCode | 规范 errorCode | 异常类型 | -|----------------|---------------|----------| -| PARAM_ERROR | COMMON_PARAM_ERROR | IllegalArgumentException | -| VALIDATION_ERROR | COMMON_VALIDATION_ERROR | MethodArgumentNotValidException | -| BUSINESS_CONFLICT | BUSINESS_CONFLICT_SLOT | IllegalStateException | -| SYSTEM_ERROR | SYSTEM_INTERNAL_ERROR | Exception | - -**迁移计划**:Phase 2 后统一改用规范 errorCode 格式。 +响应体字段:`errorCode` / `errorMessage` / `data`。 diff --git a/example-project/docs/facts/tech-topic/security.md b/example-project/docs/facts/tech-topic/security.md index a59b751..5ebad0f 100644 --- a/example-project/docs/facts/tech-topic/security.md +++ b/example-project/docs/facts/tech-topic/security.md @@ -1,90 +1,30 @@ # 安全设计 -> 本文档描述咨询预约平台的安全架构事实(as-built)。 +> 平台骨架 as-built。登录/注册等业务 API 待 ACC 实现。 ## JWT Token -**算法**:HMAC-SHA256(`jjwt` 库 MAC 算法) +**算法**:HMAC-SHA256(`jjwt`) -**密钥**:通过 `application.yml` 的 `jwt.secret` 配置,至少 256 位 +**配置**:`jwt.secret` / `jwt.expiration`(毫秒) -**有效期**:24 小时(`jwt.expiration` 配置,单位毫秒) +**Claims(约定)**:`sub`=userId,`email`,`role`(如 `ROLE_USER` / `ROLE_ADMIN`),`iat`,`exp` -**Payload Claims**: - -| Claim | 类型 | 值 | 说明 | -|-------|------|-----|------| -| sub | String | userId | 用户 UUID | -| email | String | email | 用户邮箱 | -| role | String | ROLE_USER / ROLE_ADMIN | 角色(与 Spring Security `hasRole()` 兼容) | -| iat | Date | 签发时间戳 | - -| exp | Date | 过期时间戳 | - - -## JWT 处理流程 +## 处理流程 ``` -请求 → JwtAuthenticationFilter (OncePerRequestFilter) - 1. 从 Authorization: Bearer 提取 Token - 2. 解析 JWT → userId + email + role - 3. 设置 SecurityContextHolder (Spring Security) - 4. 设置 UserContextHolder (自定义 ThreadLocal) - 5. 放行请求 - 6. 请求结束后清除 ThreadLocal +请求 → JwtAuthenticationFilter + 提取 Bearer token → 校验 → UserContextHolder + SecurityContextHolder + finally 清除 ThreadLocal / SecurityContext ``` -## Filter Chain 顺序 +## 当前放行 -``` -Spring Security Filter Chain (SecurityConfig): - 1. JwtAuthenticationFilter (自定义, 提取 JWT 并设置上下文) - 2. UsernamePasswordAuthenticationFilter (内置, 不启用) - 3. ExceptionTranslationFilter (内置, 处理 AccessDenied) - 4. ... -``` +- `GET /api/v1/health` — permitAll +- 其它 `/api/**` — authenticated(无签发入口时仅能带有效 token 访问) -## SecurityConfig 规则矩阵 +## 相关类 -| 路径模式 | 访问要求 | -|----------|----------| -| POST /api/v1/auth/register | 完全公开 | -| POST /api/v1/auth/login | 完全公开 | -| GET /api/v1/home/info | 完全公开 | -| GET /api/v1/data-dictionaries** | 完全公开 | -| GET /api/v1/business-rules** | 完全公开 | -| GET /api/v1/consultants** | 完全公开 | -| /admin/** | 仅 ROLE_ADMIN | -| /api/v1/** | 需要认证(任何角色) | - -## BCrypt 密码策略 - -- 编码器:`BCryptPasswordEncoder`(Spring Security 默认实现) -- 强度:10(默认 rounds) -- 密码要求:至少 8 位,由前端校验 - -## UserContext ThreadLocal - -**类**:`UserContextHolder` — `ThreadLocal` - -**UserContext 字段**: - -| 字段 | 类型 | 来源 | -|------|------|------| -| userId | String | JWT sub | -| email | String | JWT email | -| role | String | JWT role | - -**获取**:`SecurityUtils.currentUserId()` — 从 UserContextHolder 获取当前用户 ID - -## CORS 配置 - -- 当前:`WebConfig.java` 允许所有 origin(开发阶段) -- 生产:需限制为具体域名 - -## 密码修改流程 - -``` -1. 用户输入旧密码 + 新密码 -2. 从 DB 获取当前 BCrypt hash -3. passwordService.matches(旧密码, 当前 hash) → 校验 -4. passwordService.encode(新密码) → 更新 DB -``` +- `JwtTokenProvider` / `JwtAuthenticationFilter` +- `UserContext` / `UserContextHolder` / `SecurityUtils` +- `PasswordService` / `PasswordServiceImpl`(BCrypt) diff --git a/example-project/docs/facts/tech-topic/state-machine.md b/example-project/docs/facts/tech-topic/state-machine.md index cd2becb..9c9087c 100644 --- a/example-project/docs/facts/tech-topic/state-machine.md +++ b/example-project/docs/facts/tech-topic/state-machine.md @@ -1,67 +1,4 @@ -# 状态机设计 +# 状态机 -> 本文档描述 AppointmentStatus 的完整状态机事实(as-built)。 - -## 状态定义 - -| Code | 描述 | 含义 | -|------|------|------| -| PENDING | 待确认 | 初始状态,用户已提交但等待确认 | -| CONFIRMED | 已确认 | 咨询师/管理员已确认,预约生效 | -| COMPLETED | 已完成 | 咨询已结束,**终态** | -| CANCELLED | 已取消 | 用户或管理员取消,**终态** | - -## 状态流转图 - -``` - ┌──────────┐ - │ PENDING │ ← 创建预约后初始状态 - └────┬─────┘ - │ - ┌──────┴──────┐ - │ │ - ▼ ▼ -┌──────────┐ ┌──────────┐ -│CONFIRMED │ │CANCELLED │ ← 用户可取消 -└────┬─────┘ └──────────┘ - │ - ▼ -┌──────────┐ -│COMPLETED │ -└──────────┘ -``` - -## 转换表 - -| 当前状态 | 目标状态 | 触发操作 | 守卫条件 | 代码位置 | -|----------|----------|----------|----------|----------| -| (新创建) | PENDING | 创建预约 (AppointmentService.create) | 咨询师可预约 + 无冲突 | `AppointmentService.java:50-53` | -| PENDING | CONFIRMED | 管理员确认 (预留) | - | 未实现 | -| PENDING | CANCELLED | 取消预约 (AppointmentService.cancel) | `!COMPLETED && !CANCELLED` | `Appointment.java` `canCancel()` | -| CONFIRMED | COMPLETED | 管理员完成 (预留) | - | 未实现 | -| CONFIRMED | CANCELLED | 取消预约 (AppointmentService.cancel) | `!COMPLETED && !CANCELLED` | `Appointment.java` `canCancel()` | - -## 守卫条件 - -``` -canCancel() = status != COMPLETED && status != CANCELLED -``` - -- PENDING 可取消 -- CONFIRMED 可取消 -- COMPLETED **不可取消** -- CANCELLED **不可再次取消** - -## 业务规则集成 - -**冲突检测**(AppointmentConflictService): -- 创建预约时,排除 status == CANCELLED 的旧预约 -- 允许在同一咨询师同一时段重新预约(如果之前的预约已取消) -- 由 `uk_appointment_slot` 唯一索引 + 代码双重校验 - -## 待实现状态转换 - -| 动作 | 优先级 | 说明 | -|------|--------|------| -| PENDING → CONFIRMED | 低 | 目前无确认端点,需管理后台功能 | -| CONFIRMED → COMPLETED | 低 | 同上 | +> 空壳:原 Appointment 状态机 as-built 已清除。 +> 状态流转以 `docs/features/iteration1/` 各 spec §9 为准,实现后回写本文档。 diff --git a/example-project/docs/features/_chores/plan-20260619-project-plan.md b/example-project/docs/features/_chores/plan-20260619-project-plan.md deleted file mode 100644 index 82d3a23..0000000 --- a/example-project/docs/features/_chores/plan-20260619-project-plan.md +++ /dev/null @@ -1,67 +0,0 @@ -# 20260619 - Consultation Booking Platform 完整开发计划 - -## 总体策略 - -Domain 优先,逐层外扩。每个阶段围绕一个有边界的子域展开: - -``` -分析业务 → 设计 Domain → Infrastructure → Application → Adapter → Frontend -``` - -## 阶段划分 - -### Phase 0:基础骨架 - -**目标**:建立项目物理结构与基础设施基线 - -- 后端:pom.xml + 四层包结构 + 配置类(MyBatisPlus / Web / Jackson / Security / ExceptionHandler)+ JWT 基础设施 + BCrypt -- 前端:package.json + Vite + Vue Router + Pinia + Axios 拦截器 + 全局样式 -- 文档:standards 目录完整(layers / db / api / naming / security) - -### Phase 1:公共首页 + 用户认证 - -- Domain:User(email/password/name/role/status) -- 后端:Register + Login + JWT 签发 + Profile API -- 前端:首页 + 登录 + 注册 + AppHeader -- 数据表:user(含唯一索引 email)+ seed 管理员 - -### Phase 2:咨询师 + 预约管理 - -- Domain:Consultant + Appointment + TimeSlot -- 核心规则:预约冲突检测(唯一索引 + 代码校验)、状态机(PENDING→CONFIRMED→COMPLETED / CANCELLED) -- 后端:Consultant CRUD + Appointment CRUD + 时间段查询 -- 前端:预约四步流程(选咨询师→选日期→选时间→确认)+ 我的预约列表 -- 数据表:consultant + appointment + branch - -### Phase 3:用户中心 - -- 用户 Dashboard 统计 -- 个人信息编辑 + 密码修改 - -### Phase 4:管理后台 - -- 管理仪表盘 -- 用户管理(启用/停用) -- 咨询师管理(CRUD) -- 预约管理 -- 网点管理(CRUD) - -## 依赖关系 - -``` -Phase 0 (骨架) - └─ Phase 1 (认证) ── 依赖 JWT + SecurityConfig - └─ Phase 2 (预约) ── 依赖 Auth 上下文 - ├─ Phase 3 (用户中心) - └─ Phase 4 (管理后台) -``` - -## 技术决策 - -- Java 17 + Spring Boot 3.2 + MyBatis-Plus 3.5.5 -- JWT HMAC-SHA256 + BCrypt -- 主键 UUID VARCHAR(64),公共字段 created_by/created_time/updated_by/updated_time -- 统一错误响应 `{errorCode, errorMessage, data}` -- API 前缀 `/api/v1/`,分页入参 page/pageSize -- 前端 Vue 3 + Composition API + Pinia + Vue Router 4 + Axios -- Vite 代理 `/api` → `localhost:8080` diff --git a/example-project/docs/features/_chores/plan-20261106-businessrule-datadictionary-api-tests.md b/example-project/docs/features/_chores/plan-20261106-businessrule-datadictionary-api-tests.md deleted file mode 100644 index 65c9ea7..0000000 --- a/example-project/docs/features/_chores/plan-20261106-businessrule-datadictionary-api-tests.md +++ /dev/null @@ -1,359 +0,0 @@ -# 补齐 BusinessRule / DataDictionary API 集成测试 - -> 日期:2026-11-06 -> -> 关联需求:不涉及(本轮不引入新需求,修复的是 AGENTS.md §10 已写明的规范缺口) -> -> 设计 design:docs/facts/tech-topic/businessrule.md、docs/facts/tech-topic/data-dict.md -> -> -> **plan 一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 - -## 1. 文档说明 - -### 1.1 背景 - -`AGENTS.md` §10「开发自测覆盖要求」写得很硬: - -> 每个 API **必须** 有对应的集成测试 -> 至少覆盖:1 个 Happy Path + 关键失败分支(参数错误 / 权限不足 / 业务冲突) - -现状盘点 —— `apps/backend/src/test/java/com/consultation/adapter/rest/`: - -| Controller | 集成测试 | 状态 | -|---|---|---| -| `AdminController` | `AdminControllerTest`(6 例) | ✅ | -| `AppointmentController` | `AppointmentControllerTest`(3 例) | ✅ | -| `AuthController` | `AuthControllerTest`(3 例) | ✅ | -| `ConsultantController` | `ConsultantControllerTest`(3 例) | ✅ | -| `UserController` | `UserControllerTest`(3 例) | ✅ | -| `BusinessRuleController` | — | ❌ **缺** | -| `DataDictionaryController` | — | ❌ **缺** | -| `HomeController` | — | ❌ 缺(纯静态页,无业务规则,留待后续) | - -两个缺口都不是"锦上添花",而是 **对外暴露的公开读接口**,且都 `permitAll`(无需鉴权即可访问), -一旦字段结构漂移(ruleName 改名、字典类型漏注册)不会有任何编译错误,只会静默返回错数据。 - -关键决策点: - -- **只补测试,不动生产代码。** 这两个 Controller 的实现(`BusinessRuleAppService` / `DataDictionaryAppService`) - 本身没有问题,缺的是"证明它们是对的"的用例。改动面越窄,评审与回滚成本越低。 -- **本轮不写 QA 用例。** QA 用例针对"需求规格的验收标准",本轮没有新需求、没有契约变更, - 按 `AGENTS.md` §10 的分层定义,QA 用例库不需要新增条目(见 §11.4 同步检查)。 - -### 1.2 目标 - -- 实现目标: - - 新增 `BusinessRuleControllerTest`,覆盖 `GET /api/v1/business-rules` 的 happy path、规则完整性、YAML 配置透出、免鉴权 - - 新增 `DataDictionaryControllerTest`,覆盖 `GET /api/v1/data-dictionaries` 与 `GET /api/v1/data-dictionaries/{type}` 的 happy path、大小写不敏感、字典项内容、未知类型失败分支 -- 技术边界: - - **只新增 2 个测试文件**,`apps/backend/src/main/**` 一行不动 - - 不引入新依赖(RestAssured + JUnit 5 + Hamcrest 均已在 `pom.xml`) - - 不改数据库、不改 API 契约、不改前端 - ------- - -## 2. 领域模型(PlantUML) - -本轮不涉及 —— 无领域模型变更。仅在 §9 断言已有模型对外投影的结果。 - -## 3. 数据库设计(SQL DDL) - -本轮不涉及 —— 无表结构变更。目标接口不读写数据库。 - -## 4. API 设计(OpenAPI) - -本轮不涉及 —— **无 API 契约变更**。目标接口的现有契约(只读,仅此如下,不做任何修改): - -```yaml -openapi: 3.0.0 -info: - title: 业务规则 / 数据字典 API(现有契约,本轮不改) - version: 1.0.0 -paths: - /api/v1/business-rules: - get: - summary: 列出全部业务规则 - responses: - '200': - description: 规则数组 - content: - application/json: - schema: - type: array - items: - type: object - properties: - ruleName: { type: string } - description: { type: string } - config: { type: object } - /api/v1/data-dictionaries: - get: - summary: 列出全部数据字典类型 - responses: - '200': { description: 字典数组 } - /api/v1/data-dictionaries/{type}: - get: - summary: 按类型取数据字典 - parameters: - - name: type - in: path - required: true - schema: { type: string } - responses: - '200': { description: 单个字典 } - '400': { description: 字典类型不存在 } -``` - -## 5. 时序图(PlantUML) - -```plantuml -@startuml -actor Client -participant "BusinessRuleController\n/ DataDictionaryController" as API -participant "BusinessRuleAppService\n/ DataDictionaryAppService" as Service -participant "BusinessRuleProvider\n/ DataDictionaryUtil" as Domain - -Client -> API : GET /api/v1/business-rules -API -> Service : getAllRules() -Service -> Domain : ruleCache.values() -Domain --> Service : List> -Service --> API : List> -API --> Client : 200 JSON - -Client -> API : GET /api/v1/data-dictionaries/{unknown} -API -> Service : getByType(type) -Service -> Domain : values() 过滤 -Domain --> Service : empty -Service -> API : IllegalArgumentException -API --> Client : 400 ErrorResponse -@enduml -``` - ------- - -## 6. 专题设计(Markdown) - -### 6.1 权限设计 - -`SecurityConfig` 中 `/api/v1/data-dictionaries/**` 与 `/api/v1/business-rules/**` 均为 `permitAll`。 -本轮新增用例 **一律不带 token**,顺带把"这两个接口免鉴权"这条契约钉死 —— 将来有人误加 -`.authenticated()` 时,用例会立刻红。 - -### 6.2 并发控制 - -不涉及(只读接口,无写操作)。 - -### 6.3 事务设计 - -不涉及(只读,不涉及事务边界)。 - -### 6.4 异常处理 - -**这是本轮唯一的"契约断言"重点。** - -`GET /api/v1/data-dictionaries/{type}` 传入未知类型时: - -`DataDictionaryAppService.getByType()` → `IllegalArgumentException("字典类型不存在: " + typeName)` -→ `GlobalExceptionHandler.handleBadArg()` → HTTP 400,body 为 `ErrorResponse`: - -```json -{ - "errorCode": "PARAM_ERROR", - "errorMessage": "字典类型不存在: NOT_EXIST", - "data": null -} -``` - -> ⚠️ **发现的既有文档不一致(本轮不修,仅记录)** -> -> `AGENTS.md` §7 给的示例 JSON 写的是 `"message"` 字段: -> ```json -> { "errorCode": "APPOINTMENT_CONFLICT", "message": "该时间段已被占用", "timestamp": "..." } -> ``` -> 而 `GlobalExceptionHandler.ErrorResponse` 这个 record 的实际字段是 -> **`errorCode` / `errorMessage` / `data`**,既没有 `message` 也没有 `timestamp`。 -> -> 事实文档与代码不一致,按 `AGENTS.md` §13 的同步要求应当修正 `AGENTS.md` §7, -> 但那属于"改事实文档"而非"补测试",**建议单独开一轮**处理,本轮不动 `AGENTS.md`。 -> -> 本轮测试 **以代码实际契约为准**(断言 `errorCode` + `errorMessage`)。 - -### 6.5 性能设计 - -不涉及。 - -### 6.6 扩展性设计 - -不涉及。 - ------- - -## 7. 一致性约束(必须遵守) - -* 断言里的字段名必须与实际 JSON 一致: - * 业务规则项:`ruleName` / `description` / `config` - * 数据字典:`typeName` / `description` / `items[]`,字典项 `code` / `description` - * 错误响应:`errorCode` / `errorMessage` / `data` -* 枚举 code 一律等于枚举名(`Description.getCode()` → `name()`): - * `USER_ROLE` → `ROLE_USER` / `ROLE_ADMIN` - * `USER_STATUS` → `ACTIVE` / `DISABLED` - * `APPOINTMENT_STATUS` → `PENDING` / `CONFIRMED` / `COMPLETED` / `CANCELLED` - * `CONSULTANT_STATUS` → `ACTIVE` / `DISABLED` - * `BRANCH_STATUS` → `ACTIVE` / `DISABLED` -* 业务规则 `ruleName` 取自 `AppointmentRule` / `AuthRule` 枚举,共 **7 条**(4 + 3) -* 命名规范: - * 测试类名 `{被测Controller}Test` → `BusinessRuleControllerTest` / `DataDictionaryControllerTest` - * 方法名 `should_{action}_{expectedResult}` - * **不写 `TC-` 编号** —— `TC-xxx` 是 QA 用例的编号体系,开发自测不进入编号空间 - (`AGENTS.md` §10 用例编号列:「开发自测 = 无编号,命名表达意图」) -* 归属:这两个文件属于 **开发自测**(验证"代码按 Plan 的设计工作"), - **不是 QA 测试**,不进 `docs/test-cases/e2e-cases/`,也不进 `e2e/tests/qa/` - ------- - -## 8. 单元测试设计 - -本轮不涉及 —— 不改 domain/application 层,不新增单元测试。 -`BusinessRuleProvider` 的 YAML 装载逻辑与 `DataDictionaryUtil` 的投影逻辑 -由 §9 的集成测试经由 HTTP 端到端覆盖。 - ------- - -## 9. API 集成测试设计 - -### 9.1 测试范围 - -* 切片类型:全链路集成(`@SpringBootTest(webEnvironment = RANDOM_PORT)` + RestAssured) -* 真实加载组件:Controller → AppService → domain(`BusinessRuleProvider` / `DataDictionaryUtil`) -* Mock 边界:**无**。两个接口都不触碰 DB,也不调外部服务,全链路真实 -* 继承 `com.consultation.TestBase`(已含 `@BeforeEach` 的 `resetDbService.resetAll()`, - 本轮用例不写库,但沿用同一隔离机制,保证可重复执行、与执行顺序无关) - -### 9.2 测试环境 - -* 数据库:MariaDB4j(`TestBase` 已配好)—— 本轮用例不读写 -* 中间件:无 -* 下游服务:无 -* 迁移脚本:`spring.flyway.enabled=false`(test profile 已有) -* 鉴权:两个端点 `permitAll`,**用例不带 Authorization 头** - -### 9.3 用例覆盖场景 - -- [x] 契约校验:状态码、响应字段、错误返回结构 -- [x] 鉴权场景:免鉴权可访问(`permitAll` 契约) -- [x] 业务闭环:不涉及(只读接口) -- [x] 数据一致性:YAML 配置 → 接口透出;枚举 → 字典项 -- [ ] 状态机 / 并发幂等 / 下游异常:不涉及(只读接口,无状态流转) - -### 9.4 测试数据 - -* 数据准备:**不需要**。无 DB 写入 -* 隔离策略:沿用 `TestBase.setUp()` 的 `resetDbService.resetAll()` -* 断言规范:RestAssured + Hamcrest(`not(empty())` / `hasItem` / `hasKey` / `containsString`) - -### 9.5 用例清单 - -#### BusinessRuleControllerTest — `GET /api/v1/business-rules` - -| # | 场景类型 | 用例说明 | 预期结果 | 关联章节 | -| :--: | :------: | :------ | :------ | :------ | -| 1 | 正常场景 | 列出全部业务规则 | 200;数组非空;长度为 7(4 条预约规则 + 3 条鉴权规则) | §7 | -| 2 | 正常场景 | 包含预约冲突检测规则 | 200;含 `ruleName == "appointment_conflict_detection"`,其 `description` 非空 | §7 | -| 3 | 正常场景 | 包含鉴权令牌过期规则 | 200;含 `ruleName == "auth_token_expiration"` | §7 | -| 4 | 数据一致性 | YAML 配置透出到 `config` | 200;每条规则含 `config`;`config.appointment.slot.minMinutes == 30`;`config.auth.token.expirationMs == 86400000` | §7 | -| 5 | 鉴权场景 | 不带 token 也能访问 | 200(`permitAll` 契约) | §6.1 | - -#### DataDictionaryControllerTest - -| # | 接口 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | -| :--: | :--: | :------: | :------ | :------ | :------ | -| 1 | `GET /api/v1/data-dictionaries` | 正常场景 | 列出全部数据字典类型 | 200;长度为 5;每项 `typeName` / `description` / `items` 非空 | §7 | -| 2 | `GET /api/v1/data-dictionaries/USER_ROLE` | 正常场景 | 按类型取字典 | 200;`typeName == "USER_ROLE"`;`items` 含 `code == "ROLE_USER"` 与 `code == "ROLE_ADMIN"`,各自 `description` 非空 | §7 | -| 3 | `GET /api/v1/data-dictionaries/user_role` | 边界场景 | 类型名大小写不敏感 | 200;`typeName == "USER_ROLE"`(`equalsIgnoreCase` 契约) | §7 | -| 4 | `GET /api/v1/data-dictionaries/APPOINTMENT_STATUS` | 正常场景 | 状态字典项完整 | 200;`items` 含 `PENDING` / `CONFIRMED` / `COMPLETED` / `CANCELLED` 四个 code | §7 | -| 5 | `GET /api/v1/data-dictionaries/NOT_EXIST` | 异常场景 | 未知字典类型 | 400;`errorCode == "PARAM_ERROR"`;`errorMessage` 含 `"字典类型不存在"` | §6.4 | - -**合计 10 个用例。** 覆盖 2 个 Controller 的全部对外方法与全部可达失败分支。 - ------- - -## 11. 修改清单 - -### 11.1 代码修改 - -**无。** `apps/backend/src/main/**` 本轮一行不改。 - -### 11.1.2 新增文件 - -| 操作 | 文件 | 用途 | -| :--: | :-- | :-- | -| 新增 | `apps/backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java` | 5 个用例,覆盖 `GET /api/v1/business-rules` | -| 新增 | `apps/backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java` | 5 个用例,覆盖两个数据字典接口 | - -#### 11.1.x 关键文件速查 - -| 操作 | 文件 | 备注 | -| :--: | :-- | :-- | -| 新增 | `apps/backend/src/test/java/com/consultation/adapter/rest/BusinessRuleControllerTest.java` | 继承 `TestBase`,`should_*` 命名 | -| 新增 | `apps/backend/src/test/java/com/consultation/adapter/rest/DataDictionaryControllerTest.java` | 继承 `TestBase`,`should_*` 命名 | - -### 11.2 接口变更 - -无。 - -### 11.3 数据库变更 - -无。 - -### 11.4 文档同步检查 - -| 文档 | 是否需要更新 | 理由 | -|---|---|---| -| `docs/facts/api.yaml` | **不涉及** | 无 API 契约变更 | -| `docs/facts/db-schema.md` | **不涉及** | 无表结构变更 | -| `docs/facts/tech-topic/businessrule.md` | **不涉及** | 规则定义未变,只是给它补了测试 | -| `docs/facts/tech-topic/data-dict.md` | **不涉及** | 字典定义未变,只是给它补了测试 | -| `docs/test-cases/e2e-cases/test-cases.md` | **不涉及** | 属开发自测,不是 QA 用例;无新需求、无验收标准变化 | -| `AGENTS.md` §7 | **本轮不修,建议单独开一轮** | 见 §6.4 记录的 `ErrorResponse` 字段名不一致 | - ---- - -## 12. 验证步骤 - -1. **基线(改动前)**:`cd apps/backend && mvn -o -B test` → 期望 `Tests run: 18, Failures: 0, Errors: 0` -2. **实现后**:`cd apps/backend && mvn -o -B test` → 期望 `Tests run: 28, Failures: 0, Errors: 0` - (18 基线 + 10 新增) -3. **只看新用例**:`cd apps/backend && mvn -o -B test -Dtest='BusinessRuleControllerTest,DataDictionaryControllerTest'` - → 期望 `Tests run: 10, Failures: 0, Errors: 0` -4. **确认没碰生产代码**:`git status --short` → 只应出现 2 个新增测试文件 -5. **确认没有引入 `TC-` 编号**:`grep -rn "TC-" apps/backend/src/test/` → 无输出 - ---- - -## 13. 风险与回滚 - -* 风险点 1:**用例断言过细导致脆**。例如把 `config.appointment.slot.minMinutes == 30` 写死, - 将来 YAML 改了分钟数,用例会红 —— 这是**预期的**,配置项被改动本来就应该有测试提醒。 - 但要避免断言整个 `config` 的 JSON 全等。 -* 风险点 2:**规则条数 7 会随业务规则增减而变**。同理,属预期提醒。 - 若担心太脆,可只断言"包含 X 条规则"而非"恰好 7 条";本轮选择断言恰好 7 条, - 因为新增/删除业务规则是低频且需要评审的动作。 -* 风险点 3:**未知类型分支被 Spring 兜底成 500**。若 `IllegalArgumentException` 未被 - `GlobalExceptionHandler` 捕获,会落到 `handleOther` → 500 `SYSTEM_ERROR`。 - 用例 5 会直接暴露这个问题。 -* 回滚方案:删除 2 个新增测试文件即可,**零生产代码回滚风险**。 - ---- - -## 14. 实施后需更新的 design 文档 - -不涉及(见 §11.4)。 - ---- - -## 15. 变更记录(可选) - -| 版本 | 日期 | 变更内容 | -| ---- | ---------- | -------- | -| v1.0 | 2026-11-06 | 初始版本 | diff --git a/example-project/docs/features/_chores/plan-20261106-fix-public-endpoints-and-error-doc.md b/example-project/docs/features/_chores/plan-20261106-fix-public-endpoints-and-error-doc.md deleted file mode 100644 index ef8d417..0000000 --- a/example-project/docs/features/_chores/plan-20261106-fix-public-endpoints-and-error-doc.md +++ /dev/null @@ -1,449 +0,0 @@ -# 修复业务规则配置绑定缺陷,并让错误模型文档与实现对齐 - -> 日期:2026-11-06 -> -> 关联需求:不涉及(本轮修的是实现与事实文档之间的既有偏差,偏差来源见 §1.1) -> -> 设计 design:docs/facts/tech-topic/businessrule.md、docs/facts/tech-topic/error-code.md -> -> -> **plan 一旦定稿就不修改。** 同一资源的二次改造新建 `YYYY-MM-DD-{slug}.md`,不修改原计划文件 - -## 1. 文档说明 - -### 1.1 背景 - -上一轮(`20261106-businessrule-datadictionary-api-tests.md`)补齐了 BusinessRule / -DataDictionary 的集成测试,runner 在无人值守下记录了 **3 项"发现但未修"**。 -本轮把其中 2 项真正修掉,外加 1 项上一轮之后新核实的问题: - -| # | 问题 | 性质 | 本轮处理 | -|---|---|---|---| -| 1 | `config.auth.publicEndpoints` 被序列化成 `{"0":"/api/v1/auth/**",...}` 而非 JSON 数组 | **实现缺陷** | 修(§11.1) | -| 2 | `AGENTS.md` §7 描述了一套不存在的错误模型 | **事实文档与实现不符** | 修(§11.3) | -| 3 | `config.auth.*` 的来源与 `docs/facts/tech-topic/businessrule.md` 的"配置路径"列对不上 | **事实文档与实现不符** | 修(§11.3) | -| 4 | `docs/standards/error.md` 描述的 `IError` / `AbstractException` / `ErrorGroup` 体系在代码里 **完全不存在** | **事实文档与实现不符** | 修(§11.3) | -| 5 | 6 处引用 `docs/dev/design-fact/**` 的死链(该目录不存在) | **死链** | 修(§11.3) | - -**问题 1 的根因**(已实测确认,不是猜测): - -`BusinessRuleConfig.auth` 声明为 `Map`,Spring Boot 的 binder 拿到 YAML 里的 -**序列**(`publicEndpoints: ["...","..."]`)时,无法确定该绑成数组还是 Map,于是退化成 -**以 0/1/2… 为键的 Map**。于是 Jackson 序列化出 `{"0":"...","1":"..."}` —— -下游任何按数组消费的客户端都会拿到错误结构。 - -同一份 `auth.yml` 里的 `password` / `token` 是纯标量子结构,绑成 Map 没问题。 -**只有列表这一种形状会被绑坏。** - -**问题 2/4 的根因**:`AGENTS.md` §7 与 `docs/standards/error.md` 描述的是一套 -"照抄自别的项目"的错误模型 —— `BusinessException`、`IError`、`ErrorGroup`、 -`{errorCode, message, timestamp}`。本仓库的代码里 **一个都不存在**。 -实际实现是: - -``` -GlobalExceptionHandler(@RestControllerAdvice) -├── IllegalArgumentException → 400 PARAM_ERROR -├── IllegalStateException → 409 BUSINESS_CONFLICT -├── MethodArgumentNotValidException → 400 VALIDATION_ERROR -└── Exception(兜底) → 500 SYSTEM_ERROR -响应体:ErrorResponse{errorCode, errorMessage, data} -``` - -新人按 §7 写代码会直接编译不过(`BusinessException` 不存在), -按文档里的示例 JSON 解析响应也会拿到 `null`(字段叫 `errorMessage` 不叫 `message`)。 - -关键决策点: - -- **问题 1 改 `BusinessRuleConfig` 的类型声明,不改 YAML。** - YAML 里的列表写法是 **正确且符合直觉的**(`publicEndpoints` 就是个列表), - 错的是 Java 侧用 `Map` 去接它。改 YAML 去迁就错误的类型声明是本末倒置。 -- **问题 1 只把 `auth` 改成有类型的嵌套类,`appointment` 保持 `Map`。** - `appointment` 当前全是标量子结构,没有列表,绑 Map 是安全的;把它也类型化要新增 4 个 - 嵌套类、放大 diff 与回归面,而它今天 **没有暴露出任何问题**。留作后续。 -- **问题 2/3/4/5 改文档,不改代码。** 代码是对的(`error-code.md` 的"当前实现映射"表 - 已经如实记录了现状),错的是文档。 - -### 1.2 目标 - -- 实现目标: - - `GET /api/v1/business-rules` 返回的 `config.auth.publicEndpoints` 是 **JSON 数组** - - `AGENTS.md` §7 / §12 与 `docs/standards/error.md` 的错误模型描述与代码 **完全一致** - - `docs/facts/tech-topic/businessrule.md` 的"配置路径"列指向 **真实生效** 的配置来源 - - 仓库内不再有指向 `docs/dev/design-fact/**` 的死链 -- 技术边界: - - 生产代码改动 **限 2 个文件**:`BusinessRuleConfig`、`BusinessRuleProvider` - - YAML 内容 **不改** - - API 契约 **不改**(`docs/facts/api.yaml` 的 `config: {type: object}` 不动) - - 前端、数据库、QA 用例 **不涉及** - ---- - -## 2. 领域模型(PlantUML) - -本轮 **无领域模型变更**。`BusinessRuleConfig` 的类型收紧属于配置绑定细节, -不改变任何聚合、值对象或状态机。 - -```plantuml -@startuml -skinparam classAttributeIconSize 0 - -class BusinessRuleConfig { - - appointment : Map - - auth : AuthConfig -} - -class AuthConfig { - - password : PasswordConfig - - token : TokenConfig - - publicEndpoints : List -} - -class PasswordConfig { - - minLength : int - - algorithm : String -} - -class TokenConfig { - - expirationMs : long - - algorithm : String -} - -BusinessRuleConfig *-- AuthConfig -AuthConfig *-- PasswordConfig -AuthConfig *-- TokenConfig -AuthConfig *-- "publicEndpoints : String" <> -@enduml -``` - ---- - -## 3. 数据库设计(SQL DDL) - -不涉及 —— 本轮目标接口不读写数据库,无表结构变更。 - ---- - -## 4. API 设计(OpenAPI) - -**无契约变更。** `docs/facts/api.yaml` 里 `BusinessRuleResponse.config` 是 -`{ type: object }`,本轮不细化它(细化属于契约变更,需另行评审)。 - -本轮修复后响应体的 **实际形状**(`config` 部分,现状 vs 修复后): - -```yaml -# 现状(publicEndpoints 是被绑坏的索引 Map) -config: - auth: - password: { minLength: 8, algorithm: BCrypt } - token: { expirationMs: 86400000, algorithm: HMAC-SHA256 } - publicEndpoints: { "0": "/api/v1/auth/**", "1": "/api/v1/home/**", ... } - -# 修复后(publicEndpoints 是真正的数组) -config: - auth: - password: { minLength: 8, algorithm: BCrypt } - token: { expirationMs: 86400000, algorithm: HMAC-SHA256 } - publicEndpoints: [ "/api/v1/auth/**", "/api/v1/home/**", "/api/v1/consultants/**", - "/api/v1/data-dictionaries/**", "/api/v1/business-rules/**" ] -``` - -> `config.appointment` 子树保持原样(`conflict` / `slot` / `available` / `cancel`), -> 不在本轮变更范围内。 - ---- - -## 5. 时序图(PlantUML) - -```plantuml -@startuml -participant "Spring Environment\n(含 business-rules/*.yml)" as Env -participant "BusinessRuleConfig\n(@ConfigurationProperties)" as Cfg -participant "BusinessRuleProvider\n(@PostConstruct)" as Prov -database "HTTP 响应\nList>" as Res - -Env -> Cfg : 绑定 appointment / auth -Cfg -> Cfg : auth.publicEndpoints\n→ List(不再是索引 Map) -Cfg -> Prov : 注入配置 Bean -Prov -> Prov : ObjectMapper.convertValue(cfg)\n→ Map(投影) -Prov -> Res : config.auth.publicEndpoints = ["...","..."] -@enduml -``` - ---- - -## 6. 专题设计(Markdown) - -### 6.1 权限设计 - -不涉及 —— `GET /api/v1/business-rules` 仍是 `permitAll`,本轮不改鉴权。 - -### 6.2 并发控制 - -不涉及 —— `BusinessRuleProvider` 在 `@PostConstruct` 里一次性建缓存,之后只读。 - -### 6.3 事务设计 - -不涉及 —— 只读接口,无写操作、无事务边界变化。 - -### 6.4 异常处理 - -本轮 **不改任何异常处理**。 - -要改的是 **文档对异常处理的描述**。改完之后 `AGENTS.md` §7 必须能回答三个问题: - -1. 有哪些异常 → 各自映射什么 HTTP 状态码与 errorCode? -2. 响应体长什么样? -3. 新代码该抛什么异常? - -答案(以 `GlobalExceptionHandler` 当前实现为准): - -| 抛出什么 | HTTP | errorCode | 什么时候用 | -|---|---|---|---| -| `IllegalArgumentException` | 400 | `PARAM_ERROR` | 参数不合法、查不到的资源(消息即 `errorMessage`) | -| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` | 业务状态冲突(如同一时段被占用) | -| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` | `@Valid` 字段级校验失败(自动抛出,不手写) | -| 其它 `Exception` | 500 | `SYSTEM_ERROR` | 兜底,消息固定为「系统繁忙」 | - -响应体(`GlobalExceptionHandler.ErrorResponse` 这个 record 的实际字段): - -```json -{ - "errorCode": "BUSINESS_CONFLICT", - "errorMessage": "该时段已被占用", - "data": null -} -``` - -鉴权失败由 Spring Security 直接返回 **401 / 403**,**不走** `ErrorResponse` 包装。 - -### 6.5 性能设计 - -不涉及 —— 投影在 `@PostConstruct` 里做一次,运行时开销不变。 - -### 6.6 扩展性设计 - -**这条是本轮的核心收益。** - -现在 `auth` 有了类型,`AuthConfig` 就是契约本身: - -- YAML 里少写一个键 → 绑定时用类里的默认值,**不会静默丢字段** -- YAML 里多写一个键 → Spring Boot 绑定到未知属性时会 **fail fast**(取决于 - `ignoreUnknownFields`,默认 true 则是静默忽略 —— 所以 §6.7 要求 YAML 与类同时改) -- YAML 里把列表写错形状 → 类型不匹配,启动即报错,而不是像现在这样 **静默产出 `{"0":...}`** - -`appointment` 保持 `Map`:它没有列表,今天是安全的; -但**如果将来往 `appointment.yml` 里加列表,会重现同一个 bug**。 -本轮在 `docs/standards/business-rule.md` 里把这条约束写清楚(§11.3)。 - -### 6.7 一致性约束(必须遵守) - -* **YAML 与 Java 类必须同时改。** `auth.yml` 的键结构 = `AuthConfig` 的字段结构, - 一一对应: - * `auth.password.minLength` → `PasswordConfig.minLength`(`int`) - * `auth.password.algorithm` → `PasswordConfig.algorithm`(`String`) - * `auth.token.expirationMs` → `TokenConfig.expirationMs`(`long`) - * `auth.token.algorithm` → `TokenConfig.algorithm`(`String`) - * `auth.publicEndpoints` → `AuthConfig.publicEndpoints`(`List`) -* **默认值必须与 YAML 一致。** 类里的字段默认值写死当前 YAML 里的值 - (8 / BCrypt / 86400000 / HMAC-SHA256 / 5 个端点), - 这样即使 YAML 加载失败,接口也不会返回"空壳"配置。 -* **`appointment` 子树保持 `Map`**,其 YAML 键与值本轮 **一个字都不改**。 -* **不改 YAML 文件内容**(`apps/backend/src/main/resources/business-rules/*.yml`), - 只改它对应的 Java 类型声明。 -* **不改 API 契约**:`docs/facts/api.yaml` 不动。 -* **不改 `SecurityConfig`、`GlobalExceptionHandler`、`ErrorResponse`**。 -* 命名: - * 测试方法名 `should_{action}_{expectedResult}` - * **不写 `TC-` 编号**(`TC-xxx` 是 QA 用例的编号体系,开发自测不进入编号空间, - 见 `AGENTS.md` §10) -* 归属:新增/修改的测试属于 **开发自测**(验证"代码按 Plan 的设计工作"), - **不是 QA 测试**,不进 `docs/test-cases/e2e-cases/`,也不进 `e2e/tests/qa/`。 - ---- - -## 7. 单元测试设计 - -本轮 **不新增单元测试**。 - -`BusinessRuleProvider` 的投影逻辑由 §9 的集成测试经由 HTTP 端到端覆盖 —— -它依赖 Spring 的 binder 与 YAML 装载,脱离 Spring 上下文做单元测试意义有限 -(且项目现有约定就是 API 层集成测试覆盖,见 `AGENTS.md` §10)。 - ---- - -## 8. 单元测试设计(补充:投影的内部契约) - -不涉及。 - ---- - -## 9. API 集成测试设计 - -### 9.1 测试范围 - -* 切片类型:全链路集成(`@SpringBootTest(webEnvironment = RANDOM_PORT)` + RestAssured) -* 真实加载组件:Controller → AppService → `BusinessRuleProvider` → `BusinessRuleConfig` → YAML -* Mock 边界:**无** -* 继承 `com.consultation.TestBase`(沿用 `@BeforeEach` 的 `resetDbService.resetAll()`) - -### 9.2 测试环境 - -* 数据库:MariaDB4j —— 本轮用例不读写 -* 中间件:无;下游服务:无 -* 迁移脚本:`spring.flyway.enabled=false`(test profile 已有) -* 鉴权:`permitAll`,用例不带 `Authorization` 头 - -### 9.3 用例覆盖场景 - -- [x] 契约校验:状态码、响应字段、错误返回结构 -- [x] 鉴权场景:免鉴权可访问(`permitAll` 契约) -- [x] 业务闭环:不涉及(只读接口) -- [x] 数据一致性:YAML → 接口透出(`publicEndpoints` 数组化 + 标量不回归) -- [ ] 状态机 / 并发幂等 / 下游异常:不涉及(只读接口,无状态流转) - -### 9.4 测试数据 - -* 数据准备:**不需要**。无 DB 写入 -* 隔离策略:沿用 `TestBase.setUp()` 的 `resetDbService.resetAll()` -* 断言规范:**RestAssured + Hamcrest + 少量 Java 断言** - -> ⚠️ **GPath 限制(上一轮踩过的坑)** -> -> RestAssured 5.3.2 走 Jayway/GPath,**`$[*]` 这类写法不被支持**, -> 且嵌套列表的展开行为不可靠。 -> 本轮涉及列表的断言 **一律走 `jsonPath().getList("$")` 取出 `List>`, -> 再用 Java 断言遍历**,不依赖 GPath 对嵌套列表的展开。 - -### 9.5 用例清单 - -#### 新增:`BusinessRuleControllerTest` 补 2 例 - -| # | 场景类型 | 用例说明 | 预期结果 | 关联章节 | -| :--: | :------: | :------ | :------ | :------ | -| 1 | 数据一致性 | `publicEndpoints` 是 JSON 数组 | 200;`config.auth.publicEndpoints` 是 `List`(**不是 Map**);长度 5;含 `/api/v1/auth/**`、`/api/v1/business-rules/**`;每项以 `/api/v1/` 开头 | §6.6 §6.7 | -| 2 | 数据一致性 | `auth` 下的标量配置未被类型化改动破坏 | 200;`config.auth.password.minLength == 8`、`password.algorithm == "BCrypt"`、`token.expirationMs == 86400000`、`token.algorithm == "HMAC-SHA256"` | §6.7 | - -用例 2 是 **防回归锚点**:把 `Map` 换成有类型的类时,最容易出的错就是 -数字类型被 Jackson 变成另一种数值类型、或字段名拼错 —— 用例 1 断言不出这类问题。 - -**合计 2 个新增用例。** 现有 5 例保持不变(`should_expose_yaml_config_for_each_rule` -里的 `config.appointment.slot.minMinutes` 与 `config.auth.token.expirationMs` 断言 -在改造后必须 **继续通过** —— 这是天然的回归网)。 - ---- - -## 11. 修改清单 - -### 11.1 代码修改 - -| 操作 | 文件 | 改动 | -| :--: | :-- | :-- | -| 改 | `apps/backend/src/main/java/com/consultation/domain/businessrule/BusinessRuleConfig.java` | `auth` 由 `Map` 改为有类型的嵌套类 `AuthConfig`(含 `PasswordConfig` / `TokenConfig` / `List publicEndpoints`);`appointment` 保持 `Map` | -| 改 | `apps/backend/src/main/java/com/consultation/infrastructure/config/BusinessRuleProvider.java` | 注入 `ObjectMapper`,在 `@PostConstruct` 里把 `BusinessRuleConfig` 投影为 `Map` 后再挂进 `config`,保证对外返回结构不变(除 `publicEndpoints` 变回数组) | - -> **为什么投影放在 Provider(infrastructure)而不是让 domain 直接返回 POJO**: -> `BusinessRuleConfig` 在 `domain` 层,`AGENTS.md` §3 要求 domain 不依赖基础设施; -> 而 JSON 形状是基础设施关注点。所以 domain 保持纯 Java 类型, -> 由 infrastructure 用 `ObjectMapper` 做投影,对外契约 -> `List>` **一个字都不变**, -> `BusinessRuleAppService` / `BusinessRuleController` **不需要改**。 - -### 11.2 接口变更 - -无。 - -### 11.3 文档修改 - -| 操作 | 文件 | 改动 | -| :--: | :-- | :-- | -| 改 | `AGENTS.md` §7 | 按 `GlobalExceptionHandler` 实际实现重写错误模型:4 条异常映射表 + 真实响应体 `{errorCode, errorMessage, data}`;删除不存在的 `BusinessException` / `APPOINTMENT_CONFLICT` / `message` / `timestamp` | -| 改 | `AGENTS.md` §12 | 检查清单里「业务校验使用 `BusinessException`」改为实际异常类型(`IllegalArgumentException` / `IllegalStateException`);3 条 `docs/dev/design-fact/**` 死链改指 `docs/facts/**` | -| 改 | `docs/standards/error.md` | 删除 `IError` / `ErrorGroup` / `AbstractException` 异常类层次(代码里不存在);换成 §6.4 的实际映射表;错误码表指向 `docs/facts/tech-topic/error-code.md`(修死链) | -| 改 | `docs/standards/business-rule.md` | 结尾死链 `docs/dev/design-fact/others/businessrule.md` → `docs/facts/tech-topic/businessrule.md`;补一条约束:**只有列表会被 `Map` 绑坏**,将来往 YAML 加列表前必须先给对应配置类加类型 | -| 改 | `docs/standards/data-dictionary.md` | 结尾死链 `docs/dev/design-fact/others/data-dict.md` → `docs/facts/tech-topic/data-dict.md` | -| 改 | `docs/facts/tech-topic/businessrule.md` | 认证规则表的「配置路径」列改为真实来源(`auth.yml → token.expirationMs` 而非 `application.yml → jwt.expiration`;`auth.yml → password.algorithm` 而非 `SecurityConfig (hardcoded)`) | - -### 11.4 文档同步检查 - -| 文档 | 是否需要更新 | 理由 | -|---|---|---| -| `docs/facts/api.yaml` | **不涉及** | 无 API 契约变更(`config` 仍是自由 object) | -| `docs/facts/db-schema.md` | **不涉及** | 无表结构变更 | -| `docs/facts/tech-topic/businessrule.md` | **已更新** | 配置路径列与实现对齐(§11.3) | -| `docs/facts/tech-topic/data-dict.md` | **不涉及** | 字典定义未变 | -| `docs/facts/tech-topic/error-code.md` | **不涉及** | 其"当前实现映射"表已如实记录现状,无需改 | -| `docs/test-cases/e2e-cases/test-cases.md` | **不涉及** | 属开发自测,不是 QA 用例;无新需求、无验收标准变化 | -| `docs/standards/error.md` | **已更新** | 见 §11.3 | -| `docs/standards/business-rule.md` | **已更新** | 见 §11.3 | -| `docs/standards/data-dictionary.md` | **已更新** | 见 §11.3 | -| `AGENTS.md` | **已更新** | §7 / §12,见 §11.3 | - ---- - -## 12. 验证步骤 - -1. **基线(改动前)**:`cd apps/backend && mvn -o -B test` → 期望 `Tests run: 28, Failures: 0, Errors: 0` -2. **实现后**:`cd apps/backend && mvn -o -B test` → 期望 `Tests run: 30, Failures: 0, Errors: 0` - (28 基线 + 2 新增) -3. **只看新用例**:`cd apps/backend && mvn -o -B test -Dtest='BusinessRuleControllerTest'` - → 期望 `Tests run: 7, Failures: 0, Errors: 0`(原 5 + 新 2) -4. **确认没碰不该碰的**: - * `git status --short` → 只应出现 §11.1 / §11.3 列出的文件 - * `git diff -- apps/backend/src/main/resources/business-rules/` → **必须为空**(YAML 不改) - * `git diff -- apps/backend/src/main/java/com/consultation/adapter/` → **必须为空** - * `git diff -- apps/backend/src/main/java/com/consultation/application/` → **必须为空** - * `git diff -- docs/facts/api.yaml` → **必须为空** -5. **确认死链已清**:`grep -rn "design-fact" --include="*.md" . | grep -v "docs/plans/"` - → 无输出(`docs/plans/` 下会命中本 Plan 自身对死链路径的引用,属正常) -6. **确认文档里的错误码与代码一致**: - `grep -rn 'new ErrorResponse("' apps/backend/src/main` 的 4 个错误码, - 与 `AGENTS.md` §7 表格逐条对得上 -7. **确认没有引入 `TC-` 编号**:`grep -rn "TC-" apps/backend/src/test/` → 无输出 - ---- - -## 13. 风险与回滚 - -* **风险点 1:类型化后默认值与 YAML 不一致。** - 缓解:`AuthConfig` 各字段默认值 **写死当前 YAML 的值**; - 用例 2 会断言实际透出的值,任何一边改了另一边没跟上都会红。 - -* **风险点 2:`ObjectMapper` 投影改变了数值类型。** - 例:`expirationMs` 若声明成 `int` 而非 `long`,大数会溢出; - `minMinutes` 若声明成 `String`,JSON 里会变成 `"30"`。 - 缓解:用例 2 用 `((Number) x).intValue()` 取值再断言, - 既能挡住类型漂移,又不受 Integer/Long 装箱差异影响。 - -* **风险点 3:投影把 `appointment` 子树也洗了一遍。** - `appointment` 本来就是 `Map`,Jackson 往返后值类型可能从 - `Integer` 变 `Integer`、从 `String` 变 `String`(不变), - 但理论上可能出现 `LinkedHashMap` → `LinkedHashMap` 的键序变化。 - 缓解:现有用例 `should_expose_yaml_config_for_each_rule` 断言 - `config.appointment.slot.minMinutes == 30`,它必须继续通过; - 若它变红,说明投影方式选错了 —— **此时应改实现,不是改断言**。 - -* **风险点 4:`publicEndpoints` 变数组属于"对外可见的行为变更"。** - 下游若已按 `{"0":...}` 消费,改完会坏。 - 但 `{"0":...}` 从来不是任何文档承诺过的形状(`api.yaml` 只说 `config: {type: object}`), - 且当前没有任何消费方依赖这个形状(已核实:`apps/frontend/src` 无引用; - `e2e/tests/qa/app.spec.ts` 的 TC-004 只断言该接口 HTTP 200,不读 `config`)。 - 结论:**属于修 bug,不是破坏兼容**。 - -* **回滚方案**: - 生产代码改动集中在 2 个文件,`git checkout` 这 2 个文件即可完全回滚; - 测试是新增 2 例,删除即可;文档改动可单独回滚。 - 全程无 DDL、无数据迁移、无配置中心变更,**回滚零副作用**。 - ---- - -## 14. 实施后需更新的 design 文档 - -见 §11.3(`docs/facts/tech-topic/businessrule.md` 已列入本轮修改清单)。 - ---- - -## 15. 变更记录(可选) - -| 版本 | 日期 | 变更内容 | -| ---- | ---------- | -------- | -| v1.0 | 2026-11-06 | 初始版本 | diff --git a/example-project/docs/features/iteration1/plan-20261116-iteration1-feature-skeletons.md b/example-project/docs/features/_chores/plan-20261116-iteration1-feature-skeletons.md similarity index 100% rename from example-project/docs/features/iteration1/plan-20261116-iteration1-feature-skeletons.md rename to example-project/docs/features/_chores/plan-20261116-iteration1-feature-skeletons.md diff --git a/example-project/docs/features/iteration1/plan-20261116-iteration1-prototypes-and-specs.md b/example-project/docs/features/_chores/plan-20261116-iteration1-prototypes-and-specs.md similarity index 100% rename from example-project/docs/features/iteration1/plan-20261116-iteration1-prototypes-and-specs.md rename to example-project/docs/features/_chores/plan-20261116-iteration1-prototypes-and-specs.md diff --git a/example-project/docs/features/iteration1/plan-20261116-iteration1-prototypes-vite.md b/example-project/docs/features/_chores/plan-20261116-iteration1-prototypes-vite.md similarity index 100% rename from example-project/docs/features/iteration1/plan-20261116-iteration1-prototypes-vite.md rename to example-project/docs/features/_chores/plan-20261116-iteration1-prototypes-vite.md diff --git a/example-project/docs/features/_chores/plan-20261117-purge-demo-impl-for-iteration1.md b/example-project/docs/features/_chores/plan-20261117-purge-demo-impl-for-iteration1.md new file mode 100644 index 0000000..832a5bd --- /dev/null +++ b/example-project/docs/features/_chores/plan-20261117-purge-demo-impl-for-iteration1.md @@ -0,0 +1,402 @@ +# 清理示例实现,为 iteration1 新需求落地腾空 + +>日期: 2026-11-17 +> +>关联需求:docs/features/iteration1/(ACC~PLT 共 9 份 spec;本 chores 不实现业务) +> +>关联原型:docs/features/iteration1/prototypes/ +> +>**plan一旦定稿就不修改。** 同一横切二次改造新建 `plan-{slug}.md`,不修改本文件。 + +> 状态:**已确认执行**(2026-11-17)— 按 §1.3 拍板清理。 + + +## 1. 文档说明 + +### 1.1 背景 + +- **目标需求**:`docs/features/iteration1/`(ACC~PLT 共 9 份 spec + 独立 prototypes)。 +- **现状问题**:仓库里另有一套更早的「咨询预约」示例实现与配套 as-built 文档/用例,与 iteration1 **不对齐**,会干扰后续按规格实现。 +- **产品意图(2026-11-17)**:iteration1 是要实现的目标;**之前的代码和文档都清掉**。 + +### 1.2 目标 + +- **实现目标**: + 1. **删代码**:示例业务实现(后端四聚合与全层、前端业务页、测试、Flyway、E2E 旧断言)。 + 2. **删/复位文档**:凡描述「旧示例已实现状态」的文档一律清理(facts、旧 test-cases、旧 demo 相关 chores plan);不留误导性 as-built。 + 3. **保留**:`docs/features/iteration1/`(含 prototypes)、`docs/standards/`、`docs/features/_template/`、`AGENTS.md`、`.agents/skills/`、可编译空壳 `apps/` + 平台横切骨架。 + 4. 清理后工程 =「空壳 + iteration1 需求输入」,再按 AGENTS.md §14 为各 feature 开 plan 实现。 +- **技术边界**: + - 本 plan **只做清理与骨架复位**,不实现任何 iteration1 业务功能。 + - 不改父仓 harness 套件源码;仅动 `example-project/`。 + - **不改** `docs/features/iteration1/prototypes/` 的演示行为(可继续 `npm run dev`)。 + +### 1.3 关键决策(已按意图收敛,请最终确认) + +| # | 决策点 | 拍板 | +|---|---|---| +| D1 | 包名 `com.consultation` | **保留** | +| D2 | JWT / Security / UserContext 骨架 | **保留**空壳(无登录业务 API) | +| D3 | BusinessRule / DataDictionary 框架代码 | **保留**空注册;示例规则/字典枚举与 YAML **删除** | +| D4 | 旧 Flyway | **直接删除**脚本;不写 drop migration | +| D5 | iteration1 specs / prototypes / iteration1 README | **全部保留**(目标需求) | +| D6 | 「之前的文档」 | **清理**(见下表),不是只 stub 一句 | + +**D6 文档去留明细** + +| 路径 | 动作 | +|---|---| +| `docs/features/iteration1/**` | **保留** | +| `docs/standards/**`、`docs/features/_template/**` | **保留**(工程规范,非旧业务 as-built) | +| `docs/features/_chores/plan-20261116-iteration1-*.md` | **保留**(服务 iteration1 骨架/原型的历史 plan) | +| `docs/features/_chores/plan-20261117-purge-demo-impl-for-iteration1.md` | **保留**(本 plan) | +| `docs/features/_chores/plan-20260619-project-plan.md` | **删除**(旧示例总计划) | +| `docs/features/_chores/plan-20261106-*.md` | **删除**(旧示例修补 plan) | +| `docs/facts/api.yaml`、`db-schema.md`、`domain-model.md` | **删内容并改成空壳 stub**(标明尚未实现) | +| `docs/facts/business/booking-flow.md` | **删除** | +| `docs/facts/tech-topic/businessrule.md`、`data-dict.md`、`state-machine.md` | **删内容改 stub** 或删除文件(与空壳一致) | +| `docs/facts/tech-topic/001~005`、`error-code.md`、`security.md` | **保留框架向说明**(仍约束空壳:分层/UUID/JWT/ThreadLocal/错误模型);去掉「已实现某业务 API」的表述 | +| `docs/test-cases/e2e-cases|manual-cases|smoking-cases/**` | **清空为目录 + 短 stub**(无旧 TC-xxx) | +| `docs/test-cases/README.md`、`dev-self-cases/README.md` | **保留并改写**为指向「用例待按 iteration1 编写」 | +| 根 `README.md` | **改写**为空壳说明 + 指向 iteration1 | + +以下正文按上表执行;若最终确认有偏差,先改口再动手。 + +--- + +## 2. 领域模型(PlantUML) + +本次无新增领域实体。清理后 domain 层为空(或仅保留与平台骨架相关的空包)。 + +```plantuml +@startuml +title 清理后 — 无业务聚合(占位) + +note as N + User / Consultant / Appointment / Branch + 及其 VO、DomainService 全部移除。 + 后续按 iteration1 各 feature 的 plan 重新引入。 +end note +@enduml +``` + +--- + +## 3. 数据库设计(SQL DDL) + +清理后 **无业务表**。删除现有 migration: + +- `apps/backend/src/main/resources/db/migration/V20260619__init_user.sql` +- `apps/backend/src/main/resources/db/migration/V20260620__consultant_appointment.sql` +- `apps/backend/src/main/resources/db/migration/V20260621__branch.sql` + +测试用 `schema.sql` / `data.sql` 同步清空为最小可启动(可仅保留空文件或注释说明)。 + +后续 iteration1 实现时再新增 Flyway(建议新序列,如 `V20261117__...` 起),并同步 `docs/facts/db-schema.md`。 + +```sql +-- 清理后无业务 DDL。占位:工程可启动,Flyway 无待执行脚本即可。 +``` + +--- + +## 4. API 设计(OpenAPI) + +清理后对外仅保留(可选)健康/首页探针;业务 API 全部移除。 + +```yaml +openapi: 3.0.0 +info: + title: Consultation Platform API (skeleton) + version: 0.0.0 +paths: + /api/v1/health: + get: + summary: 存活探针(骨架) + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: UP +``` + +原 Auth / User / Consultant / Appointment / Admin / BusinessRule / DataDictionary 业务路径从 `docs/facts/api.yaml` 移除或文件复位为上述骨架。 + +--- + +## 5. 时序图(PlantUML) + +```plantuml +@startuml +actor Dev +participant "apps/backend" as BE +participant "apps/frontend" as FE +participant "docs/facts" as Facts + +Dev -> BE : 删除业务包 / migration / 测试 +Dev -> FE : 删除业务视图,保留壳 +Dev -> Facts : 复位 as-built stub +BE --> Dev : mvn -q -DskipTests compile 通过 +FE --> Dev : npm run build 通过 +note over Dev + 确认后停止。 + iteration1 各 feature 另开 plan 再实现。 +end note +@enduml +``` + +--- + +## 6. 专题设计(Markdown) + +### 6.1 权限设计 + +* 保留 JWT 相关类与 `SecurityConfig` 骨架;清理后默认策略:**除 `/api/v1/health`(及静态/前端代理)外,其它 `/api/**` 需认证或直接 401**(实现时取「仅放行 health」最简配置,避免空壳被误用)。 +* 删除依赖 User 仓储的登录/注册过滤器业务路径;无 token 签发入口直至 ACC plan 落地。 + +### 6.2 并发控制 + +* 不适用(无写路径)。 + +### 6.3 事务设计 + +* 保留「事务在 application 层」规范;清空后无 `@Transactional` 业务方法。 + +### 6.4 异常处理 + +* **保留** `GlobalExceptionHandler` 与现有错误码约定(见 `docs/standards/error.md` / `docs/facts/tech-topic/error-code.md` 中与框架相关的部分)。 + +### 6.5 性能设计 + +* 不适用。 + +### 6.6 扩展性设计 + +* 包结构与分层目录保留空包或 README 占位,便于按 `docs/standards/templates/` 再生成。 + +--- + +## 7. 一致性约束(必须遵守) + +* 清理后:`docs/facts/` 不得再描述已删除的表/API/聚合。 +* `docs/features/iteration1/**` 规格与原型 **不得** 因本次清理被改写业务规则(仅允许在 README 中加一句「业务实现已复位,待按 feature plan 重建」类说明,可选)。 +* 命名与分层规范仍以 `AGENTS.md` / `docs/standards/` 为准。 +* 不引入与清理无关的依赖升级。 + +--- + +## 8. 单元测试设计 + +### 8.1 测试范围 + +* 删除全部示例相关单元/领域测试。 +* 骨架阶段可不新增单元测试;若保留 `GlobalExceptionHandler`,可选留 1 个轻量测试(非必须)。 + +### 8.2~8.4 + +* 策略沿用项目规范;本 chores 以删除为主。 + +### 8.5 用例清单 + +| 被测单元 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :------: | :------: | :------: | :------: | :------: | +| (清理) | — | 删除旧 `*Test` 中业务用例 | 无编译引用残留 | §11 | +| Health(可选) | 正常 | 探针返回 UP | 200 | §4 | + +--- + +## 9. API 集成测试设计 + +### 9.1 测试范围 + +* 删除现有 RestAssured 业务集成测试(Auth/Appointment/Admin 等)。 +* 可选保留:`should_return_up_when_get_health` 一条,证明空壳可起。 + +### 9.2 测试环境 + +* 仍用 MariaDB4j + `@ActiveProfiles("test")`;`schema.sql`/`data.sql` 置空或最小。 +* Flyway test 继续 `enabled=false`(与现约定一致)。 + +### 9.5 用例清单 + +| 接口 | 场景类型 | 用例说明 | 预期结果 | 关联章节 | +| :--: | :------: | :------: | :------: | :------: | +| `GET /api/v1/health` | Happy | 空壳启动后可访问 | 200 + status=UP | §4 | + +--- + +## 10. E2E 测试设计 + +### 10.1 测试范围 + +* `e2e/tests/qa/app.spec.ts`、`e2e/tests/dev/visual.spec.ts`:改为仅断言前端壳首页可打开(或暂时 `test.skip` 并在 README 注明待 iteration1 重建)。 +* `docs/test-cases/e2e-cases/test-cases.md` 等:清空旧 TC 正文,保留目录与「用例归属」说明,或改为 stub「暂无 QA 用例,待 feature 编写」。 + +### 10.6 用例清单 + +| 链路名称 | 覆盖步骤 | 验证点 | 关联章节 | +| :------: | :------: | :----: | :------: | +| 壳冒烟(dev) | 打开 `/` | 标题/入口存在 | §11 | + +--- + +## 11. 修改清单 + +### 11.1 代码修改 + +#### 11.1.3 删除 — 后端业务 + +删除(含测试对称文件,路径以仓库实存为准): + +**adapter** + +- `apps/backend/src/main/java/com/consultation/adapter/rest/AdminController.java` +- `.../AppointmentController.java` +- `.../AuthController.java` +- `.../ConsultantController.java` +- `.../UserController.java` +- `.../BusinessRuleController.java`(若 D3 选保留框架则改为空列表实现,否则删除) +- `.../DataDictionaryController.java`(同上) +- `.../HomeController.java`(若与业务耦合则删;健康探针改独立 `HealthController`) +- `adapter/rest/dto/**` 业务 DTO + +**application** + +- `application/service/*`(Admin/Appointment/Auth/Consultant/User 及 BusinessRule/DataDictionary 若无空壳价值则删) +- `application/assembler/**` + +**domain** + +- `domain/aggregate/{User,Consultant,Appointment,Branch}.java` +- `domain/vo/**` 业务枚举 +- `domain/repository/**` +- `domain/service/**` 业务域服务 +- `domain/businessrule` / `domain/datadictionary`:按 D3 — 建议保留接口与空注册,删除 Appointment/Auth 等示例规则枚举与 YAML 业务条目 + +**infrastructure** + +- `repositoryimpl/**` +- `persistence/po/**`、`mapper/**`、`converter/**` 业务文件 +- 保留:`GlobalExceptionHandler`、`SecurityConfig`(改配置)、`Jwt*`、`UserContext*`、`JacksonConfig`、`WebConfig`、`MybatisPlusConfig` +- 删除:`PasswordServiceImpl` 若仅服务已删 Auth;或留接口空实现待 ACC + +**resources** + +- 删除上述 3 个 Flyway 业务脚本 +- `resources/business-rules/**` 示例规则 YAML:清空或删 +- test `schema.sql` / `data.sql` / `ResetDbService` 业务表逻辑:改空 + +**测试** + +- `apps/backend/src/test/java/**` 中业务 `*Test.java` 全部删除 + +#### 11.1.2 新增 — 后端骨架 + +- `adapter/rest/HealthController.java` — `GET /api/v1/health` +- (可选)各层空包保持 `package-info.java` 或目录存在即可 +- 最小集成测试 `HealthControllerTest`(可选) + +#### 11.1.3 删除 — 前端业务 + +- `apps/frontend/src/views/admin/**` +- `apps/frontend/src/views/user/**`(业务页) +- `apps/frontend/src/views/auth/**`(登录注册;ACC 再做) +- 业务 API `src/api/**`、业务 composables、业务类型字段 + +#### 11.1.1 修改 — 前端壳 + +- `router/index.ts` — 仅 `/` 首页 +- `views/home/HomePage.vue` — 改为「工程骨架 / 指向 iteration1 原型与规格」的占位页(可链到规格路径说明,勿依赖后端业务) +- `stores/auth.ts` — 清空为最小 store 或删除并去掉引用 +- `components/layout/*` — 收拢为单一简单布局或极简 header + +#### 11.1.3 删除/修改 — E2E 与用例文本 + +- 重写或瘦身:`e2e/tests/qa/app.spec.ts`、`e2e/tests/dev/visual.spec.ts` +- stub:`docs/test-cases/e2e-cases/test-cases.md`、`manual-cases/`、`smoking-cases/` 中旧 TC + +#### 11.1.x 关键文件速查 + +| 操作 | 文件 / 目录 | 备注 | +| :--: | :-- | :-- | +| 删除 | `apps/backend/.../domain/aggregate/*` | 四聚合 | +| 删除 | `apps/backend/.../adapter/rest/*Controller`(业务) | 见上 | +| 删除 | `apps/backend/.../db/migration/V20260619*.sql` 等三份 | Flyway | +| 删除 | `apps/frontend/src/views/{admin,user,auth}/**` | 业务 UI | +| 新增 | `.../HealthController.java` | 探针 | +| 修改 | `SecurityConfig.java` | 仅放行 health | +| 修改 | `apps/frontend/src/router/index.ts` | 仅首页 | +| 复位 | `docs/facts/api.yaml` | 骨架 OpenAPI | +| 复位 | `docs/facts/db-schema.md` | 无表说明 | +| 复位 | `docs/facts/domain-model.md` | 无聚合说明 | +| 修订 | `docs/facts/tech-topic/businessrule.md`、`data-dict.md`、`state-machine.md` 等 | 去掉示例业务内容或标「待重建」 | +| 修订 | `README.md` | 说明当前为空壳,需求见 iteration1 | +| 保留 | `docs/features/iteration1/**` | 含 prototypes | +| 保留 | `docs/standards/**`、`AGENTS.md`、`.agents/**` | harness | + +### 11.2 接口变更 + +| 路径 | 方法 | 变更类型 | 说明 | +| :--: | :--: | :--: | :-- | +| `/api/v1/health` | GET | 新增 | 骨架探针 | +| `/api/v1/**` 原业务 | * | 删除 | Auth/预约/管理等全部下线 | +| `/admin/**` | * | 删除 | 管理端 API 下线 | + +### 11.3 数据库变更 + +- 删除既有 Flyway 业务脚本(非新增 V__drop)。 +- 影响表:`user` / `consultant` / `appointment` / `branch`(及脚本中实际表名)——**结构从代码库消失**;本地/开发库需手动 drop 或重建空库(写入 README 注意点)。 +- 数据迁移:无;示例数据不保留。 + +--- + +## 12. 验证步骤 + +1. `cd apps/backend && mvn -q test`(或至少 `mvn -q -DskipTests compile`)— 编译通过;若有 Health 测试则绿灯。 +2. `cd apps/frontend && npm run build` — 通过。 +3. 启动后端,`curl -s http://localhost:8080/api/v1/health` — 期望 `{"status":"UP"}`(字段以实作为准)。 +4. 启动前端,`/` 可打开占位页;无预约/登录业务路由。 +5. `rg -n "Appointment|BookAppointment|ROLE_ADMIN" apps/` — 无业务残留(允许注释/文档外代码零命中)。 +6. 确认 `docs/features/iteration1/prototypes` 仍可 `npm run dev`(本 chores 不破坏)。 +7. (可选)父仓 `./.agents/verify.sh` 若依赖 example-project 路径 — 确认仍绿。 + +--- + +## 13. 风险与回滚 + +- **风险**:误删平台骨架导致后续 ACC 重复搭建;缓解:D2/D3 按建议保留。 +- **风险**:facts 未同步导致 Agent 按旧 API 编码;缓解:§11 强制复位 facts,验证步骤 5。 +- **风险**:本地 MySQL 仍留旧表;缓解:README 注明 drop database / 重建。 +- **回滚**:`git checkout` / `git restore` 回到清理前提交;不依赖 Flyway 回滚脚本。 + +--- + +## 14. 实施后需更新的事实文档 + +按 §1.3 D6 表执行(删除旧 demo 文档 + facts/test-cases 复位 + README 改写)。 +`docs/features/iteration1/README.md`:补一句「业务实现已清空,待按各 feature plan 落地」。 + +**docs 同步检查**:涉及 — 必须做。 + +--- + +## 15. 变更记录 + +| 版本 | 日期 | 变更内容 | +| ---- | ---------- | -------- | +| v1.0 | 2026-11-17 | 初稿 | +| v1.1 | 2026-11-17 | 按意图收紧:旧代码+旧文档清理;iteration1 为唯一目标需求 | + +--- + +## 确认清单(人工) + +- [x] D1~D6 按 §1.3 拍板表执行(含删除旧 chores plan / booking-flow / 旧 TC) +- [x] 保留 iteration1 + standards + 空壳 apps +- [x] 已确认执行(2026-11-17) diff --git a/example-project/docs/features/iteration1/README.md b/example-project/docs/features/iteration1/README.md index 096fa55..2867ea6 100644 --- a/example-project/docs/features/iteration1/README.md +++ b/example-project/docs/features/iteration1/README.md @@ -2,7 +2,8 @@ > 状态:**v0.1**(字段、规则、验收与原型已完成) > 日期:2026-11-16 -> 原型:独立 Vite Demo(Element Plus),见 [`prototypes/`](./prototypes/)(端口 5174) +> 原型:独立 Vite Demo(Element Plus),见 [`prototypes/`](./prototypes/)(端口 5174) +> **实现**:业务代码已清空为工程骨架;请按各 feature 的 plan 重新落地(见 `_chores/plan-20261117-purge-demo-impl-for-iteration1.md`)。 ## 1. 产品概述 diff --git a/example-project/docs/test-cases/e2e-cases/test-cases.md b/example-project/docs/test-cases/e2e-cases/test-cases.md index a1b5628..4b22cae 100644 --- a/example-project/docs/test-cases/e2e-cases/test-cases.md +++ b/example-project/docs/test-cases/e2e-cases/test-cases.md @@ -1,84 +1,6 @@ -# E2E 测试用例 — 咨询预约平台 +# E2E 测试用例(QA) -> **归属:QA 测试。** 本文件是 QA 验收用例的 **文本基线**,由 QA 定义与判定。 -> -> - 自动化实现位于 `e2e/tests/qa/app.spec.ts`,编号与本文件一一对应 -> - 自动化代码可由开发代写,但用例的 **定义权与判定权归 QA** -> - 需求规格的每条验收标准(`docs/features/*/§12`)与每条业务规则(`R-xxx`)都必须有对应用例 -> - **合并闸门**:本文件的用例未全部通过验收,不能合并 +> **归属:QA 测试。** 旧示例 TC 已清除。 +> 请按 `docs/features/iteration1/` 各 spec 的验收标准重新编写 `TC-xxx`,再实现 `e2e/tests/qa/`。 -> **不属于本文件的**:开发自测用例放在源码旁与 `e2e/tests/dev/`,只对开发本人负责,不是验收依据。 - -## 1. 公共页面 - -| # | 用例 | 步骤 | 预期 | -|---|---|---|---| -| TC-001 | 首页加载 | 访问 `/` | 页面显示标题"专业咨询服务"、"免费注册"、"立即预约"按钮、版权信息 | -| TC-002 | 登录页渲染 | 访问 `/login` | 显示邮箱/密码输入框、登录按钮、注册链接 | -| TC-003 | 注册页渲染 | 访问 `/register` | 显示姓名/邮箱/手机/密码输入框、注册按钮、登录链接 | -| TC-004 | 公开 API 可用 | GET `/api/v1/data-dictionaries`、`/api/v1/business-rules`、`/api/v1/consultants` | 均返回 200,咨询师列表 ≥ 3 条 | -| TC-005 | 导航跳转 | 首页点击"登录" → 点击"立即注册" | URL 依次变为 `/login` → `/register` | - -## 2. 认证 - -| # | 用例 | 步骤 | 预期 | -|---|---|---|---| -| TC-006 | 管理员登录成功 | 填写 admin@test.com / password → 提交 | 跳转到 `/admin/dashboard`,显示"管理仪表盘" | -| TC-007 | 错误密码提示 | 填写 admin@test.com / wrongpassword → 提交 | 显示错误提示 | -| TC-008 | 注册新用户 | 填写姓名/邮箱/手机/密码 → 提交 | 跳转到 `/user/dashboard`,显示用户姓名 | -| TC-009 | 重复邮箱注册 | 使用已注册邮箱再次注册 | 显示错误提示 | -| TC-010 | 新用户登录 | 使用刚注册的账号登录 | 跳转到 `/user/dashboard`,显示"用户中心" | - -## 3. 用户流程 - -| # | 用例 | 步骤 | 预期 | -|---|---|---|---| -| TC-011 | 用户仪表盘 | 登录后访问 `/user/dashboard` | 显示"总预约"、"待确认"、"已完成"统计卡片 | -| TC-012 | 浏览咨询师 | 访问 `/user/book` | 显示张医生、李律师、王教练三条记录 | -| TC-013 | 预约 + 取消 | 选咨询师 → 选日期 → 选时间 → 填备注 → 提交 → 取消 | 预约成功跳转预约列表 → 取消后显示"已取消"状态 | -| TC-014 | 编辑个人信息 | 访问 `/user/profile` → 修改姓名 → 保存 | 弹出"保存成功"提示 | - -## 4. 管理员流程 - -| # | 用例 | 步骤 | 预期 | -|---|---|---|---| -| TC-015 | 仪表盘统计 | 管理员登录 → 访问 `/admin/dashboard` | 显示用户数 / 咨询师 / 总预约 / 待确认 / 网点五个卡片 | -| TC-016 | 用户管理 | 访问 `/admin/users` | 表格显示 admin@test.com、管理员;可点击禁用/启用 | -| TC-017 | 咨询师管理 | 侧栏点击"咨询师管理" | 表格显示张医生、李律师、王教练 | -| TC-018 | 预约管理 | 侧栏点击"预约管理" | 页面标题为"预约管理" | -| TC-019 | 网点 CRUD | 新增网点(名称/地址/电话) → 保存 → 编辑 → 保存 → 删除 | 表格显示新建条目 → 修改后名称更新 → 删除后消失 | - -## 5. 边界情况 - -| # | 用例 | 步骤 | 预期 | -|---|---|---|---| -| TC-020 | 未登录访问管理页 | 清除 localStorage → 访问 `/admin/dashboard` | 跳转到 `/login` | -| TC-021 | 未登录访问用户页 | 清除 localStorage → 访问 `/user/dashboard` | 跳转到 `/login` | -| TC-022 | 首页 CTA 可见 | 未登录状态下访问 `/` | "免费注册"按钮可见 | - -## 测试数据 - -| 角色 | 邮箱 | 密码 | -|---|---|---| -| 管理员 | admin@test.com | password | -| 新注册用户 | (动态生成) | Test123456 | - -种子数据:3 位咨询师(张医生、李律师、王教练)、3 个网点(朝阳、海淀、浦东)。 - -## 用例 ↔ 自动化对照 - -| 文本用例 | 自动化用例(`e2e/tests/qa/app.spec.ts`) | 状态 | -|---|---|---| -| TC-001 ~ TC-022 | 同名 `test('TC-xxx ...')` | 22 / 22 已实现 | - -新增文本用例时,同步在自动化里加同名 `TC-xxx` 用例,并把状态改为"待实现"。 - -## 与开发自测的边界 - -| | 本文件(QA 测试) | 开发自测 | -|---|---|---| -| 位置 | `docs/test-cases/e2e-cases/` + `e2e/tests/qa/` | `apps/backend/src/test/`、`apps/frontend/src/**/*.test.ts`、`e2e/tests/dev/` | -| 依据 | 需求规格 | Plan | -| 闸门 | **是** | 否 | - -`e2e/tests/dev/` 下的用例(视觉冒烟等)是开发自测,**不能** 作为本文件的验收依据。 +当前基线:无业务验收用例(仅工程壳冒烟见自动化占位)。 diff --git a/example-project/docs/test-cases/manual-cases/manual-test-cases.md b/example-project/docs/test-cases/manual-cases/manual-test-cases.md index f09fe44..4a0856e 100644 --- a/example-project/docs/test-cases/manual-cases/manual-test-cases.md +++ b/example-project/docs/test-cases/manual-cases/manual-test-cases.md @@ -1,14 +1,3 @@ -# 手动执行用例 — 咨询预约平台 +# 手动测试用例(QA) -> **归属:QA 测试。** 自动化难以覆盖、或需要人工主观判断的场景写在这里。 -> 由 QA 定义与判定,是 **合并闸门** 的一部分。 - -## 用例清单 - -| # | 用例 | 前置条件 | 步骤 | 预期 | 执行人 | -|---|---|---|---|---|---| -| TC-M01 | 后台禁用用户后其登录态失效 | 存在普通用户 `user@test.com` | 管理员禁用该用户 → 用户端刷新页面 | 用户被强制登出,跳转登录页 | | -| TC-M02 | 同一时段重复预约的提示文案 | 已有 咨询师A + 某时段 的预约 | 用另一账号预约同一时段 | 提示"该时间段已被占用",errorCode = `APPOINTMENT_CONFLICT` | | -| TC-M03 | 移动端视口下布局不塌陷 | 已登录 | 视口宽度调至 375px | 首页与预约页排版正常,无横向滚动条 | | -| TC-M04 | 弱网下的加载态 | 浏览器限速 Slow 3G | 打开预约列表 | 显示加载态骨架,不出现空白页 | | -| TC-M05 | 刷新后表单草稿保留 | — | 在个人资料页填写昵称但不保存 → 刷新 | 昵称仍在输入框中 | | +> 旧示例用例已清除。待按 iteration1 规格补充 `TC-Mxx`。 diff --git a/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md b/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md index 4c02d75..2a29435 100644 --- a/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md +++ b/example-project/docs/test-cases/smoking-cases/smoking-test-cases.md @@ -1,22 +1,3 @@ -# 冒烟用例 — 咨询预约平台 +# 冒烟用例(QA) -> **归属:QA 测试。** 发版前必须全绿的一组最小用例集。 -> 目标:**5 分钟内跑完**,用于快速判断"能不能发"。 -> 自动化实现位于 `e2e/tests/qa/app.spec.ts`,本文件是它的精简视图。 - -## 用例清单 - -| # | 用例 | 冒烟点 | 预期 | 自动化 | -|---|---|---|---|---| -| TC-S01 | 服务启动 | 后端可启动、前端可加载 | 无启动错误,首页 200 | `qa/app.spec.ts` → Public Pages | -| TC-S02 | 登录 | 管理员正确凭据登录 | 跳转到 `/admin/dashboard` | `qa/app.spec.ts` → Auth | -| TC-S03 | 用户注册 | 全新邮箱注册 | 跳转到 `/user/dashboard`,显示用户名 | `qa/app.spec.ts` → Auth | -| TC-S04 | 核心预约链路 | 选咨询师 → 选时间 → 提交 | 预约成功,出现在预约列表 | `qa/app.spec.ts` → User Flows | -| TC-S05 | 管理端可读 | 管理员查看用户/预约/网点列表 | 三个列表均正常渲染 | `qa/app.spec.ts` → Admin Flows | -| TC-S06 | 数据库连通 | 写入后可读回 | 无连接错误,数据一致 | `qa/app.spec.ts` | - -## 执行 - -```bash -cd e2e && npm run test:qa -``` +> 旧示例用例已清除。待按 iteration1 规格补充 `TC-Sxx`。 diff --git a/example-project/e2e/tests/dev/visual.spec.ts b/example-project/e2e/tests/dev/visual.spec.ts index 7bc0a3a..ff0f904 100644 --- a/example-project/e2e/tests/dev/visual.spec.ts +++ b/example-project/e2e/tests/dev/visual.spec.ts @@ -1,153 +1,8 @@ import { test, expect } from '@playwright/test' -import { visualTest } from '../../helpers/visual-test' - -const ADMIN_EMAIL = 'admin@test.com' -const ADMIN_PASSWORD = 'password' - -const vlm = visualTest() - -/* ─────────────── Visual Tests ─────────────── */ - -test.describe('Visual Tests', () => { - - test('homepage hero section visual layout', async ({ page }) => { - test.skip(!vlm.isConfigured, 'VLM not configured (set VLM_API_KEY)') +test.describe('Dev visual smoke', () => { + test('homepage shell visible', async ({ page }) => { await page.goto('/') - const analysis = await vlm.analyze(page, { - prompt: `Describe the hero section of this consultation booking website homepage. - What is the main heading text? What buttons/actions are available? - List the exact text content you see.`, - fullPage: true, - }) - expect(analysis).toContain('专业咨询服务') - console.log('[Visual] Homepage analysis:', analysis) - }) - - test('login page form layout', async ({ page }) => { - test.skip(!vlm.isConfigured, 'VLM not configured') - - await page.goto('/login') - const analysis = await vlm.analyze(page, { - prompt: `Describe the login page form. What input fields are visible? - Are there any labels? What does the submit button say? - List all visible text elements.`, - }) - expect(analysis).toContain('登录') - console.log('[Visual] Login page analysis:', analysis) - }) - - test('calendar date picker renders consecutive dates', async ({ page }) => { - test.skip(!vlm.isConfigured, 'VLM not configured (set VLM_API_KEY)') - - // Login and go to book page - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - await page.goto('/user/book') - await expect(page.locator('h1')).toHaveText('预约咨询') - - // Select a consultant to reveal the date picker - await page.locator('text=张医生').click() - await expect(page.locator('text=2. 选择日期')).toBeVisible() - - // Visual analysis of the date picker - const analysis = await vlm.analyze(page.locator('.booking-steps'), { - prompt: `Analyze the date picker section (step 2). - 1. How many date buttons are shown? - 2. List each date in YYYY-MM-DD format. - 3. Are the dates consecutive (no gaps)? - 4. Is today's date included as the first option? - Return the list of dates and your observations.`, - }) - console.log('[Visual] Date picker analysis:', analysis) - - // Verify the date format is correct (YYYY-MM-DD) - const dates = analysis.match(/\d{4}-\d{2}-\d{2}/g) - expect(dates).not.toBeNull() - expect(dates!.length).toBeGreaterThanOrEqual(5) - }) - - test('admin dashboard stat cards layout', async ({ page }) => { - test.skip(!vlm.isConfigured, 'VLM not configured') - - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - const analysis = await vlm.analyze(page.locator('.stats-grid'), { - prompt: `Analyze the dashboard statistics grid. - 1. How many stat cards are visible? - 2. For each card, what is the number/value and what is its label? - 3. Are all cards displayed in a grid layout? - List each card's content.`, - }) - expect(analysis).toContain('用户数') - expect(analysis).toContain('咨询师') - expect(analysis).toContain('总预约') - expect(analysis).toContain('网点') - console.log('[Visual] Dashboard stats analysis:', analysis) - }) - - test('booking flow visual consistency (consultant → date → time → confirm)', async ({ page }) => { - test.skip(!vlm.isConfigured, 'VLM not configured') - - // Login and go to book page - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - await page.goto('/user/book') - await page.locator('text=张医生').click() - await expect(page.locator('text=2. 选择日期')).toBeVisible() - - // Pick a date to reveal time slots - const dateBtn = page.locator('div.date-list button').first() - await dateBtn.click() - await page.waitForTimeout(1500) - - // Full booking form visual analysis - const analysis = await vlm.analyze(page.locator('.booking-steps'), { - prompt: `Analyze this multi-step booking form. - 1. How many steps are currently visible? - 2. Which consultant is currently selected? - 3. What date was chosen? - 4. Are time slots visible? If yes, list the available times. - 5. Describe the overall layout and completeness of the form. - Give a detailed step-by-step description.`, - }) - console.log('[Visual] Booking form analysis:', analysis) - }) - - test('admin sidebar navigation renders all links', async ({ page }) => { - test.skip(!vlm.isConfigured, 'VLM not configured') - - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - const analysis = await vlm.analyze(page.locator('.sidebar'), { - prompt: `Analyze the admin sidebar navigation. - 1. List all navigation links visible. - 2. Is there a logout button? - 3. What is the title of the sidebar? - List all link text.`, - }) - expect(analysis).toContain('仪表盘') - expect(analysis).toContain('用户管理') - expect(analysis).toContain('咨询师管理') - expect(analysis).toContain('预约管理') - expect(analysis).toContain('网点管理') - expect(analysis).toContain('退出') - console.log('[Visual] Sidebar analysis:', analysis) + await expect(page.locator('h1')).toBeVisible() }) }) diff --git a/example-project/e2e/tests/qa/app.spec.ts b/example-project/e2e/tests/qa/app.spec.ts index 9aaa2cd..6b96e74 100644 --- a/example-project/e2e/tests/qa/app.spec.ts +++ b/example-project/e2e/tests/qa/app.spec.ts @@ -1,341 +1,9 @@ import { test, expect } from '@playwright/test' -const BASE = 'http://localhost:5173' -const ADMIN_EMAIL = 'admin@test.com' -const ADMIN_PASSWORD = 'password' - -/* ─────────────── Public Pages ─────────────── */ - -test.describe('Public Pages', () => { - - test('TC-001 首页加载', async ({ page }) => { +test.describe('Skeleton smoke (QA placeholder)', () => { + test('homepage shell loads', async ({ page }) => { await page.goto('/') - await expect(page.locator('h1')).toHaveText('专业咨询服务') - await expect(page.locator('text=免费注册')).toBeVisible() - await expect(page.locator('text=立即预约')).toBeVisible() - await expect(page.locator('text=© 2026 咨询预约平台')).toBeVisible() - }) - - test('TC-002 登录页渲染', async ({ page }) => { - await page.goto('/login') - await expect(page.locator('h2')).toHaveText('登录') - await expect(page.locator('input[type="email"]')).toBeVisible() - await expect(page.locator('input[type="password"]')).toBeVisible() - await expect(page.locator('button[type="submit"]')).toHaveText('登录') - await expect(page.locator('text=还没有账号?')).toBeVisible() - }) - - test('TC-003 注册页渲染', async ({ page }) => { - await page.goto('/register') - await expect(page.locator('h2')).toHaveText('注册') - await expect(page.locator('input[type="email"]')).toBeVisible() - await expect(page.locator('input[type="password"]')).toBeVisible() - await expect(page.locator('button[type="submit"]')).toHaveText('注册') - await expect(page.locator('text=已有账号?')).toBeVisible() - }) - - test('TC-004 公开 API 可用', async ({ request }) => { - let resp = await request.get(`${BASE}/api/v1/data-dictionaries`) - expect(resp.status()).toBe(200) - - resp = await request.get(`${BASE}/api/v1/business-rules`) - expect(resp.status()).toBe(200) - - resp = await request.get(`${BASE}/api/v1/consultants`) - expect(resp.status()).toBe(200) - const body = await resp.json() - expect(body.length).toBeGreaterThanOrEqual(3) - }) - - test('TC-005 导航跳转', async ({ page }) => { - await page.goto('/') - await page.click('text=登录') - await expect(page).toHaveURL('/login') - - await page.click('text=立即注册') - await expect(page).toHaveURL('/register') - }) -}) - -/* ─────────────── Auth & User Lifecycle (serial: share registered email) ─────────────── */ - -let registerEmail = '' - -test.describe.serial('Auth & User Lifecycle', () => { - - test('TC-006 管理员登录成功', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - await expect(page.locator('h1')).toHaveText('管理仪表盘') - }) - - test('TC-007 错误密码提示', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', 'wrongpassword') - await page.click('button[type="submit"]') - await expect(page.locator('.error')).toBeVisible({ timeout: 8000 }) - }) - - test('TC-008 注册新用户', async ({ page }) => { - registerEmail = `e2e_${Date.now()}@test.com` - await page.goto('/register') - - await page.locator('input[placeholder*="姓名"]').fill('E2E用户') - await page.fill('input[type="email"]', registerEmail) - await page.locator('input[placeholder*="选填"]').fill('13800000001') - await page.fill('input[type="password"]', 'Test123456') - - await page.click('button[type="submit"]') - await page.waitForURL('**/user/dashboard', { timeout: 10000 }) - await expect(page.locator('text=E2E用户')).toBeVisible() - }) - - test('TC-009 重复邮箱注册', async ({ page }) => { - await page.goto('/register') - await page.locator('input[placeholder*="姓名"]').fill('重复用户') - await page.fill('input[type="email"]', registerEmail) - await page.fill('input[type="password"]', 'Test123456') - await page.click('button[type="submit"]') - await expect(page.locator('.error')).toBeVisible({ timeout: 8000 }) - }) - - test('TC-010 新用户登录', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', registerEmail) - await page.fill('input[type="password"]', 'Test123456') - await page.click('button[type="submit"]') - await page.waitForURL('**/user/dashboard', { timeout: 10000 }) - await expect(page.locator('h1').first()).toHaveText('用户中心') - }) - - test('TC-011 用户仪表盘', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', registerEmail) - await page.fill('input[type="password"]', 'Test123456') - await page.click('button[type="submit"]') - await page.waitForURL('**/user/dashboard', { timeout: 10000 }) - - await expect(page.locator('.stat-card').filter({ hasText: '总预约' })).toBeVisible() - await expect(page.locator('text=待确认')).toBeVisible() - await expect(page.locator('text=已完成')).toBeVisible() - }) - - test('TC-012 浏览咨询师', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', registerEmail) - await page.fill('input[type="password"]', 'Test123456') - await page.click('button[type="submit"]') - await page.waitForURL('**/user/dashboard', { timeout: 10000 }) - - await page.goto('/user/book') - await expect(page.locator('h1')).toHaveText('预约咨询') - await expect(page.locator('text=张医生')).toBeVisible() - await expect(page.locator('text=李律师')).toBeVisible() - await expect(page.locator('text=王教练')).toBeVisible() - }) - - test('TC-013 预约 + 取消', async ({ page }) => { - // Login - await page.goto('/login') - await page.fill('input[type="email"]', registerEmail) - await page.fill('input[type="password"]', 'Test123456') - await page.click('button[type="submit"]') - await page.waitForURL('**/user/dashboard', { timeout: 10000 }) - - // Go to book page - await page.goto('/user/book') - await expect(page.locator('h1')).toHaveText('预约咨询') - - // Step 1: Select consultant - await page.locator('text=张医生').click() - await expect(page.locator('text=2. 选择日期')).toBeVisible() - - // Step 2: Pick a date - const dateBtn = page.locator('div.date-list button').first() - await expect(dateBtn).toBeVisible() - await dateBtn.click() - await page.waitForTimeout(1500) - - // Step 3: Pick a time slot - const slotBtn = page.locator('div.slot-list button').first() - if (await slotBtn.isVisible({ timeout: 5000 })) { - await slotBtn.click() - await expect(page.locator('text=4. 备注')).toBeVisible() - - // Step 4: Add note and submit - await page.fill('textarea', 'E2E booking test') - await page.click('text=确认预约') - await page.waitForURL('**/user/appointments', { timeout: 10000 }) - - // Verify appointment created - await expect(page.locator('h1')).toHaveText('我的预约') - - // Cancel the appointment - const cancelBtn = page.locator('button:has-text("取消")').first() - if (await cancelBtn.isVisible({ timeout: 5000 })) { - page.once('dialog', dialog => dialog.accept()) - await cancelBtn.click() - await page.waitForTimeout(1500) - await expect(page.locator('.status.cancelled').first()).toBeVisible({ timeout: 5000 }) - } - } - }) - - test('TC-014 编辑个人信息', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', registerEmail) - await page.fill('input[type="password"]', 'Test123456') - await page.click('button[type="submit"]') - await page.waitForURL('**/user/dashboard', { timeout: 10000 }) - - await page.goto('/user/profile') - const nameInput = page.locator('input').nth(1) - await nameInput.fill('E2E用户-已改名') - const [dialog] = await Promise.all([ - page.waitForEvent('dialog', { timeout: 5000 }), - page.click('text=保存'), - ]) - expect(dialog.message()).toContain('保存成功') - await dialog.dismiss() - }) -}) - -/* ─────────────── Admin Flows (independent tests) ─────────────── */ - -test.describe('Admin Flows', () => { - - test('TC-015 仪表盘统计', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - await expect(page.locator('h1')).toHaveText('管理仪表盘') - await expect(page.locator('.stat-card').filter({ hasText: '用户数' })).toBeVisible() - await expect(page.locator('.stat-card').filter({ hasText: '咨询师' })).toBeVisible() - await expect(page.locator('.stat-card').filter({ hasText: '总预约' })).toBeVisible() - await expect(page.locator('.stat-card').filter({ hasText: '待确认' })).toBeVisible() - await expect(page.locator('.stat-card').filter({ hasText: '网点' })).toBeVisible() - }) - - test('TC-016 用户管理', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - await page.goto('/admin/users') - await expect(page.locator('table')).toBeVisible({ timeout: 10000 }) - await expect(page.locator('text=admin@test.com')).toBeVisible() - await expect(page.locator('text=管理员')).toBeVisible() - - const toggleBtn = page.locator('button:has-text("禁用"), button:has-text("启用")').first() - if (await toggleBtn.isVisible()) { - await toggleBtn.click() - await page.waitForTimeout(1000) - } - }) - - test('TC-017 咨询师管理', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - await page.locator('a:has-text("咨询师管理")').click() - await page.waitForURL('**/admin/consultants', { timeout: 10000 }) - await expect(page.locator('table')).toBeVisible({ timeout: 10000 }) - await expect(page.locator('text=张医生')).toBeVisible() - await expect(page.locator('text=李律师')).toBeVisible() - await expect(page.locator('text=王教练')).toBeVisible() - }) - - test('TC-018 预约管理', async ({ page }) => { - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - await page.locator('a:has-text("预约管理")').click() - await page.waitForURL('**/admin/appointments', { timeout: 10000 }) - await expect(page.locator('h1')).toHaveText('预约管理') - }) - - test('TC-019 网点 CRUD', async ({ page }) => { - // Login - await page.goto('/login') - await page.fill('input[type="email"]', ADMIN_EMAIL) - await page.fill('input[type="password"]', ADMIN_PASSWORD) - await page.click('button[type="submit"]') - await page.waitForURL('**/admin/dashboard', { timeout: 10000 }) - - // Go to branches - await page.locator('a:has-text("网点管理")').click() - await page.waitForURL('**/admin/branches', { timeout: 10000 }) - await expect(page.locator('h1')).toHaveText('网点管理') - await expect(page.locator('text=朝阳咨询中心')).toBeVisible({ timeout: 10000 }) - await expect(page.locator('text=海淀咨询中心')).toBeVisible() - await expect(page.locator('text=浦东咨询中心')).toBeVisible() - - // ── CREATE ── - await page.click('text=新增网点') - await expect(page.locator('.modal')).toBeVisible() - - // Modal:
- await page.locator('.modal .form-group').nth(0).locator('input').fill('E2E测试网点') - await page.locator('.modal .form-group').nth(1).locator('input').fill('东城区测试大街1号') - await page.locator('.modal .form-group').nth(2).locator('input').fill('010-88889999') - await page.locator('.modal button:has-text("保存")').click() - await page.waitForTimeout(1500) - await expect(page.locator('text=E2E测试网点')).toBeVisible({ timeout: 5000 }) - - // ── EDIT ── - await page.locator('tr:has-text("E2E测试网点") button:has-text("编辑")').click() - await expect(page.locator('.modal')).toBeVisible() - await page.locator('.modal .form-group').nth(0).locator('input').fill('E2E测试网点-已改') - await page.locator('.modal button:has-text("保存")').click() - await page.waitForTimeout(1500) - await expect(page.locator('text=E2E测试网点-已改')).toBeVisible({ timeout: 5000 }) - - // ── DELETE ── - page.once('dialog', dialog => dialog.accept()) - await page.locator('tr:has-text("E2E测试网点-已改") button:has-text("删除")').click() - await page.waitForTimeout(1500) - await expect(page.locator('text=E2E测试网点-已改')).toHaveCount(0, { timeout: 5000 }) - }) -}) - -/* ─────────────── Edge Cases ─────────────── */ - -test.describe('Edge Cases', () => { - - test('TC-020 未登录访问管理页', async ({ page }) => { - await page.goto('/') - await page.evaluate(() => localStorage.clear()) - await page.goto('/admin/dashboard') - await expect(page).toHaveURL(/\/login/, { timeout: 5000 }) - }) - - test('TC-021 未登录访问用户页', async ({ page }) => { - await page.goto('/') - await page.evaluate(() => localStorage.clear()) - await page.goto('/user/dashboard') - await expect(page).toHaveURL(/\/login/, { timeout: 5000 }) - }) - - test('TC-022 首页 CTA 可见', async ({ page }) => { - await page.goto('/') - await page.evaluate(() => localStorage.clear()) - await page.goto('/') - const cta = page.locator('text=免费注册') - await expect(cta).toBeVisible() + await expect(page.locator('h1')).toHaveText('咨询预约平台') + await expect(page.getByText('工程骨架已就绪')).toBeVisible() }) }) diff --git a/example-project/opencode.jsonc b/example-project/opencode.jsonc index 69e15c9..aefdca9 100644 --- a/example-project/opencode.jsonc +++ b/example-project/opencode.jsonc @@ -2,6 +2,6 @@ "$schema": "https://opencode.ai/config.json", "skills": { - "paths": [".agent/skills"] + "paths": [".agents/skills"] } } diff --git a/harness-installer/SKILL.md b/harness-installer/SKILL.md index 20f7b9c..42e8370 100644 --- a/harness-installer/SKILL.md +++ b/harness-installer/SKILL.md @@ -37,7 +37,7 @@ description: 初始化项目的工程 harness —— 生成/补齐 AGENTS.md( 1. **探测项目结构**:找后端(有 `pom.xml`/`build.gradle`)、前端(有 `package.json`)、E2E 目录 2. **渲染 `AGENTS.md`**:把模板里的 `{{...}}` 占位符替换成探测结果,写入 `<项目>/AGENTS.md` 3. **铺 `docs/` 骨架**:复制 `templates/docs/**` 到 `<项目>/docs/**` -4. **确保 `opencode.jsonc`**:不存在则创建(注册 `.agent/skills` 路径) +4. **确保 `opencode.jsonc`**:不存在则创建(注册 `.agents/skills` 路径) ## 生成后必须做的事 diff --git a/harness-installer/templates/opencode.jsonc b/harness-installer/templates/opencode.jsonc index 69e15c9..aefdca9 100644 --- a/harness-installer/templates/opencode.jsonc +++ b/harness-installer/templates/opencode.jsonc @@ -2,6 +2,6 @@ "$schema": "https://opencode.ai/config.json", "skills": { - "paths": [".agent/skills"] + "paths": [".agents/skills"] } } diff --git a/opencode.jsonc b/opencode.jsonc index bae41dc..a2a0207 100644 --- a/opencode.jsonc +++ b/opencode.jsonc @@ -8,7 +8,7 @@ "harness-installer", "tool-chain-installer", "overnight-runner", - "example-project/.agent/skills" + "example-project/.agents/skills" ] } } diff --git a/team-workflow-guide/index.html b/team-workflow-guide/index.html index 94c63d0..342cb50 100644 --- a/team-workflow-guide/index.html +++ b/team-workflow-guide/index.html @@ -516,7 +516,7 @@
  • AGENTS.md + docs/
  • -
  • .agent/skills/
  • +
  • .agents/skills/
  • MCP 配置、测试闸门约定
@@ -708,7 +708,7 @@ 步骤主责产物 初始化 AGENTS.md + docs/TLAGENTS.md、docs/** - 安装 SDD skillTL.agent/skills/ + 安装 SDD skillTL.agents/skills/ 安装 MCPTL.mcp.json / opencode.jsonc 定架构与标准TLdocs/standards/、docs/facts/ 定测试闸门QA + TLtest:qa 进 CI @@ -724,7 +724,7 @@ 完成后由 TL 补全 AGENTS.md 里的业务 / 架构 TODO(Agent 可起草,人必须拍板)。
  • - 装 SDD skills — 对 Agent 说:用 agile-team-sdd 把 16 个流程 skill 安装到目标项目的 .agent/skills/。 + 装 SDD skills — 对 Agent 说:用 agile-team-sdd 把 16 个流程 skill 安装到目标项目的 .agents/skills/。
  • 装 MCP 工具链 — 对 Agent 说:用 tool-chain-installer 把 MCP 配置写入项目(如 .mcp.json / opencode.jsonc)。