Initial commit: ai4se-harness-suite
Import harness suite (skills, installers, overnight-runner, docs) as a fresh history for InspireChina. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
93
example-project/docs/standards/api-design.md
Normal file
93
example-project/docs/standards/api-design.md
Normal file
@@ -0,0 +1,93 @@
|
||||
# API 规范
|
||||
|
||||
## 基础
|
||||
|
||||
- RESTful 风格
|
||||
- URL 一律小写连字符(kebab-case)
|
||||
- 名词使用复数(如 `/users`、`/appointments`)
|
||||
- API 前缀 `/api/v1/`
|
||||
|
||||
## 请求
|
||||
|
||||
- GET/DELETE 参数通过 Query String
|
||||
- POST/PUT 参数通过 JSON Body
|
||||
- Content-Type: `application/json`
|
||||
- 认证通过 `Authorization: Bearer <token>` 请求头
|
||||
|
||||
## 响应
|
||||
|
||||
- 成功:直接返回数据体
|
||||
- 错误:统一格式 `{errorCode, errorMessage, data}`
|
||||
|
||||
## HTTP 状态码
|
||||
|
||||
| 状态码 | 含义 | 使用场景 |
|
||||
|--------|------|----------|
|
||||
| 200 | 成功 | 正常返回 |
|
||||
| 400 | 参数错误 | 参数校验失败 / 业务参数错误 |
|
||||
| 401 | 未授权 | Token 缺失 / 无效 / 过期 |
|
||||
| 403 | 无权限 | 非管理员访问 /admin |
|
||||
| 404 | 不存在 | 资源 ID 不存在 |
|
||||
| 409 | 业务冲突 | 重复预约 / 状态冲突 |
|
||||
| 500 | 服务器错误 | 未捕获异常 |
|
||||
|
||||
## 分页
|
||||
|
||||
- 入参:`page`(从 1 开始)、`pageSize`(默认 20)
|
||||
- 出参:`{records, total, page, pageSize}`
|
||||
|
||||
---
|
||||
|
||||
## 前端 API 调用规范
|
||||
|
||||
### Service 层封装
|
||||
|
||||
每个领域对应一个 service 文件,统一通过 Axios 实例调用:
|
||||
|
||||
```typescript
|
||||
// src/services/appointmentService.ts
|
||||
import api from '@/utils/axios'
|
||||
|
||||
export const appointmentService = {
|
||||
list: () => api.get('/appointments'),
|
||||
getById: (id: string) => api.get(`/appointments/${id}`),
|
||||
create: (data: CreateAppointmentDto) => api.post('/appointments', data),
|
||||
cancel: (id: string, reason?: string) => api.put(`/appointments/${id}/cancel`, { reason }),
|
||||
}
|
||||
```
|
||||
|
||||
### Axios 实例配置
|
||||
|
||||
```typescript
|
||||
// src/utils/axios.ts
|
||||
import axios from 'axios'
|
||||
|
||||
const api = axios.create({ baseURL: '/api/v1' })
|
||||
|
||||
// 请求拦截器:自动附加 JWT
|
||||
api.interceptors.request.use(config => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
|
||||
// 响应拦截器:统一错误处理与 401 跳转
|
||||
api.interceptors.response.use(
|
||||
res => res,
|
||||
error => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('token')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export default api
|
||||
```
|
||||
|
||||
### 响应处理
|
||||
|
||||
- 成功响应直接返回 data
|
||||
- 业务错误(400/409)在调用处 catch 处理,展示错误消息
|
||||
- 网络/系统错误(500)由拦截器统一提示
|
||||
123
example-project/docs/standards/architecture.md
Normal file
123
example-project/docs/standards/architecture.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# 系统架构设计
|
||||
|
||||
> 本文档描述咨询预约平台的事实架构(as-built)。
|
||||
|
||||
## 部署形态
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ 单机部署 (Monolith) │
|
||||
│ ┌──────────┐ ┌──────────────────────────────────┐ │
|
||||
│ │ │ │ Spring Boot 3.2 │ │
|
||||
│ │ Vite │ /api│ ┌────────────────────────────┐ │ │
|
||||
│ │ Dev │─────│ │ adapter/rest │ │ │
|
||||
│ │ Server │ │ │ (Controller, 协议转换) │ │ │
|
||||
│ │ :5173 │ │ └──────────┬─────────────────┘ │ │
|
||||
│ │ │ │ ↓ │ │
|
||||
│ │ or │ │ ┌────────────────────────────┐ │ │
|
||||
│ │ Nginx │ │ │ application/service │ │ │
|
||||
│ │ :80 │ │ │ (用例编排, 事务边界) │ │ │
|
||||
│ └──────────┘ │ └──────────┬─────────────────┘ │ │
|
||||
│ │ ↓ │ │
|
||||
│ │ ┌────────────────────────────┐ │ │
|
||||
│ │ │ domain/aggregate │ │ │
|
||||
│ │ │ (业务不变量, 状态机) │ │ │
|
||||
│ │ └──────────┬─────────────────┘ │ │
|
||||
│ │ ↑ │ │
|
||||
│ │ ┌──────────┴─────────────────┐ │ │
|
||||
│ │ │ infrastructure/ │ │ │
|
||||
│ │ │ (DB/外部API/安全/配置) │ │ │
|
||||
│ │ └────────────────────────────┘ │ │
|
||||
│ │ │ │ │
|
||||
│ │ ↓ │ │
|
||||
│ │ ┌────────────┐ │ │
|
||||
│ │ │ MySQL │ │ │
|
||||
│ │ │ :3306 │ │ │
|
||||
│ │ └────────────┘ │ │
|
||||
│ └──────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 通信方式
|
||||
|
||||
| 端 | 目标 | 协议 | 说明 |
|
||||
|----|------|------|------|
|
||||
| 浏览器 → Vite Dev Server | 前端静态资源 | HTTP | 开发模式,Vite 热更新 |
|
||||
| Vite Dev Server → Spring Boot | 后端 API | HTTP (proxy) | `/api` → `localhost:8080`,由 `vite.config.ts` 配置 |
|
||||
| Spring Boot → MySQL | 数据库 | JDBC | MyBatis-Plus 连接池,默认 3306 |
|
||||
| Nginx (生产) → 静态文件 | 前端 | HTTP | 打包后的 dist/ |
|
||||
| Nginx (生产) → Spring Boot | 后端 API | HTTP | 反向代理 `/api` |
|
||||
|
||||
## 四层依赖方向
|
||||
|
||||
```
|
||||
adapter → application → domain ← infrastructure
|
||||
```
|
||||
|
||||
- **adapter**:仅做 HTTP 协议转换与参数校验,不包含业务逻辑
|
||||
- **application**:用例编排、事务管理、DTO ↔ Domain 转换(Assembler)
|
||||
- **domain**:纯 POJO + Lombok,无 Spring 注解,承载业务不变量
|
||||
- **infrastructure**:实现 domain 的 Repository 接口 + 安全 + 配置
|
||||
|
||||
## 前端架构(Vue 3)
|
||||
|
||||
```
|
||||
src/
|
||||
├── views/ # 页面级组件(按子系统分)
|
||||
│ ├── user/ # 用户端(dashboard, book, appointments, profile)
|
||||
│ └── admin/ # 管理端(dashboard, users, consultants, appointments, branches)
|
||||
├── components/ # 通用 UI 组件
|
||||
│ ├── layout/ # 布局组件(AppHeader, AppSidebar, AppFooter)
|
||||
│ └── common/ # 通用组件(StatCard, BookingCalendar, DataTable)
|
||||
├── composables/ # 可复用组合式逻辑
|
||||
│ ├── useAuth.ts # 登录/注册/登出逻辑
|
||||
│ ├── useBooking.ts # 预约流程状态管理
|
||||
│ └── usePagination.ts # 分页逻辑
|
||||
├── services/ # API 服务层
|
||||
│ ├── axios.ts # Axios 实例(拦截器配置)
|
||||
│ ├── authService.ts # 认证相关 API
|
||||
│ ├── appointmentService.ts # 预约相关 API
|
||||
│ └── consultantService.ts # 咨询师相关 API
|
||||
├── stores/ # Pinia 全局状态
|
||||
│ ├── authStore.ts # 用户认证状态
|
||||
│ └── bookingStore.ts # 预约流程临时状态
|
||||
├── router/ # Vue Router 配置
|
||||
│ └── index.ts # 路由定义 + 守卫
|
||||
├── styles/ # 全局样式
|
||||
│ └── variables.css # CSS 变量
|
||||
└── types/ # TypeScript 类型定义
|
||||
└── index.ts # 接口 DTO 类型
|
||||
```
|
||||
|
||||
## 技术栈
|
||||
|
||||
| 组件 | 技术 | 版本 |
|
||||
|------|------|------|
|
||||
| JDK | OpenJDK | 17 |
|
||||
| 框架 | Spring Boot | 3.2.0 |
|
||||
| ORM | MyBatis-Plus | 3.5.5 |
|
||||
| DB | MySQL 8.0 / H2 (test) | - |
|
||||
| Migration | Flyway | (Boot managed) |
|
||||
| 安全 | Spring Security + JWT (jjwt) | 0.12.3 |
|
||||
| 前端框架 | Vue 3 + Composition API + TypeScript | - |
|
||||
| 构建 | Vite | 5.x |
|
||||
| 状态管理 | Pinia | - |
|
||||
| 路由 | Vue Router 4 | - |
|
||||
| 测试 | JUnit 5 + RestAssured | - |
|
||||
|
||||
## 包结构
|
||||
|
||||
```
|
||||
com.consultation
|
||||
├── ConsultationApplication.java
|
||||
├── adapter.rest.* # Controller
|
||||
├── application.assembler.* # Response/Command DTO
|
||||
├── application.service.* # AppService
|
||||
├── domain.aggregate.* # 聚合根
|
||||
├── domain.repository.* # 仓储接口
|
||||
├── domain.service.* # 领域服务
|
||||
├── domain.vo.* # 值对象
|
||||
├── domain.businessrule.* # 业务规则接口 (Phase 2)
|
||||
├── domain.datadictionary.* # 数据字典接口 (Phase 3)
|
||||
└── infrastructure.* # 配置/持久化/安全/规则实现
|
||||
```
|
||||
65
example-project/docs/standards/business-rule.md
Normal file
65
example-project/docs/standards/business-rule.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# 业务规则规范
|
||||
|
||||
## 定义方式
|
||||
|
||||
业务规则通过 `IBusinessRule` 接口定义:
|
||||
|
||||
```java
|
||||
public interface IBusinessRule {
|
||||
String getRuleName(); // 唯一规则名
|
||||
String getDescription(); // 描述
|
||||
}
|
||||
```
|
||||
|
||||
## 配置存储
|
||||
|
||||
- 规则配置存储在 `resources/business-rules/*.yml` 中
|
||||
- 命名:`{domain}.yml`(如 `appointment.yml`、`auth.yml`)
|
||||
- 格式:
|
||||
|
||||
```yaml
|
||||
appointment:
|
||||
conflict:
|
||||
detection: "同一咨询师同一时段不可重复预约"
|
||||
slot:
|
||||
minMinutes: 30
|
||||
maxMinutes: 120
|
||||
intervalMinutes: 60
|
||||
```
|
||||
|
||||
- 加载方式:`application.yml` 通过 `spring.config.import` 显式导入这些 YAML,
|
||||
导入后的顶层键(`appointment` / `auth`)作为根级属性绑定到 `BusinessRuleConfig`。
|
||||
漏掉 `spring.config.import` 时 YAML 不会进入 Environment,接口将**静默少返回 `config` 字段**。
|
||||
|
||||
## 查询
|
||||
|
||||
- `BusinessRuleProvider` 在启动时加载所有 YAML 规则
|
||||
- 通过 `GET /api/v1/business-rules` 公开查询
|
||||
|
||||
## 配置类型绑定
|
||||
|
||||
顶层键绑定到 `domain/businessrule/BusinessRuleConfig`:
|
||||
|
||||
| 顶层键 | Java 类型 | 说明 |
|
||||
|--------|-----------|------|
|
||||
| `appointment` | `Map<String, Object>` | 目前全是标量子结构,绑 Map 安全 |
|
||||
| `auth` | `AuthConfig`(有类型嵌套类) | `password` / `token` / `publicEndpoints` 均为强类型 |
|
||||
|
||||
**约束:往 YAML 里加列表前,必须先给对应的配置类加类型。**
|
||||
|
||||
Spring Boot 的 binder 拿到 YAML 里的 **序列** 而目标类型是 `Map<String, Object>` 时,
|
||||
无法判断该绑成数组还是 Map,会退化成 **以 0/1/2… 为键的 Map**,
|
||||
最终序列化出 `{"0": "...", "1": "..."}` 这种错误结构(而不是 JSON 数组)。
|
||||
|
||||
只有 **列表** 这一种形状会被绑坏 —— 纯标量子结构绑 Map 没问题。
|
||||
`auth.publicEndpoints` 就是踩过这个坑的地方,现在由 `AuthConfig.publicEndpoints`
|
||||
(`List<String>`)承接。
|
||||
|
||||
同时约定:
|
||||
|
||||
- YAML 与 Java 类必须 **同时改**,键结构一一对应
|
||||
- 类里的字段默认值写死当前 YAML 的值,避免 YAML 加载失败时接口返回"空壳"配置
|
||||
|
||||
## 同步
|
||||
|
||||
新增或修改业务规则后,同步更新 `docs/designs/topic/businessrule.md`。
|
||||
38
example-project/docs/standards/data-dictionary.md
Normal file
38
example-project/docs/standards/data-dictionary.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# 数据字典规范
|
||||
|
||||
## 接口定义
|
||||
|
||||
所有业务枚举需实现 `Description` 接口:
|
||||
|
||||
```java
|
||||
public interface Description {
|
||||
String getCode(); // enum.name(),如 "PENDING"
|
||||
String getDescription(); // 中文描述,如 "待确认"
|
||||
default Map<String, String> getExtraFields() { return Collections.emptyMap(); }
|
||||
}
|
||||
```
|
||||
|
||||
## 注册
|
||||
|
||||
枚举通过 `DataDictionaryType` 注册为字典类型:
|
||||
|
||||
```java
|
||||
public interface DataDictionaryType {
|
||||
Class<? extends Description> getClazz(); // 枚举类
|
||||
String getDescription(); // 字典类型描述
|
||||
}
|
||||
```
|
||||
|
||||
系统中实现 `DataDictionaryType` 的枚举统一管理所有字典注册。
|
||||
|
||||
## 动态查询
|
||||
|
||||
| 端点 | 说明 |
|
||||
|------|------|
|
||||
| `GET /api/v1/data-dictionaries` | 获取所有字典类型列表 |
|
||||
| `GET /api/v1/data-dictionaries/{type}` | 获取指定字典的条目列表 |
|
||||
|
||||
## docs 同步
|
||||
|
||||
修改枚举后,运行 `DataDictionaryUtil` 的 `generateMarkdown()` 更新 `docs/designs/topic/data-dict.md`。
|
||||
也可以在 AGENTS.md 中约定手动同步。
|
||||
6
example-project/docs/standards/db.md
Normal file
6
example-project/docs/standards/db.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# 数据库规范
|
||||
|
||||
- 字符集 utf8mb4,排序 utf8mb4_bin,引擎 InnoDB
|
||||
- 表名/字段小写蛇形,表名单数,主键 VARCHAR(64) UUID
|
||||
- 公共字段:created_by, created_time, updated_by, updated_time
|
||||
- Flyway 迁移 V<YYYYMMDD>__<description>.sql
|
||||
104
example-project/docs/standards/error.md
Normal file
104
example-project/docs/standards/error.md
Normal file
@@ -0,0 +1,104 @@
|
||||
# 错误码规范
|
||||
|
||||
## 全局异常处理
|
||||
|
||||
本项目 **没有** 自定义异常类体系。所有异常由
|
||||
`infrastructure/config/GlobalExceptionHandler`(`@RestControllerAdvice`)统一转换:
|
||||
|
||||
| 抛出什么 | HTTP | errorCode | 什么时候用 |
|
||||
|---|---|---|---|
|
||||
| `IllegalArgumentException` | 400 | `PARAM_ERROR` | 参数不合法、查不到的资源(异常消息即 `errorMessage`) |
|
||||
| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` | 业务状态冲突(如同一时段被占用) |
|
||||
| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` | `@Valid` 字段级校验失败(自动抛出,不手写) |
|
||||
| 其它 `Exception` | 500 | `SYSTEM_ERROR` | 兜底,消息固定为「系统繁忙」 |
|
||||
|
||||
## 写新代码的约定
|
||||
|
||||
- 参数不合法 / 资源不存在 → 抛 `IllegalArgumentException`
|
||||
- 业务状态冲突 → 抛 `IllegalStateException`
|
||||
- 不要裸抛 `RuntimeException`:会落到 500 兜底,业务语义丢失
|
||||
- 鉴权失败由 Spring Security 直接返回 401 / 403,不走 `ErrorResponse` 包装
|
||||
|
||||
## 响应体格式
|
||||
|
||||
`GlobalExceptionHandler.ErrorResponse` 的字段是 `errorCode` / `errorMessage` / `data`
|
||||
(**不是** `message`):
|
||||
|
||||
```json
|
||||
{
|
||||
"errorCode": "BUSINESS_CONFLICT",
|
||||
"errorMessage": "该时段已被占用",
|
||||
"data": null
|
||||
}
|
||||
```
|
||||
|
||||
## 错误码表
|
||||
|
||||
全量错误码与"当前实现映射"见 `docs/designs/topic/error-code.md`。
|
||||
|
||||
---
|
||||
|
||||
## 前端错误处理
|
||||
|
||||
### Axios 响应拦截器
|
||||
|
||||
```typescript
|
||||
api.interceptors.response.use(
|
||||
res => res,
|
||||
error => {
|
||||
const { status, data } = error.response || {}
|
||||
|
||||
if (status === 401) {
|
||||
// Token 过期或无效 → 清除登录状态,跳转登录页
|
||||
localStorage.removeItem('token')
|
||||
window.location.href = '/login'
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (status === 403) {
|
||||
// 无权限 → 显示提示
|
||||
ElMessage.error('无权访问该资源')
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (status === 409) {
|
||||
// 业务冲突 → 将错误消息透传给调用方显示
|
||||
ElMessage.warning(data?.errorMessage || '操作冲突')
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (status >= 500) {
|
||||
ElMessage.error('系统繁忙,请稍后重试')
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### 业务调用处处理
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await appointmentService.cancel(id, reason)
|
||||
ElMessage.success('取消成功')
|
||||
refreshList()
|
||||
} catch (err: any) {
|
||||
// 409 已在拦截器中处理 toast
|
||||
// 400 错误展示具体提示
|
||||
if (err.response?.status === 400) {
|
||||
ElMessage.warning(err.response.data?.errorMessage || '参数错误')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 错误提示原则
|
||||
|
||||
| HTTP Status | 用户提示方式 | 说明 |
|
||||
|-------------|-------------|------|
|
||||
| 400 | `ElMessage.warning` | 参数错误,具体消息来自后端 |
|
||||
| 401 | 自动跳转登录页 | Token 失效,静默处理 |
|
||||
| 403 | `ElMessage.error` | 无权限,阻断操作 |
|
||||
| 409 | `ElMessage.warning` | 业务冲突,具体消息来自后端 |
|
||||
| 500 | `ElMessage.error` | 系统繁忙,通用提示 |
|
||||
44
example-project/docs/standards/layers.md
Normal file
44
example-project/docs/standards/layers.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# 分层架构规范
|
||||
|
||||
## 四层架构
|
||||
|
||||
```
|
||||
adapter → application → domain ← infrastructure
|
||||
```
|
||||
|
||||
## adapter
|
||||
HTTP Controller 入/出参协议转换、参数基础校验。不含业务逻辑。
|
||||
|
||||
## application
|
||||
用例编排、事务边界管理、Command→domain→Response 转换(Assembler)。
|
||||
|
||||
## domain
|
||||
核心业务逻辑、Entity/Aggregate/ValueObject、Repository 接口定义。不依赖 infrastructure。
|
||||
|
||||
## infrastructure
|
||||
PO + Mapper + Converter + RepositoryImpl + 安全 + 配置。
|
||||
|
||||
---
|
||||
|
||||
## 前端(Vue 3)分层
|
||||
|
||||
```
|
||||
view (页面路由) → component (UI 组件) → composable (可复用逻辑) → service (API 调用)
|
||||
↓
|
||||
store (Pinia 全局状态)
|
||||
```
|
||||
|
||||
### view
|
||||
页面级组件,对应 Vue Router 路由。负责布局与页面组合,不含业务逻辑。
|
||||
|
||||
### component
|
||||
通用 UI 组件(表单、表格、卡片等),接收 props、发射 events。
|
||||
|
||||
### composable
|
||||
可复用的组合式逻辑(`useAuth`、`useBooking` 等),封装响应式状态与方法。
|
||||
|
||||
### service
|
||||
Axios API 调用封装,每个领域一个 service 文件(`authService.ts`、`appointmentService.ts`)。
|
||||
|
||||
### store(Pinia)
|
||||
全局状态管理(`authStore`、`bookingStore`),使用 Composition API 风格定义。
|
||||
37
example-project/docs/standards/naming.md
Normal file
37
example-project/docs/standards/naming.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# 命名规范
|
||||
|
||||
## 后端
|
||||
|
||||
| 类型 | 约定 | 示例 |
|
||||
|------|------|------|
|
||||
| Controller | `XxxController` | `AppointmentController` |
|
||||
| Service | `XxxService` | `AppointmentService` |
|
||||
| Repository 接口 | `XxxRepository` | `AppointmentRepository` |
|
||||
| Repository 实现 | `XxxRepositoryImpl` | `AppointmentRepositoryImpl` |
|
||||
| Mapper | `XxxMapper` | `AppointmentMapper` |
|
||||
| PO | `XxxPO` | `AppointmentPO` |
|
||||
| Assembler | `XxxAssembler` | `AppointmentAssembler` |
|
||||
| Converter | `XxxConverter` | `AppointmentConverter` |
|
||||
|
||||
## 前端
|
||||
|
||||
| 类型 | 约定 | 示例 |
|
||||
|------|------|------|
|
||||
| 组件文件 | PascalCase `.vue` | `BookingWizard.vue` |
|
||||
| 视图文件 | PascalCase `.vue` | `UserDashboard.vue` |
|
||||
| Service 文件 | camelCase `.ts` | `appointmentService.ts` |
|
||||
| Store 文件 | camelCase `.ts` | `authStore.ts` |
|
||||
| Composable | `useXxx` `.ts` | `useBooking.ts` |
|
||||
| 变量/方法 | camelCase | `currentUser`, `fetchAppointments()` |
|
||||
| 目录名 | kebab-case | `user-dashboard/` |
|
||||
| 路由路径 | kebab-case | `/user/dashboard` |
|
||||
| 组件名(多词) | PascalCase | `<BookingCalendar />` |
|
||||
| Props 定义 | camelCase | `:userName="..."` |
|
||||
| Events | kebab-case | `@update-profile` |
|
||||
|
||||
## 数据库
|
||||
|
||||
- 小写蛇形,单数表名:`appointment`、`consultant`
|
||||
- 字段小写蛇形:`appointment_date`、`start_time`
|
||||
- 唯一索引前缀 `uk_`:`uk_appointment_slot`
|
||||
- 普通索引前缀 `idx_`:`idx_user_id`
|
||||
61
example-project/docs/standards/security.md
Normal file
61
example-project/docs/standards/security.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# 安全规范
|
||||
|
||||
## 后端
|
||||
|
||||
- 密码 BCrypt 加密,至少 8 位含字母+数字
|
||||
- JWT HMAC-SHA256,24h 有效期,载荷含 userId/email/role
|
||||
- 无状态鉴权,Token 传 `Authorization: Bearer <token>`
|
||||
- 公开端点:`/auth/**`, `/home/**`, `GET /consultants`
|
||||
- 管理端点:`/admin/**` 需 `ROLE_ADMIN`
|
||||
|
||||
## 前端
|
||||
|
||||
### Token 存储
|
||||
|
||||
```typescript
|
||||
// 登录成功后
|
||||
localStorage.setItem('token', response.token)
|
||||
localStorage.setItem('user', JSON.stringify(response.user))
|
||||
```
|
||||
|
||||
- Token 存入 `localStorage`,JWT 不涉及 XSS 时相对安全
|
||||
- 用户信息同步存入 Pinia store:`authStore.setUser(user)`
|
||||
|
||||
### Axios 请求拦截器
|
||||
|
||||
```typescript
|
||||
api.interceptors.request.use(config => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
```
|
||||
|
||||
### 路由守卫
|
||||
|
||||
```typescript
|
||||
// src/router/index.ts
|
||||
router.beforeEach((to, from, next) => {
|
||||
const token = localStorage.getItem('token')
|
||||
const user = JSON.parse(localStorage.getItem('user') || 'null')
|
||||
|
||||
if (to.meta.requiresAuth && !token) return next('/login')
|
||||
if (to.meta.requiresAdmin && user?.role !== 'ROLE_ADMIN') return next('/')
|
||||
next()
|
||||
})
|
||||
```
|
||||
|
||||
### 登出
|
||||
|
||||
```typescript
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
authStore.clear()
|
||||
router.push('/login')
|
||||
```
|
||||
|
||||
### 安全注意事项
|
||||
|
||||
- 不在 localStorage 存储敏感信息(如 BCrypt 密码 hash)
|
||||
- 后端返回的 JWT 不包含密码等敏感字段
|
||||
- 前端不校验权限,仅做 UI 显示控制;权限校验由后端 `SecurityConfig` 强制执行
|
||||
@@ -0,0 +1,58 @@
|
||||
# REST Controller(Adapter 层)
|
||||
|
||||
```java
|
||||
package com.xxx.adapter.rest;
|
||||
|
||||
import com.xxx.application.service.XxxService;
|
||||
import com.xxx.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/xxx")
|
||||
@RequiredArgsConstructor
|
||||
public class XxxController {
|
||||
|
||||
private final XxxService xxxService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<?> list() {
|
||||
return ResponseEntity.ok(xxxService.getMyXxx(SecurityUtils.currentUserId()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<?> get(@PathVariable String id) {
|
||||
return ResponseEntity.ok(xxxService.getById(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> create(@Valid @RequestBody CreateRequest r) {
|
||||
return ResponseEntity.ok(xxxService.create(SecurityUtils.currentUserId(), r.field1, r.field2));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/action")
|
||||
public ResponseEntity<Void> action(@PathVariable String id, @RequestBody Map<String, String> body) {
|
||||
xxxService.action(id, SecurityUtils.currentUserId(), body.getOrDefault("reason", "默认原因"));
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class CreateRequest {
|
||||
@NotBlank String field1;
|
||||
String field2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- Controller 只做协议转换,不包含业务逻辑
|
||||
- 使用 `@Valid` 做参数校验,内联 DTO 类
|
||||
- 通过 `SecurityUtils.currentUserId()` 获取当前用户
|
||||
- 返回 `ResponseEntity<?>` 统一响应格式
|
||||
@@ -0,0 +1,54 @@
|
||||
# AppService(Application 层)
|
||||
|
||||
```java
|
||||
package com.xxx.application.service;
|
||||
|
||||
import com.xxx.application.assembler.XxxAssembler;
|
||||
import com.xxx.domain.aggregate.Xxx;
|
||||
import com.xxx.domain.repository.XxxRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class XxxService {
|
||||
|
||||
private final XxxRepository xxxRepo;
|
||||
private final XxxAssembler assembler;
|
||||
|
||||
public XxxAssembler.XxxResponse getById(String id) {
|
||||
return assembler.toResponse(xxxRepo.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("记录不存在")));
|
||||
}
|
||||
|
||||
public List<XxxAssembler.XxxResponse> getMyXxx(String userId) {
|
||||
return xxxRepo.findByUserId(userId, 1, 100).stream()
|
||||
.map(assembler::toResponse).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public XxxAssembler.XxxResponse create(String userId, String field1, String field2) {
|
||||
// 1. 校验(通过 repository 或 domain service)
|
||||
// 2. 构建聚合根
|
||||
Xxx xxx = xxxRepo.save(Xxx.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.userId(userId)
|
||||
.field1(field1)
|
||||
.field2(field2)
|
||||
.status(XxxStatus.PENDING)
|
||||
.build());
|
||||
return assembler.toResponse(xxx);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- `@Transactional` 标记在用例方法上,事务边界在 application 层
|
||||
- 组合 repository、domain service 完成用例编排
|
||||
- 使用 assembler 将 domain 转为 DTO 返回给调用方(controller)
|
||||
- 异常使用 `IllegalArgumentException`(400)或 `IllegalStateException`(409)
|
||||
40
example-project/docs/standards/templates/03-ddd-assembler.md
Normal file
40
example-project/docs/standards/templates/03-ddd-assembler.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# Assembler(Domain → DTO 转换)
|
||||
|
||||
```java
|
||||
package com.xxx.application.assembler;
|
||||
|
||||
import com.xxx.domain.aggregate.Xxx;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class XxxAssembler {
|
||||
|
||||
public XxxResponse toResponse(Xxx xxx) {
|
||||
if (xxx == null) return null;
|
||||
return XxxResponse.builder()
|
||||
.id(xxx.getId())
|
||||
.userId(xxx.getUserId())
|
||||
.field1(xxx.getField1())
|
||||
.field2(xxx.getField2())
|
||||
.status(xxx.getStatus().name())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Data @Builder
|
||||
public static class XxxResponse {
|
||||
String id;
|
||||
String userId;
|
||||
String field1;
|
||||
String field2;
|
||||
String status;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- Assembler 负责 Domain → DTO 的转换,在 Application 层
|
||||
- Converter(Infrastructure 层)负责 Domain ⟷ PO 的转换 — 见 `08-ddd-converter.md`
|
||||
- DTO 使用 `@Data @Builder`,内联为静态类
|
||||
57
example-project/docs/standards/templates/04-ddd-aggregate.md
Normal file
57
example-project/docs/standards/templates/04-ddd-aggregate.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# 聚合根(Domain 层)
|
||||
|
||||
```java
|
||||
package com.xxx.domain.aggregate;
|
||||
|
||||
import com.xxx.domain.vo.XxxStatus;
|
||||
import lombok.Builder;
|
||||
import lombok.Value;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Value @Builder
|
||||
public class Xxx {
|
||||
String id;
|
||||
String userId;
|
||||
String field1;
|
||||
String field2;
|
||||
LocalDate date;
|
||||
XxxStatus status;
|
||||
String note;
|
||||
|
||||
// 业务守卫方法
|
||||
public boolean isOwnedBy(String uid) { return userId.equals(uid); }
|
||||
|
||||
public boolean canCancel() {
|
||||
return status == XxxStatus.PENDING || status == XxxStatus.CONFIRMED;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- 使用 `@Value @Builder` 实现不可变对象
|
||||
- 业务逻辑以守卫方法(guard method)形式封装在聚合根内
|
||||
- 不含框架注解,纯 Java POJO
|
||||
- 枚举实现 `Description` 接口用于数据字典注册(见 `04b-ddd-enum.md`)
|
||||
|
||||
### 示例:带枚举的聚合根
|
||||
|
||||
```java
|
||||
@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.xxx.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; }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
# Domain Service(Domain 层)
|
||||
|
||||
```java
|
||||
package com.xxx.domain.service;
|
||||
|
||||
import com.xxx.domain.aggregate.Xxx;
|
||||
import com.xxx.domain.vo.XxxStatus;
|
||||
import java.util.List;
|
||||
|
||||
public class XxxConflictService {
|
||||
|
||||
/**
|
||||
* 校验新建记录与已有记录不冲突。
|
||||
* 冲突时抛出 IllegalStateException(HTTP 409)。
|
||||
*/
|
||||
public void validateNoConflict(List<Xxx> existing, CheckParam param) {
|
||||
boolean conflict = existing.stream().anyMatch(a ->
|
||||
a.getField1().equals(param.field1()) &&
|
||||
a.getStatus() != XxxStatus.CANCELLED);
|
||||
if (conflict) throw new IllegalStateException("冲突:该条件已存在");
|
||||
}
|
||||
|
||||
public record CheckParam(String field1) {}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- Domain Service 处理跨聚合的业务校验,不在任何一个聚合根内
|
||||
- 不依赖 Spring,纯 Java
|
||||
- 在 AppService 中组合使用
|
||||
@@ -0,0 +1,26 @@
|
||||
# Repository 接口(Domain 层)
|
||||
|
||||
```java
|
||||
package com.xxx.domain.repository;
|
||||
|
||||
import com.xxx.domain.aggregate.Xxx;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface XxxRepository {
|
||||
Optional<Xxx> findById(String id);
|
||||
List<Xxx> findByUserId(String userId, int page, int pageSize);
|
||||
List<Xxx> findByField1(String field1);
|
||||
List<Xxx> findAll(int page, int pageSize);
|
||||
Xxx save(Xxx xxx);
|
||||
void update(Xxx xxx);
|
||||
long count();
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- 接口定义在 Domain 层,实现放在 Infrastructure 层(依赖反转)
|
||||
- 方法操作的是 Domain 对象(`Xxx`),而非 PO
|
||||
- 方法命名贴近业务语言
|
||||
@@ -0,0 +1,82 @@
|
||||
# Repository 实现(Infrastructure 层 — MyBatis-Plus)
|
||||
|
||||
```java
|
||||
package com.xxx.infrastructure.repositoryimpl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xxx.domain.aggregate.Xxx;
|
||||
import com.xxx.domain.repository.XxxRepository;
|
||||
import com.xxx.infrastructure.persistence.converter.XxxConverter;
|
||||
import com.xxx.infrastructure.persistence.mapper.XxxMapper;
|
||||
import com.xxx.infrastructure.persistence.po.XxxPO;
|
||||
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 XxxRepositoryImpl implements XxxRepository {
|
||||
|
||||
private final XxxMapper mapper;
|
||||
private final XxxConverter converter;
|
||||
|
||||
@Override public Optional<Xxx> findById(String id) {
|
||||
return Optional.ofNullable(converter.toDomain(mapper.selectById(id)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Xxx> findByUserId(String userId, int page, int pageSize) {
|
||||
return mapper.selectPage(new Page<>(page, pageSize),
|
||||
new LambdaQueryWrapper<XxxPO>()
|
||||
.eq(XxxPO::getUserId, userId)
|
||||
.orderByDesc(XxxPO::getCreatedTime))
|
||||
.getRecords().stream()
|
||||
.map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Xxx> findByField1(String field1) {
|
||||
return mapper.selectList(new LambdaQueryWrapper<XxxPO>()
|
||||
.eq(XxxPO::getField1, field1))
|
||||
.stream().map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override public List<Xxx> findAll(int page, int pageSize) {
|
||||
return mapper.selectPage(new Page<>(page, pageSize), null)
|
||||
.getRecords().stream().map(converter::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Xxx save(Xxx xxx) {
|
||||
XxxPO po = converter.toPO(xxx);
|
||||
po.setCreatedBy(xxx.getUserId());
|
||||
po.setCreatedTime(LocalDateTime.now());
|
||||
po.setUpdatedBy(xxx.getUserId());
|
||||
po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.insert(po);
|
||||
return xxx;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Xxx xxx) {
|
||||
XxxPO po = converter.toPO(xxx);
|
||||
po.setUpdatedTime(LocalDateTime.now());
|
||||
mapper.updateById(po);
|
||||
}
|
||||
|
||||
@Override public long count() {
|
||||
return mapper.selectCount(null);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- `@Repository` 标记,实现 Domain 层的接口
|
||||
- 通过 Converter 在 PO 和 Domain 之间转换
|
||||
- 使用 LambdaQueryWrapper 做类型安全的查询
|
||||
- 审计字段(createdBy/createdTime/updatedBy/updatedTime)在持久化时设置
|
||||
47
example-project/docs/standards/templates/08-ddd-converter.md
Normal file
47
example-project/docs/standards/templates/08-ddd-converter.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Converter(Infrastructure 层 — PO ⟷ Domain 转换)
|
||||
|
||||
```java
|
||||
package com.xxx.infrastructure.persistence.converter;
|
||||
|
||||
import com.xxx.domain.aggregate.Xxx;
|
||||
import com.xxx.domain.vo.XxxStatus;
|
||||
import com.xxx.infrastructure.persistence.po.XxxPO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class XxxConverter {
|
||||
|
||||
public Xxx toDomain(XxxPO po) {
|
||||
if (po == null) return null;
|
||||
return Xxx.builder()
|
||||
.id(po.getId())
|
||||
.userId(po.getUserId())
|
||||
.field1(po.getField1())
|
||||
.field2(po.getField2())
|
||||
.date(po.getDate())
|
||||
.status(XxxStatus.valueOf(po.getStatus()))
|
||||
.note(po.getNote())
|
||||
.build();
|
||||
}
|
||||
|
||||
public XxxPO toPO(Xxx xxx) {
|
||||
if (xxx == null) return null;
|
||||
XxxPO po = new XxxPO();
|
||||
po.setId(xxx.getId());
|
||||
po.setUserId(xxx.getUserId());
|
||||
po.setField1(xxx.getField1());
|
||||
po.setField2(xxx.getField2());
|
||||
po.setDate(xxx.getDate());
|
||||
po.setStatus(xxx.getStatus().name());
|
||||
po.setNote(xxx.getNote());
|
||||
return po;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- `@Component`,两层双向转换
|
||||
- `toDomain` 使用 Domain 的 `@Builder` 构建
|
||||
- `toPO` 使用 PO 的 setter(Lombok `@Data`)
|
||||
- 枚举字段通过 `.name()` / `valueOf()` 与字符串互转
|
||||
50
example-project/docs/standards/templates/09-ddd-po-mapper.md
Normal file
50
example-project/docs/standards/templates/09-ddd-po-mapper.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# PO 与 Mapper(Infrastructure 层 — MyBatis-Plus)
|
||||
|
||||
## PO(持久化对象)
|
||||
|
||||
```java
|
||||
package com.xxx.infrastructure.persistence.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("xxx")
|
||||
public class XxxPO {
|
||||
private String id;
|
||||
private String userId;
|
||||
private String field1;
|
||||
private String field2;
|
||||
private LocalDate date;
|
||||
private String status;
|
||||
private String note;
|
||||
// 审计字段
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
```
|
||||
|
||||
## Mapper
|
||||
|
||||
```java
|
||||
package com.xxx.infrastructure.persistence.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xxx.infrastructure.persistence.po.XxxPO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface XxxMapper extends BaseMapper<XxxPO> {}
|
||||
```
|
||||
|
||||
## 要点
|
||||
|
||||
- PO 使用 `@Data` + `@TableName`,字段与数据库列一一对应
|
||||
- 枚举字段存为 `String`(`status`),通过 Converter 与 Domain 枚举互转
|
||||
- Mapper 继承 `BaseMapper<PO>`,无需手写 SQL
|
||||
- 主键为 UUID 字符串(`VARCHAR(64)`),由应用层生成
|
||||
- 审计字段(createdBy/createdTime/updatedBy/updatedTime)在每个 PO 中定义
|
||||
@@ -0,0 +1,65 @@
|
||||
# 全局异常处理(Infrastructure 层)
|
||||
|
||||
```java
|
||||
package com.xxx.infrastructure.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBadArg(IllegalArgumentException e) {
|
||||
return ResponseEntity.badRequest().body(new ErrorResponse("PARAM_ERROR", e.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<ErrorResponse> handleConflict(IllegalStateException e) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(new ErrorResponse("BUSINESS_CONFLICT", e.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException e) {
|
||||
var msg = e.getBindingResult().getFieldError();
|
||||
return ResponseEntity.badRequest().body(
|
||||
new ErrorResponse("VALIDATION_ERROR",
|
||||
msg != null ? msg.getDefaultMessage() : "参数错误"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleOther(Exception e) {
|
||||
log.error("Unexpected error", e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(new ErrorResponse("SYSTEM_ERROR", "系统繁忙"));
|
||||
}
|
||||
|
||||
public record ErrorResponse(String errorCode, String errorMessage, Object data) {
|
||||
public ErrorResponse(String errorCode, String errorMessage) {
|
||||
this(errorCode, errorMessage, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 异常 → HTTP 状态码映射
|
||||
|
||||
| 异常 | HTTP | errorCode |
|
||||
|------|------|-----------|
|
||||
| `IllegalArgumentException` | 400 | `PARAM_ERROR` |
|
||||
| `MethodArgumentNotValidException` | 400 | `VALIDATION_ERROR` |
|
||||
| `IllegalStateException` | 409 | `BUSINESS_CONFLICT` |
|
||||
| `Exception`(未预期) | 500 | `SYSTEM_ERROR` |
|
||||
|
||||
## 要点
|
||||
|
||||
- 业务参数错误用 `IllegalArgumentException`,返回 400
|
||||
- 业务冲突用 `IllegalStateException`,返回 409
|
||||
- 未预期异常记录日志并返回 500,不暴露内部信息
|
||||
- 响应体统一为 `ErrorResponse` 结构
|
||||
18
example-project/docs/standards/templates/README.md
Normal file
18
example-project/docs/standards/templates/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Snippet — 常见业务代码模版
|
||||
|
||||
存放 DDD 四层架构的代码打样,供新功能开发时参考复制。所有模版均来自本项目的实现代码。
|
||||
|
||||
## 目录
|
||||
|
||||
| # | 文件 | 层 | 用途 |
|
||||
|---|------|-----|------|
|
||||
| 1 | `01-ddd-controller.md` | Adapter | REST Controller 模版 |
|
||||
| 2 | `02-ddd-appservice.md` | Application | AppService 用例编排模版 |
|
||||
| 3 | `03-ddd-assembler.md` | Application | Domain → DTO 转换器模版 |
|
||||
| 4 | `04-ddd-aggregate.md` | Domain | 聚合根模版(含业务守卫方法) |
|
||||
| 5 | `05-ddd-domain-service.md` | Domain | Domain Service 模版 |
|
||||
| 6 | `06-ddd-repository-interface.md` | Domain | Repository 接口模版 |
|
||||
| 7 | `07-ddd-repository-impl.md` | Infrastructure | MyBatis-Plus Repository 实现模版 |
|
||||
| 8 | `08-ddd-converter.md` | Infrastructure | PO ⟷ Domain 转换器模版 |
|
||||
| 9 | `09-ddd-po-mapper.md` | Infrastructure | PO 与 Mapper 模版 |
|
||||
| 10 | `10-global-exception-handler.md` | Infrastructure | 全局异常处理模版 |
|
||||
149
example-project/docs/standards/test.md
Normal file
149
example-project/docs/standards/test.md
Normal file
@@ -0,0 +1,149 @@
|
||||
# 测试规范
|
||||
|
||||
## 0. 两类用例:开发自测 vs QA 测试
|
||||
|
||||
本项目的测试用例分两层,**归属看"谁定义、谁判定",不是"谁敲的代码"**。
|
||||
|
||||
| 维度 | 开发自测(Dev Self-Test) | QA 测试(QA Test) |
|
||||
|---|---|---|
|
||||
| **验证什么** | 代码按 **Plan** 的设计工作 | 系统符合 **需求规格** |
|
||||
| **用例来源** | Plan(技术方案) | 需求规格 `docs/features/` + 业务规则编号 |
|
||||
| **谁定义** | 开发本人 | QA(与 PO 对齐业务规则) |
|
||||
| **谁判定** | 开发本人 | **QA** |
|
||||
| **什么时候写** | 实现过程中,边写边补 | 实现完成后的验收阶段 |
|
||||
| **用例编号** | 无编号,用命名表达意图 | `TC-xxx`,与文本用例一一对应 |
|
||||
| **存放位置** | 源码旁(`*Test.java`、`*.test.ts`) | `docs/` 用例库 + `e2e/tests/qa/` |
|
||||
| **是不是合并闸门** | 否(自测不通过,开发自己不能提交) | **是**(QA 用例不通过,不能验收、不能合并) |
|
||||
| **失败意味着** | 代码写错了 | 需求没实现 / 理解有偏差 / 规格有歧义 |
|
||||
| **谁修** | 开发 | 开发(QA 判定并跟单) |
|
||||
|
||||
### 关键约定
|
||||
|
||||
1. **QA 用例的自动化实现可以由开发代写**,但用例的 **定义权与判定权归 QA**。
|
||||
2. **开发自测不能替代 QA 测试**。开发自测全绿 ≠ 需求被实现。
|
||||
3. **QA 用例必须先有文本用例**(`docs/test-cases/e2e-cases/`),再写自动化。反过来做会漏场景。
|
||||
4. 发现实现中出现 **需求规格之外** 的行为,是缺陷(除非 PO 明确认可)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 用例归属速查
|
||||
|
||||
| 层 | 类型 | 归属 | 位置 | 框架 |
|
||||
|---|---|---|---|---|
|
||||
| Adapter | 集成测试 | 开发自测 | `backend/src/test/**/*Test.java` | SpringBootTest + RestAssured |
|
||||
| Application | 单元测试 | 开发自测 | `backend/src/test/**/*Test.java` | JUnit 5 + Mockito |
|
||||
| Domain | 单元测试 | 开发自测 | `backend/src/test/**/*Test.java` | JUnit 5 |
|
||||
| Infrastructure | 集成测试 | 开发自测 | `backend/src/test/**/*Test.java` | SpringBootTest + MariaDB4j |
|
||||
| View | E2E 验收 | **QA 测试** | `e2e/tests/qa/` | Playwright |
|
||||
| — | E2E 自测 | 开发自测 | `e2e/tests/dev/` | Playwright |
|
||||
| Composable / Store / Component | 单元测试 | 开发自测 | `frontend/src/**/*.test.ts` | Vitest |
|
||||
| — | 手动用例 | **QA 测试** | `docs/test-cases/manual-cases/` | 人工 |
|
||||
| — | 冒烟用例 | **QA 测试** | `docs/test-cases/smoking-cases/` | 人工 / 自动化 |
|
||||
| — | 自测场景索引 | 开发自测 | `docs/test-cases/dev-self-cases/` | 可选文本索引 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 开发自测规范
|
||||
|
||||
### 2.1 后端分层测试策略
|
||||
|
||||
| 层次 | 测试类型 | 关注点 |
|
||||
|------|----------|--------|
|
||||
| Adapter | 集成测试 | 请求/响应/状态码/错误码 |
|
||||
| Application | 单元测试 | 用例编排/事务边界 |
|
||||
| Domain | 单元测试 | 业务不变量/状态机 |
|
||||
| Infrastructure | 集成测试 | 持久化/映射正确性 |
|
||||
|
||||
### 2.2 Adapter 层集成测试约定
|
||||
|
||||
- 基类:`TestBase` 继承 `@SpringBootTest(webEnvironment = RANDOM_PORT)`
|
||||
- HTTP 客户端:RestAssured(配置端口 + 日志)
|
||||
- 数据隔离:`@BeforeEach` 重置所有表
|
||||
- 认证:使用 `loginAsUser()` / `loginAsAdmin()` 辅助方法获取 Token
|
||||
|
||||
### 2.3 命名
|
||||
|
||||
- 类名:`{被测Controller}Test`(如 `AuthControllerTest`)
|
||||
- 方法名:`should_{action}_{expectedResult}`(如 `should_register_and_return_token`)
|
||||
- 用例名 **不写** `TC-` 编号 —— 编号属于 QA 用例
|
||||
|
||||
### 2.4 覆盖要求(每个 Controller 测试)
|
||||
|
||||
- 1 个 happy path
|
||||
- 2 个错误分支
|
||||
- 涉及聚合写入的,补 1 个业务冲突分支
|
||||
|
||||
### 2.5 前端单元测试(Vitest)
|
||||
|
||||
- 测试文件与源码同目录,以 `.test.ts` 结尾
|
||||
- Composable 测试:mock service 层,验证响应式状态
|
||||
- Store 测试:使用 `setActivePinia(createPinia())` 隔离 store 实例
|
||||
|
||||
---
|
||||
|
||||
## 3. QA 测试规范
|
||||
|
||||
### 3.1 四类 QA 产物
|
||||
|
||||
| 产物 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| 文本验收用例 | `docs/test-cases/e2e-cases/test-cases.md` | QA 用例的 **基线**,先写这里 |
|
||||
| E2E 自动化 | `e2e/tests/qa/*.spec.ts` | 文本用例的自动化实现,编号一一对应 |
|
||||
| 手动用例 | `docs/test-cases/manual-cases/manual-test-cases.md` | 自动化难覆盖 / 需人工判断 |
|
||||
| 冒烟用例 | `docs/test-cases/smoking-cases/smoking-test-cases.md` | 发版前 5 分钟跑完的最小集 |
|
||||
| 开发自测索引 | `docs/test-cases/dev-self-cases/` | 可选;可执行用例仍在源码旁 / `e2e/tests/dev/` |
|
||||
|
||||
### 3.2 编号约定
|
||||
|
||||
- QA 用例统一编号 `TC-xxx`(文本用例与自动化用例 **共用** 同一编号)
|
||||
- 业务规则编号(`R-xxx`)与用例编号(`TC-xxx`)是 **映射关系**,不是同一个编号空间
|
||||
- 自动化用例的 `test()` 标题里带上 `TC-xxx`,便于双向追溯:
|
||||
|
||||
```ts
|
||||
test('TC-021 预约成功后出现在预约列表中', async ({ page }) => {
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
### 3.3 覆盖要求
|
||||
|
||||
- 需求规格 §12 的 **每条** 验收标准 → 至少 1 条 QA 用例
|
||||
- 每条业务规则(`R-xxx`)→ 至少 1 条 QA 用例
|
||||
- 至少覆盖:Happy Path / 参数错误 / 权限不足 / 业务冲突 / 边界
|
||||
|
||||
### 3.4 可重复执行
|
||||
|
||||
- 用例之间 **不能有顺序依赖**
|
||||
- 每个用例自己准备数据、自己清理数据
|
||||
- 不依赖真实外部服务的时间点、随机数、当前时间
|
||||
|
||||
### 3.5 运行
|
||||
|
||||
```bash
|
||||
cd e2e
|
||||
npm run test:qa # 只跑 QA 验收用例(合并闸门)
|
||||
npm run test:dev # 只跑开发自测用例
|
||||
npm test # 全部
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 合并闸门
|
||||
|
||||
| 闸门 | 要求 | 谁判定 |
|
||||
|---|---|---|
|
||||
| 开发自测 | `mvn test` 全绿、`npm run build` 通过、`npm run test:dev` 不阻塞 | 开发 |
|
||||
| QA 验收 | `npm run test:qa` 全绿 + 文本用例逐条勾选 | QA |
|
||||
|
||||
**QA 闸门未过,不能合并。** 开发自测不过,先修再提。
|
||||
|
||||
---
|
||||
|
||||
## 5. 测试环境
|
||||
|
||||
- 测试使用 `application.yml`(test resources),配置 MariaDB4j
|
||||
- Flyway 在测试中禁用(`spring.flyway.enabled=false`)
|
||||
- `@ActiveProfiles("test")` 在 TestBase 中设置
|
||||
- 测试使用 `schema.sql` + `data.sql` 初始化数据
|
||||
- ResetDbService 在每个 `@BeforeEach` 中 TRUNCATE 全表
|
||||
- DB 相关用例必须可重复执行,不依赖执行顺序
|
||||
Reference in New Issue
Block a user