2 Commits

147 changed files with 7356 additions and 13347 deletions
-318
View File
@@ -1,318 +0,0 @@
# AGENT.md — 健身房管理系统 AI 协作工作流
## 概述
本项目采用"需求驱动开发"Requirement-Driven Development)工作流,通过以下四个核心命令完成从模糊需求到可运行代码的全流程。遇到复杂 Bug 时可随时调用 `/systemic-debugging` 进行系统化诊断。
---
## 项目技术栈与模块结构
### 技术栈总览
| 层 | 技术栈 | 目录 | 测试框架 |
|---|---|---|---|
| 后端 API | Java Spring BootMaven 多模块) | `gym-manage-api/` | JUnit + Spring Boot Test |
| 管理后台 Web | Vue.js | `gym-manage-web/` | Playwright E2E |
| 会员小程序 | UniApp | `gym-manage-uniapp/` | — |
| 端到端测试 | Playwright | `e2e-tests/` | Playwright |
### 后端模块映射
| 模块 | 目录 | 职责 |
|---|---|---|
| manage-app | `gym-manage-api/manage-app/` | 应用启动入口、配置中心 |
| manage-gateway | `gym-manage-api/manage-gateway/` | API 网关、路由转发 |
| manage-common | `gym-manage-api/manage-common/` | 公共工具、通用组件 |
| manage-db | `gym-manage-api/manage-db/` | 数据库迁移(Flyway)、基础实体 |
| manage-sys | `gym-manage-api/manage-sys/` | 系统管理(用户/角色/权限/菜单/字典/文件/通知/日志) |
| manage-audit | `gym-manage-api/manage-audit/` | 审计日志 |
| manage-file | `gym-manage-api/manage-file/` | 文件管理 |
| manage-notify | `gym-manage-api/manage-notify/` | 消息通知 |
| gym-auth | `gym-manage-api/gym-auth/` | 认证授权、JWT |
| gym-member | `gym-manage-api/gym-member/` | 会员管理(注册/信息/会员卡) |
| gym-groupCourse | `gym-manage-api/gym-groupCourse/` | 团课管理、团课预约 |
| gym-checkIn | `gym-manage-api/gym-checkIn/` | 签到管理 |
| gym-dataCount | `gym-manage-api/gym-dataCount/` | 数据统计 |
| gym-payment | `gym-manage-api/gym-payment/` | 支付集成、支付对账 |
### 涉及模块的判断原则
`/to-issues``/test-driven-development` 阶段,根据功能需求确定涉及的模块。例如:
- "会员卡购买" → `gym-member` + `gym-payment` + `gym-manage-web` + `gym-manage-uniapp`
- "团课预约" → `gym-groupCourse` + `gym-member` + `gym-manage-uniapp`
- "系统管理"类功能 → `manage-sys` + `gym-manage-web`
---
## 工作流总览
```
/grill-with-docs → /to-prd → /to-issues → /test-driven-development
↓ ↓ ↓ ↓
需求澄清 结构化PRD 任务拆解 TDD实现
+ 领域建模
(CONTEXT.md)
```
---
## 0. /domain-modeling — 领域建模(贯穿全流程)
**目标**:建立并维护项目的统一语言(Ubiquitous Language),确保需求、设计、代码中术语一致。
### 核心产出
- 项目根目录的 [CONTEXT.md](./CONTEXT.md) — 术语表,不含任何实现细节,纯粹的概念定义和关系。
### 执行时机
- **在 `/grill-with-docs` 阶段**:识别新术语,与用户确认定义,写入 `CONTEXT.md`
- **在 `/to-prd` 阶段**:引用 `CONTEXT.md` 中的术语,保持 PRD 术语一致。
- **在 `/to-issues` 阶段**:确保每个 Issue 使用的术语与 `CONTEXT.md` 对齐。
- **在 `/test-driven-development` 阶段**:代码中的类名、方法名、变量名需反映领域术语。
### 领域术语规则
1. **挑战模糊语言**:当用户使用模糊或过载的术语时,提出精确的规范术语。例如:"你说的'账户'是指会员(Member)还是用户(User)?它们是不同的概念。"
2. **冲突检测**:当用户使用的术语与 `CONTEXT.md` 中已定义的不同时,立即指出:"你的术语表将'取消'定义为 X,但你现在似乎指 Y — 是哪个?"
3. **场景验证**:用具体的边界场景压力测试领域关系。例如:"如果会员卡已过期,预约还能取消吗?"
4. **代码交叉验证**:当需要确认某个术语的实际语义时,查阅现有代码实现,如有矛盾及时指出。
### 更新原则
- 术语一经确认,立即更新 `CONTEXT.md`,不要批量处理。
- 只在有实际产出时才创建或修改 `CONTEXT.md`
---
## 1. /grill-with-docs — 需求澄清与领域建模
**目标**:通过结构化问答 + 领域建模,将模糊需求转化为清晰、文档化的共识。
### 触发条件
- 用户提出新功能需求但描述不完整
- 需求存在歧义或矛盾
- 需要明确验收标准
### 执行流程
1. **收集原始需求**:理解用户意图,记录关键信息。
2. **启动领域建模**:识别需求中涉及的领域概念,对照 [CONTEXT.md](./CONTEXT.md) 检查术语一致性,新术语与用户确认后写入。
3. **识别模糊点**:主动指出需求中的歧义、缺失、矛盾之处。
4. **逐轮问答**:每次只问 1-2 个关键问题,避免信息过载。使用 `AskUserQuestion` 工具。
5. **生成共识文档**:将确认后的需求写入 `docs/superpowers/plans/` 目录,文件名格式为 `{YYYY-MM-DD}-{功能名称}-grill.md`,内容包括:
- 功能概述
- 用户故事
- 业务流程(Mermaid 流程图)
- 验收标准
- 涉及的领域概念(引用 `CONTEXT.md`
- 非功能需求
- 待确认项(如有)
### 规则
- 不要在分歧未解决前进入下一阶段。
- 所有关键决策需用户确认。
- 文档使用中文,保持与项目已有文档风格一致。
- 新术语必须写入 `CONTEXT.md` 后再用于文档。
---
## 2. /to-prd — 生成产品需求文档
**目标**:将澄清后的需求转化为结构化的 PRD。
### 输入
- `/grill-with-docs` 生成的共识文档(`docs/superpowers/plans/{日期}-{功能名称}-grill.md`
- 项目的功能清单文档([基础版功能清单.md](./基础版功能清单.md)
- 领域术语表([CONTEXT.md](./CONTEXT.md)
### 执行流程
1. **读取共识文档**:理解需求全貌。
2. **参考现有规范**:对照 [基础版功能清单.md](./基础版功能清单.md) 中的优先级定义(P0/P1/P2/P3)、技术规范和文档风格。
3. **术语对齐**:对照 [CONTEXT.md](./CONTEXT.md),确保 PRD 使用的所有业务术语与术语表一致。
4. **生成 PRD**:将 PRD 写入 `docs/superpowers/specs/` 目录,文件名格式为 `{YYYY-MM-DD}-{功能名称}-prd.md`,内容结构:
- 文档元信息(编号、版本、日期、状态)
- 功能概述与目标
- 用户故事(As a... I want... So that...
- 功能详细描述(功能点、优先级、验收标准、依赖关系、预计工时)
- 涉及的后端模块(参考模块映射表)
- 业务流程(Mermaid 流程图)
- 业务规则
- 非功能需求(性能、安全、可用性)
- UI/UX 要求(如适用)
- 技术要点建议
### 规则
- PRD 格式严格对齐 [基础版功能清单.md](./基础版功能清单.md) 的风格。
- 优先级标记使用 P0/P1/P2/P3 体系。
- 每个功能点必须有明确的验收标准。
- 必须在 PRD 中标注涉及的后端模块和前端应用。
---
## 3. /to-issues — 任务拆解
**目标**:将 PRD 拆解成可独立执行、可验证的具体任务(Issues)。
### 输入
- `/to-prd` 生成的 PRD`docs/superpowers/specs/{日期}-{功能名称}-prd.md`
- 领域术语表([CONTEXT.md](./CONTEXT.md)
### 拆解原则
**纵向拆分(全栈 Issue**:每个 Issue 按功能维度拆分,覆盖完整的前后端链路。
- 一个 Issue = 一个可独立交付的功能点,包含后端 API + Web 前端 + 小程序(按需)。
- TDD 顺序:后端单元测试 → 后端实现 → 前端 E2E 测试 → 前端实现。
**粒度控制**
- 预计工时不超过 2 天,超过则继续拆解。
- Issue 粒度应足够小,确保一个 Issue 可以在一轮对话中实现。
**优先级与排序**
- P0 任务排在 P1 之前,同一优先级下按依赖拓扑排序。
- 每个 Issue 标注依赖关系。
### 输出
写入 `docs/superpowers/issues/` 目录(如不存在则创建),文件名格式为 `ISSUES-{功能名称}.md`,内容结构:
```markdown
## GYM-{编号}: {标题}
- **优先级**: P0 / P1 / P2 / P3
- **预计工时**: {天数}天
- **依赖**: GYM-{编号} 或 无
- **涉及模块**: 后端模块列表 + 前端应用列表
- **领域术语**: 引用的 CONTEXT.md 术语
### 验收标准
1. 后端单元测试通过
2. E2E 测试通过
3. ...
### 技术要点
- 要点 1
- 要点 2
```
---
## 4. /test-driven-development — 测试驱动开发
**目标**:采用 TDD 方式,按 Red-Green-Refactor 循环逐个实现 Issues。
### 前置步骤(每个 Issue 开始前必须执行)
1. **阅读 Issue 描述**:理解全栈范围(涉及哪些后端模块和前端应用)。
2. **阅读 [CONTEXT.md](./CONTEXT.md)**:确认使用的领域术语,确保代码命名一致。
3. **阅读现有测试基础设施**
- E2E 测试:`e2e-tests/helpers/`TestDataManager、TestStabilityHelper、auth.ts)、`e2e-tests/pages/`Page Object 模式)、`e2e-tests/fixtures/``e2e-tests/utils/`TestDataFactory、RetryHelper、api-client
- 后端测试:参考 `gym-checkIn/src/test/``gym-payment/src/test/` 等现有模块测试用例的风格和结构
- 遵循已有的 Page Object、DataFactory、Smoke/Journey 测试分层 pattern
### 执行流程
按 Issue 顺序逐个实现,每个 Issue 遵循三步循环:
#### Step 1: Red — 编写失败的测试
1. 先写后端单元测试(JUnit),验证 API 逻辑和边界条件。
2. 运行后端测试,确认测试失败(红色)。
3. 写前端 E2E 测试(Playwright),覆盖用户操作链路。
4. 运行 E2E 测试,确认测试失败(红色)。
#### Step 2: Green — 编写最小实现
1. 编写后端 API 代码,刚好让单元测试通过。
2. 运行后端测试,确认通过(绿色)。
3. 编写前端代码,刚好让 E2E 测试通过。
4. 运行 E2E 测试,确认通过(绿色)。
5. 不添加任何测试未覆盖的功能。
#### Step 3: Refactor — 重构优化
1. 在全部测试保持绿色的前提下重构代码。
2. 消除重复、改善命名(对齐 `CONTEXT.md` 术语)、优化结构。
3. 运行全部测试,确认仍然通过。
### 规则
- 一个 Issue 完成后再开始下一个。
- 每次只改最少代码。
- 测试优先覆盖核心逻辑和边界条件。
- 代码风格严格遵循项目现有规范。
- 代码命名必须对齐 [CONTEXT.md](./CONTEXT.md) 中的领域术语。
- 所有测试通过后方可标记 Issue 为完成。
---
## 5. /systemic-debugging — 系统化调试
**目标**:当遇到复杂 Bug 时,通过系统化诊断流程定位根因并修复。
### 触发条件
- 遇到难以复现的 Bug
- 多轮尝试修复无效
- 用户明确请求调试
### 执行流程
1. **定义问题**:明确描述 Bug 的现象、触发条件和预期行为。
2. **收集证据**:查看相关日志、错误堆栈、数据库状态(检查 Flyway 迁移版本)、网络请求等。
3. **建立假设**:基于证据提出 1-3 个可能的根因假设。
4. **验证假设**:通过添加日志、编写最小复现用例、断点调试等方式验证或排除假设。一次只验证一个假设。
5. **修复与验证**:定位根因后编写修复代码,确保测试覆盖该场景。
6. **回归检查**:运行全部测试(后端 JUnit + 前端 E2E),确保修复未引入新问题。
### 规则
- 不要猜测式修复,每一步必须有证据支撑。
- 每次只验证一个假设。
- 修复后必须添加对应的回归测试。
---
## 目录结构约定
```
gym-manage/
├── AGENT.md # 本文件
├── CONTEXT.md # 领域术语表(统一语言)
├── 基础版功能清单.md # 项目功能清单(参考规范)
├── docs/
│ └── superpowers/ # AI 协作产出物
│ ├── plans/ # 需求澄清文档(/grill-with-docs 产出)
│ │ └── {YYYY-MM-DD}-{功能名称}-grill.md
│ ├── specs/ # PRD/to-prd 产出)
│ │ └── {YYYY-MM-DD}-{功能名称}-prd.md
│ └── issues/ # 任务拆解(/to-issues 产出)
│ └── ISSUES-{功能名称}.md
├── gym-manage-api/ # 后端 Java Spring Boot 多模块
│ ├── manage-app/ # 应用启动入口
│ ├── manage-gateway/ # API 网关
│ ├── manage-common/ # 公共组件
│ ├── manage-db/ # 数据库迁移
│ ├── manage-sys/ # 系统管理
│ ├── manage-audit/ # 审计日志
│ ├── manage-file/ # 文件管理
│ ├── manage-notify/ # 消息通知
│ ├── gym-auth/ # 认证授权
│ ├── gym-member/ # 会员管理
│ ├── gym-groupCourse/ # 团课管理
│ ├── gym-checkIn/ # 签到管理
│ ├── gym-dataCount/ # 数据统计
│ └── gym-payment/ # 支付集成
├── gym-manage-web/ # 管理后台 Web 前端
├── gym-manage-uniapp/ # 会员小程序前端
└── e2e-tests/ # 端到端测试
├── helpers/ # TestDataManager、auth 等
├── pages/ # Page Object 模式
├── fixtures/ # 测试数据
├── utils/ # TestDataFactory、RetryHelper
├── journeys/ # 用户旅程测试
└── smoke/ # 冒烟测试
```
---
## 通用规则
- **语言**:所有文档和代码注释使用中文,代码标识符使用英文。
- **术语对齐**:所有文档和代码中的业务术语必须对齐 [CONTEXT.md](./CONTEXT.md)。
- **风格对齐**:严格遵循项目现有代码风格和文档风格。
- **每一步确认**:关键产出(grill 文档、PRD、Issues)完成后通知用户确认再继续。
- **最小化原则**:不添加需求范围外的功能,不引入不必要的复杂度。
- **测试优先**:后端单元测试和前端 E2E 测试必须在新代码之前编写。
-169
View File
@@ -1,169 +0,0 @@
# CONTEXT.md — 健身房管理系统 领域术语表
> 本文档定义项目的统一语言(Ubiquitous Language),确保需求、设计、代码、测试中术语一致。
> 不含任何实现细节,仅为概念定义和关系。
---
## 一、核心业务概念
### 租户 (Tenant)
健身房经营实体。每个租户拥有独立的小程序、服务号、品牌配置。系统中的所有业务数据按租户隔离。
### 会员 (Member)
在健身房消费的终端用户。通过微信小程序注册,拥有会员档案、会员卡和预约记录。
### 用户 (User)
系统管理端的操作人员(健身房员工)。包括管理员、前台、店长等,拥有不同的角色和权限。
### 管理员 (Admin)
拥有系统最高权限的用户,可管理所有用户、角色、权限、配置。
### 教练 (Coach)
负责团课授课的人员,属于用户的一种扩展身份。
---
## 二、微信生态概念
### 小程序 (Mini Program / MiniApp)
会员端的微信小程序入口。用户通过小程序完成登录、浏览课程、预约、签到等操作。
### 服务号 (Service Account)
用于向会员推送模板消息的微信服务号。发送预约提醒、签到通知、会员卡到期提醒等。
### 开放平台 (Open Platform)
微信开放平台,用于统一小程序和服务号的用户身份(通过 UnionID)。
### UnionID
微信开放平台下的统一用户标识。同一微信开放平台账号下的不同应用(小程序、服务号),同一用户的 UnionID 相同。
### OpenID
单个微信应用下的用户标识。同一用户在不同应用中 OpenID 不同。
### 模板消息 (Template Message)
通过服务号向会员发送的结构化通知消息。每月限额 4 条/用户。
---
## 三、团课与预约
### 团课 (Group Course)
健身房提供的团体健身课程。包含课程名称、教练、时间、地点、容量(最多 20 人)等信息。
### 团课类型 (Course Type)
团课的分类维度,如"瑜伽、动感单车、搏击操"等。
### 团课标签 (Course Label)
团课的标记维度,如"新手友好、高强度、减脂"等。
### 团课推荐 (Course Recommendation)
管理员手动标记的推荐课程,在小程序首页优先展示。
### 预约 (Booking / Reservation)
会员报名参加团课的操作。预约成功后扣减会员卡权益,课程开始前 30 分钟截止预约。
### 取消预约 (Cancel Booking)
会员取消已报名的团课。需在课程开始前至少 2 小时操作,取消后自动退还权益。
---
## 四、会员卡
### 会员卡 (Membership Card)
会员购买的权益凭证,分为三种类型:
- **时长卡 (Duration Card)**:在有效期内无限次使用
- **次卡 (Count Card)**:按次数扣减
- **储值卡 (Stored Value Card)**:按金额扣减
### 会员卡权益 (Card Entitlement)
会员卡包含的可使用权益,如每日入场次数、可预约课程数。
### 会员卡状态 (Card Status)
会员卡的生命周期状态:激活、冻结、到期、已退款。
### 到期提醒 (Expiry Reminder)
会员卡到期前 7 天通过服务号模板消息向会员发送提醒。
---
## 五、签到
### 签到 (Check-in)
会员到场时的身份确认操作。需验证会员卡有效性和预约信息(如有团课预约)。
### 签到码 (Check-in Code)
会员出示的动态二维码,用于前台/设备扫描签到。
---
## 六、支付
### 支付 (Payment)
会员购买会员卡或课程时的在线支付操作,支持微信支付和支付宝支付。
### 退款 (Refund)
将已支付金额原路退回会员账户的操作。
### 对账 (Reconciliation)
每日将系统支付记录与微信/支付宝账单进行比对核验的过程。
---
## 七、权限与审计
### 角色 (Role)
权限的集合。系统中的角色包括管理员、店长、前台等,采用 RBAC(基于角色的访问控制)模型。
### 权限 (Permission)
对系统资源的操作许可。包括菜单访问权限、按钮操作权限、数据查看权限。
### 菜单 (Menu)
管理后台的导航入口,通过权限控制可见性。
### 操作日志 (Operation Log)
记录用户在系统中的关键操作(增删改),用于审计追溯。
### 登录日志 (Login Log)
记录用户的登录行为,包括登录 IP、时间、结果。
### 异常日志 (Exception Log)
记录系统运行时异常,用于问题排查。
---
## 八、配置
### 参数配置 (System Config)
系统级别的可调参数,如签到超时时间、预约截止时间等,通过管理后台的参数配置页面管理。
### 字典 (Dictionary)
系统使用的枚举值配置,如下拉选项、状态值等,通过字典管理页面维护。
### 轮播图 (Banner)
小程序首页的推广图片,通过管理后台管理。
### 通知公告 (Notice)
向会员或用户发布的系统公告,通过管理后台管理。
---
## 九、测试相关概念
### 冒烟测试 (Smoke Test)
每次提交后运行的快速验证测试,覆盖核心登录/登出流程,执行时间 ≤ 5 分钟。
### 用户旅程测试 (Journey Test / E2E)
模拟真实用户完整操作链路的端到端测试。覆盖从登录到完成业务操作的全流程。
### 角色边界测试 (Role Boundary Test)
验证不同角色(Admin/普通用户/未登录)的权限隔离是否正确的测试。
### Page Object
E2E 测试中的设计模式,将页面元素定位和操作封装为类,提高测试可维护性。
### TestDataManager
测试数据管理器,负责测试数据的自动生成(带唯一前缀)和清理回调注册。
### TestDataFactory
测试数据工厂,提供随机的测试数据对象(用户、角色、菜单等)。
Vendored
+250 -143
View File
@@ -1,203 +1,310 @@
pipeline {
agent any
parameters {
choice(
name: 'TEST_SCOPE',
choices: ['smoke', 'full', 'all', 'miniapp'],
description: '测试范围: smoke=仅冒烟测试, full=完整E2E, all=所有测试含性能, miniapp=仅小程序'
)
choice(
name: 'BROWSER',
choices: ['chromium', 'all'],
description: '目标浏览器: chromium=单浏览器快速, all=全浏览器'
)
string(
name: 'BASE_URL',
defaultValue: 'http://localhost:3002',
description: '测试目标URL'
)
}
environment {
PLAYWRIGHT_HEADLESS = 'true'
CI = 'true'
NODE_ENV = 'test'
JEST_JUNIT_OUTPUT_DIR = 'test-results'
JEST_JUNIT_OUTPUT_NAME = 'junit.xml'
// 项目配置
PROJECT_NAME = 'gym-manage-system'
FRONTEND_DIR = 'gym-manage-web'
BACKEND_DIR = 'gym-manage-api'
// Node.js 配置
NODE_VERSION = '20'
PNPM_VERSION = '8.15.0'
// Java 配置
JAVA_VERSION = '17'
MAVEN_VERSION = '3.9.0'
// Docker 配置
DOCKER_REGISTRY = credentials('docker-registry')
DOCKER_IMAGE_FRONTEND = "${PROJECT_NAME}-frontend"
DOCKER_IMAGE_BACKEND = "${PROJECT_NAME}-backend"
// 数据库配置(用于E2E测试)
DB_HOST = 'localhost'
DB_PORT = '5432'
DB_NAME = 'gym_test'
DB_USER = credentials('db-user')
DB_PASSWORD = credentials('db-password')
// 测试配置
TEST_TIMEOUT = '30'
RETRY_COUNT = '2'
}
tools {
nodejs "NodeJS-${NODE_VERSION}"
maven "Maven-${MAVEN_VERSION}"
jdk "JDK-${JAVA_VERSION}"
}
stages {
stage('环境准备') {
steps {
echo '🔧 准备构建环境...'
sh '''
# 安装 pnpm
npm install -g pnpm@${PNPM_VERSION}
# 验证工具版本
node --version
pnpm --version
java -version
mvn --version
'''
}
}
stage('代码检查') {
parallel {
stage('安装Web端依赖') {
stage('前端代码检查') {
steps {
dir('gym-manage-web') {
bat 'npm ci'
bat 'npx playwright install chromium --with-deps'
dir(FRONTEND_DIR) {
echo '🔍 执行前端代码检查...'
sh '''
pnpm install
pnpm run lint
pnpm run type-check
'''
}
}
}
stage('安装小程序端依赖') {
stage('后端代码检查') {
steps {
dir('gym-manage-uniapp') {
bat 'npm ci'
dir(BACKEND_DIR) {
echo '🔍 执行后端代码检查...'
sh 'mvn clean compile -DskipTests'
}
}
}
}
}
stage('启动后端服务') {
steps {
dir('gym-manage-api') {
bat 'mvn spring-boot:run -pl manage-app -DskipTests &'
bat 'mvn spring-boot:run -pl manage-gateway -DskipTests &'
stage('单元测试') {
parallel {
stage('前端单元测试') {
steps {
dir(FRONTEND_DIR) {
echo '🧪 执行前端单元测试...'
sh 'pnpm run test:unit'
}
}
post {
always {
dir(FRONTEND_DIR) {
// 发布测试报告
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'coverage',
reportFiles: 'index.html',
reportName: '前端单元测试覆盖率报告'
])
}
}
}
}
// 等待后端健康检查
script {
retry(10) {
sleep(10)
try {
def response = httpRequest 'http://localhost:8084/actuator/health'
print "后端健康状态: ${response.content}"
} catch (err) {
error "后端尚未就绪: ${err.message}"
stage('后端单元测试') {
steps {
dir(BACKEND_DIR) {
echo '🧪 执行后端单元测试...'
sh 'mvn test'
}
}
post {
always {
dir(BACKEND_DIR) {
// 发布测试报告
junit '**/target/surefire-reports/*.xml'
// 发布代码覆盖率报告
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'target/site/jacoco',
reportFiles: 'index.html',
reportName: '后端单元测试覆盖率报告'
])
}
}
}
}
}
}
stage('冒烟测试') {
stage('构建') {
parallel {
stage('前端构建') {
steps {
dir(FRONTEND_DIR) {
echo '📦 构建前端项目...'
sh '''
pnpm run build:prod
# 创建构建产物归档
tar -czf frontend-dist.tar.gz dist/
'''
}
}
post {
success {
archiveArtifacts artifacts: "${FRONTEND_DIR}/frontend-dist.tar.gz", fingerprint: true
}
}
}
stage('后端构建') {
steps {
dir(BACKEND_DIR) {
echo '📦 构建后端项目...'
sh '''
mvn clean package -DskipTests
# 创建构建产物归档
tar -czf backend-jars.tar.gz */target/*.jar
'''
}
}
post {
success {
archiveArtifacts artifacts: "${BACKEND_DIR}/backend-jars.tar.gz", fingerprint: true
}
}
}
}
}
stage('E2E测试') {
steps {
dir('gym-manage-web') {
bat 'npm run test:e2e:smoke'
echo '🎭 执行E2E测试...'
dir(FRONTEND_DIR) {
sh '''
# 安装Playwright浏览器
pnpm exec playwright install --with-deps chromium
# 执行E2E测试
pnpm run test:e2e:journeys
'''
}
}
post {
failure {
echo '冒烟测试失败,跳过后续测试'
}
}
}
stage('Web E2E 测试') {
when {
expression { params.TEST_SCOPE != 'smoke' }
}
steps {
dir('gym-manage-web') {
script {
def projectFilter = params.TEST_SCOPE == 'all'
? ''
: '--project=root --project=journeys'
bat "npx playwright test ${projectFilter}"
always {
dir(FRONTEND_DIR) {
// 发布E2E测试报告
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'test-results',
reportFiles: 'custom-report.html',
reportName: 'E2E测试报告'
])
// 归档测试失败截图和视频
archiveArtifacts artifacts: 'test-results/**/*.png, test-results/**/*.webm', allowEmptyArchive: true
}
}
}
}
stage('性能测试') {
stage('构建Docker镜像') {
when {
expression { params.TEST_SCOPE == 'all' }
branch 'develop'
}
steps {
dir('gym-manage-web') {
bat 'npm run test:e2e:perf'
echo '🐳 构建Docker镜像...'
// 构建前端镜像
dir(FRONTEND_DIR) {
sh """
docker build -t ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:${BUILD_NUMBER} .
docker tag ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:${BUILD_NUMBER} ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:latest
"""
}
// 构建后端镜像
dir(BACKEND_DIR) {
sh """
docker build -t ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:${BUILD_NUMBER} .
docker tag ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:${BUILD_NUMBER} ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:latest
"""
}
}
}
stage('角色边界测试') {
stage('推送Docker镜像') {
when {
expression { params.TEST_SCOPE == 'all' }
branch 'develop'
}
steps {
dir('gym-manage-web') {
bat 'npx playwright test --grep "权限|角色|边界|boundary"'
}
echo '📤 推送Docker镜像到仓库...'
sh """
docker push ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:${BUILD_NUMBER}
docker push ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:latest
docker push ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:${BUILD_NUMBER}
docker push ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:latest
"""
}
}
stage('小程序编译') {
stage('部署到测试环境') {
when {
anyOf {
expression { params.TEST_SCOPE == 'all' }
expression { params.TEST_SCOPE == 'miniapp' }
}
branch 'develop'
}
steps {
dir('gym-manage-uniapp') {
bat 'npm run build:mp-weixin'
}
echo '🚀 部署到测试环境...'
sh """
# 这里可以添加部署脚本
# 例如:使用docker-compose或kubernetes部署
echo "部署前端镜像: ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:${BUILD_NUMBER}"
echo "部署后端镜像: ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:${BUILD_NUMBER}"
"""
}
}
stage('小程序 E2E 测试') {
stage('部署到生产环境') {
when {
anyOf {
expression { params.TEST_SCOPE == 'all' }
expression { params.TEST_SCOPE == 'miniapp' }
}
}
environment {
WECHAT_DEVTOOLS_CLI = 'D:\\微信web开发者工具\\cli.bat'
branch 'main'
}
steps {
dir('gym-manage-uniapp') {
script {
try {
// 使用一键脚本:自动启动 IDE → 运行测试 → 关闭 IDE
bat 'node e2e/run-tests.js --close --verbose'
} catch (err) {
echo "小程序 E2E 测试失败:${err.message}"
// 失败也继续(IDE 可能不可用)
unstable('小程序 E2E 测试未通过')
}
}
}
echo '🚀 部署到生产环境...'
input message: '确认部署到生产环境?', ok: '确认部署'
sh """
# 这里可以添加生产环境部署脚本
# 例如:使用kubernetes进行滚动更新
echo "部署前端镜像: ${DOCKER_REGISTRY}/${DOCKER_IMAGE_FRONTEND}:${BUILD_NUMBER}"
echo "部署后端镜像: ${DOCKER_REGISTRY}/${DOCKER_IMAGE_BACKEND}:${BUILD_NUMBER}"
"""
}
}
}
post {
always {
// 归档测试报告
dir('gym-manage-web') {
archiveArtifacts artifacts: 'test-results/**/*', allowEmptyArchive: true
archiveArtifacts artifacts: 'playwright-report/**', allowEmptyArchive: true
junit 'test-results/junit.xml'
}
// 归档小程序测试报告
dir('gym-manage-uniapp') {
archiveArtifacts artifacts: 'test-results/**/*', allowEmptyArchive: true
}
}
failure {
// 失败通知
script {
def failedTests = currentBuild.rawBuild.getLog(50)
emailext(
subject: "[测试失败] ${env.JOB_NAME} - Build #${env.BUILD_NUMBER}",
body: """
<h2>UI 自动化测试失败</h2>
<p><b>Job:</b> ${env.JOB_NAME}</p>
<p><b>Build:</b> #${env.BUILD_NUMBER}</p>
<p><b>分支:</b> ${env.BRANCH_NAME}</p>
<p><b>日志:</b> <a href="${env.BUILD_URL}">${env.BUILD_URL}</a></p>
<h3>最后 50 行日志:</h3>
<pre>${failedTests}</pre>
""",
mimeType: 'text/html',
to: 'dev-team@gym-manage.com'
)
}
echo '🧹 清理工作空间...'
cleanWs()
}
success {
echo "全部 UI 测试通过!"
echo '✅ 流水线执行成功!'
// 可以添加通知,例如发送邮件或Slack消息
}
failure {
echo '❌ 流水线执行失败!'
// 可以添加失败通知
}
unstable {
echo '⚠️ 流水线执行不稳定!'
// 可以添加不稳定状态通知
}
}
}
@@ -1,319 +0,0 @@
# UI 层级全自动测试套件 — 需求共识文档
> **文档编号**: GYM-GRILL-UI-TEST-001
> **日期**: 2026-07-21
> **状态**: 已确认
> **产出命令**: /grill-with-docs
---
## 一、功能概述
为健身房管理系统构建 UI 层级的全自动测试套件,覆盖 **管理后台 WebVue 3****会员小程序(UniApp** 两个 UI 终端,确保所有已实现功能通过系统化测试,达到 ≥95% 通过率的交付水平。
### 目标终端
| UI 层级 | 技术栈 | 当前测试状态 | 目标 |
|---|---|---|---|
| 管理后台 Web | Vue 3 + Element Plus + Vite | Vitest 单元测试 + Playwright E2E81%通过率) | 修复失败 → 补齐覆盖 → ≥95% |
| 会员小程序 | UniAppVue | **零测试** | 从零构建 → 完整覆盖 |
---
## 二、当前状态分析
### 2.1 已实现功能清单(管理后台 - 21个页面)
| 模块 | 页面 | 关联功能清单 | 已有 E2E Page Object | 已有 E2E 测试 |
|---|---|---|---|---|
| 系统管理 | Login / Dashboard / 403 | P0 模块7 | LoginPage / DashboardPage | ✅ |
| 系统管理 | UserManagement | P0 模块7 | UserManagementPage | ✅ journeys |
| 系统管理 | **CoachManagement** | —(额外功能) | ❌ | ❌ |
| 系统管理 | RoleManagement | P0 模块7 | RoleManagementPage | ✅ journeys |
| 系统管理 | MenuManagement | P0 模块7 | MenuManagementPage | ✅ |
| 配置 | ConfigManagement | —(额外功能) | SystemConfigPage | ✅ |
| 配置 | DictManagement | —(额外功能) | DictionaryManagementPage | ✅ |
| 文件 | FileManagement | —(额外功能) | FileManagementPage | ✅ |
| 通知 | NoticeManagement | —(额外功能) | NotificationPage | ✅ |
| 轮播图 | **BannerManagement** | —(额外功能) | ❌ | ❌ |
| 审计 | LoginLog | —(额外功能) | LoginLogPage | ✅ |
| 审计 | OperationLog | —(额外功能) | OperationLogPage | ✅ |
| 审计 | ExceptionLog | —(额外功能) | ExceptionLogPage | ✅ |
| 团课 | GroupCourseManagement | P1 模块2 | ❌ | ❌ (Page 缺失) |
| 团课 | CourseTypeManagement | P1 模块2 | ❌ | ❌ |
| 团课 | **CourseLabelManagement** | —(额外功能) | ❌ | ❌ |
| 团课 | **CourseRecommendManagement** | —(额外功能) | ❌ | ❌ |
| 会员 | **MemberManagement** | P1 模块1 | ❌ | ❌ |
| 会员 | **MemberCardManagement** | P0 模块1 | ❌ | ❌ |
| 统计 | **StatisticsDashboard** | P1 模块4 | ❌ | ❌ |
> 标记 `❌` 的为 **新增测试缺口**,共 **10 个页面**。
### 2.2 已实现功能清单(小程序 - 6个页面)
| 页面 | 关联功能清单 | 测试状态 |
|---|---|---|
| 首页 (index) | P0 模块1 微信登录入口 | ❌ |
| 登录 (login) | P0 模块1 微信快捷登录 | ❌ |
| 课程详情 (course-detail) | P0 模块2 团课详情 | ❌ |
| 我的课程 (my-courses) | P0 模块2 预约记录 | ❌ |
| 个人中心 (profile) | P0 模块1 会员信息 | ❌ |
| 搜索 (search) | P0 模块2 团课搜索 | ❌ |
### 2.3 现有测试资产
| 资产 | 状态 | 价值 |
|---|---|---|
| 12 个 Page Object | 成熟 | 可直接复用 |
| TestDataManager + TestDataFactory | 成熟 | 可直接复用 |
| RetryHelper + TestStabilityHelper | 成熟 | 可直接复用 |
| global-setup / global-teardown | 成熟 | 可直接复用 |
| customReporterHTML+JSON+控制台) | 成熟 | 可直接复用 |
| auth.setupstorageState | **有 Bug** | 需修复 storageState 冲突 |
| 10 个 Journey 测试(100%通过) | 健康 | 保持不变 |
### 2.4 现有失败测试分析(9个)
| 失败测试 | 根因 | 修复策略 |
|---|---|---|
| auth-test.spec.ts (4用例) | storageState 冲突:全局认证状态下,登录相关测试无法模拟未登录场景 | 为该文件配置独立 project(禁用 storageState |
| basic-ui-test.spec.ts | 已登录后重定向到 Dashboard 而非登录页 | 调整测试预期或独立 project |
| config-management.spec.ts | 超时/选择器不匹配 | 更新选择器,增加等待策略 |
| dict-management.spec.ts | 超时/选择器不匹配 | 同上 |
| menu-management.spec.ts | 超时/选择器不匹配 | 同上 |
| debug/debug-role-assignment.spec.ts | 测试逻辑问题 | 重写或移除 |
---
## 三、用户故事
### US-1: 测试工程师运行全量回归
> As a **测试工程师**
> I want **一键运行全部 UI 测试并自动生成报告**
> So that **每次发版前能快速确认系统质量状况**
### US-2: 开发者在 CI 中获得反馈
> As a **开发者**
> I want **Push 代码后 Jenkins 自动运行冒烟测试**
> So that **核心功能回归能在 5 分钟内给出反馈**
### US-3: 产品经理验证业务规则
> As a **产品经理**
> I want **测试覆盖功能清单中的业务规则和技术要点**
> So that **交付的功能与设计一致**
### US-4: 小程序团队确保质量
> As a **小程序开发者**
> I want **微信模拟器中的自动化测试**
> So that **小程序端的回归不需要手动点点点**
---
## 四、测试架构设计
### 4.1 整体分层
```
┌─────────────────────────────────────────────────┐
│ L3: 性能测试 (Performance) │
│ - 页面加载性能 │
│ - API 响应性能 │
│ - 报告:performance-report/ │
├─────────────────────────────────────────────────┤
│ L2: 用户旅程测试 (Journey Tests) │
│ - 管理后台:按模块拆分用户旅程 │
│ - 小程序:按页面拆分用户旅程 │
│ - 报告:test-results/ + customReporter │
├─────────────────────────────────────────────────┤
│ L1: 角色边界测试 (Role Boundary) │
│ - 权限隔离验证 │
│ - 多角色并发验证 │
│ - 报告:test-results/ │
├─────────────────────────────────────────────────┤
│ L0: 冒烟测试 (Smoke) │
│ - 管理后台:登录/登出 │
│ - 小程序:启动/首页渲染 │
│ - 运行频次:每次 Push │
│ - 时限:≤ 5 分钟 │
└─────────────────────────────────────────────────┘
```
### 4.2 技术方案
| 层级 | 管理后台 Web | 会员小程序 |
|---|---|---|
| 框架 | Playwright + TypeScript | miniprogram-automator + Jest |
| 设计模式 | Page Object | Page Object(模拟) |
| 数据管理 | TestDataManager + TestDataFactory | 独立 DataFactory(复用 API 层) |
| 报告 | customReporterHTML+JSON | Jest HTML Reporter |
| 运行环境 | 复用 global-setup 自动启动服务 | 微信开发者工具 CLI + 模拟器 |
| CI | Jenkins Pipeline | Jenkins Pipeline |
---
## 五、业务流程(测试范围)
### 5.1 管理后台核心流程
```mermaid
flowchart LR
A[登录] --> B[Dashboard]
B --> C1[用户管理 CRUD]
B --> C2[角色管理 + 权限分配]
B --> C3[菜单管理]
C1 & C2 --> D[角色边界验证]
B --> E1[团课管理 CRUD]
B --> E2[会员管理 查看/搜索]
B --> E3[会员卡管理]
B --> E4[数据统计看板]
B --> F1[教练管理]
B --> F2[轮播图管理]
B --> F3[参数配置]
B --> F4[字典管理]
B --> F5[文件管理]
B --> F6[通知公告]
B --> F7[审计日志]
```
### 5.2 小程序核心流程
```mermaid
flowchart LR
A[微信授权登录] --> B[首页]
B --> C[搜索团课]
C --> D[课程详情]
D --> E[预约课程]
B --> F[我的课程]
F --> G[取消预约]
B --> H[个人中心]
```
---
## 六、验收标准
### 通用标准
| 编号 | 标准 | 量化指标 |
|---|---|---|
| AC-1 | 测试通过率 | ≥ 95%(总用例) |
| AC-2 | 核心业务链路 | 100% 通过(登录→关键操作→退出) |
| AC-3 | 冒烟测试耗时 | ≤ 5 分钟 |
| AC-4 | 全量 E2E 耗时 | ≤ 15 分钟(管理后台 + 小程序并行) |
| AC-5 | 测试报告 | 自动生成 HTML + JSON 报告,包含失败截图 |
| AC-6 | CI 集成 | Jenkins Pipeline 可一键触发,结果自动归档 |
| AC-7 | 测试数据隔离 | 每次运行使用独立数据前缀,运行后自动清理 |
| AC-8 | 稳定性 | 连续 3 次无随机失败(flake rate = 0% |
### 功能覆盖标准
| 编号 | 标准 |
|---|---|
| AC-9 | 管理后台 21 个页面,每个至少 1 个 Happy Path 测试 |
| AC-10 | 核心 CRUD 操作(用户/角色/团课)覆盖增删改查全流程 |
| AC-11 | 角色边界测试覆盖至少 3 个角色(Admin / 店长 / 前台) |
| AC-12 | 小程序 6 个页面,每个至少 1 个 Happy Path 测试 |
| AC-13 | 小程序预约/取消流程端到端验证 |
| AC-14 | 性能测试至少覆盖 Dashboard 和团课列表 2 个关键页面 |
---
## 七、实施计划(优先级排序)
### 第1阶段:修复现有测试(预计 1 天)
| 任务 | 产出 |
|---|---|
| 修复 storageState 冲突 | auth-test.spec.ts 4 个用例通过 |
| 为需要未登录状态的测试创建独立 Playwright project | basic-ui-test.spec.ts 通过 |
| 更新选择器 + 等待策略 | config/dict/menu 3 个 spec 通过 |
| 处理 debug 目录 | 重写或移除 debug-role-assignment |
| **目标** | 53/53 测试通过(100% |
### 第2阶段:补齐管理后台缺失测试(预计 2 天)
| 任务 | 覆盖页面 |
|---|---|
| 创建 10 个新 Page Object | CoachManagement, BannerManagement, GroupCourseManagement, CourseTypeManagement, CourseLabelManagement, CourseRecommendManagement, MemberManagement, MemberCardManagement, StatisticsDashboard(以及团课页面类) |
| 编写 8 个 Journey 测试 | 对应上述缺失页面 |
| 扩展角色边界测试 | 3 角色 × 5 关键页面 |
| 编写 2 个性能测试 | Dashboard + 团课列表 |
### 第3阶段:构建小程序测试(预计 2 天)
| 任务 | 产出 |
|---|---|
| 搭建 miniprogram-automator 环境 | 安装依赖、配置微信开发者工具 CLI |
| 创建小程序 Page Object(6 个页面) | 首页/登录/课程详情/我的课程/个人中心/搜索 |
| 编写 4 个 Journey 测试 | 登录→首页→课程详情→预约;登录→我的课程→取消;登录→个人中心→信息编辑;首页→搜索→课程详情 |
| 编写 1 个冒烟测试 | 启动→首页渲染→登录 |
### 第4阶段:Jenkins CI 集成(预计 1 天)
| 任务 | 产出 |
|---|---|
| 编写 Jenkinsfile | 定义 Stage:环境准备 → 冒烟测试 → 全量 E2E(Web + 小程序并行) → 性能测试 → 报告归档 |
| 配置测试报告归档 | HTML Report Plugin + JUnit Plugin |
| 配置失败通知 | 企业微信/邮件通知 |
---
## 八、涉及的领域概念
| 领域概念 | 测试关注点 |
|---|---|
| 会员 (Member) | 会员管理 CRUD、会员卡购买/查看 |
| 用户 (User) | 用户管理 CRUD、角色分配 |
| 角色 (Role) | 角色 CRUD、权限分配、边界验证 |
| 权限 (Permission) | 菜单可见性、按钮权限、越权访问验证 |
| 团课 (Group Course) | 团课 CRUD、类型/标签/推荐管理 |
| 预约 (Booking) | 预约/取消流程(小程序端) |
| 签到 (Check-in) | 扫码签到(后续迭代,依赖微信环境) |
| 会员卡 (Membership Card) | 会员卡管理、到期提醒 |
---
## 九、非功能需求
| 类型 | 要求 |
|---|---|
| **可靠性** | 连续 3 次运行无随机失败(flake-free |
| **可维护性** | Page Object 模式,禁止硬编码选择器 |
| **可扩展性** | 新页面通过添加 Page Object + 1 个 Journey 即可接入 |
| **数据隔离** | 测试数据使用唯一前缀,运行后自动清理,不影响开发环境 |
| **CI 兼容** | Jenkins Pipeline 声明式,参数化(支持选择运行范围) |
---
## 十、风险与应对
| 风险 | 应对策略 |
|---|---|
| miniprogram-automator 与 UniApp 兼容性问题 | 先用 H5 模式验证可行性,再切换模拟器 |
| 微信开发者工具在 Jenkins 无头环境运行受限 | Jenkins Agent 部署在 Windows 有桌面环境机器上 |
| 现有 E2E 测试大规模重构引入回归 | 第1阶段仅修复,不做重构;后续新增测试在独立文件中 |
| 小程序登录依赖真实微信环境 | 使用 Mock 微信 API 或测试用 OpenID/UnionID |
| 性能测试基准不稳定 | 取 3 次运行中位数,允许 ±15% 波动 |
---
## 十一、待确认项
- [x] UI 层级范围:管理后台 + 小程序
- [x] 功能范围:全部已实现功能,对齐功能清单业务规则
- [x] 交付标准:≥95% 通过率 + Jenkins CI
- [x] 测试类型:E2E / 冒烟 / 性能 / 角色边界 / 小程序专项
- [x] 小程序方案:miniprogram-automator
- [x] CI 平台:Jenkins
- [x] 测试环境:复用 global-setup
- [x] 优先级:修复现有 → 补齐 Web → 构建小程序 → CI
- [x] 用户体验测试 (UAT):**不纳入**,聚焦自动化测试,UAT 由人工执行
- [x] 视觉回归测试:**不纳入**,避免基准截图频繁更新的维护成本
---
## 十二、相关文档
- [CONTEXT.md](../../../CONTEXT.md) — 项目领域术语表
- [基础版功能清单.md](../../../基础版功能清单.md) — 功能清单与业务规则
- [AGENT.md](../../../AGENT.md) — AI 协作工作流规范
+41 -80
View File
@@ -1,99 +1,60 @@
# 三端自动化测试
# E2E测试说明
> 本项目覆盖 **后端 API**、**Web 后台管理系统**、**小程序** 三端的自动化测试,总计 **1,286+ 用例,100% 通过率**。
## 测试结构
---
本项目的E2E测试采用分层测试策略:
## 测试总览
### 冒烟测试(smoke/
| 端 | 测试类型 | 框架 | 用例数 | 通过率 | 详细文档 |
|---|---|---|---|---|---|
| **后端 API** | 单元 + 集成 | JUnit 5 + Mockito | 1,094 | 100% | [backend-api-test.md](docs/backend-api-test.md) |
| **Web 后台** | 单元(组件) | Vitest + jsdom | 171 | 100% | [web-admin-test.md](docs/web-admin-test.md) |
| **Web 后台** | E2E(端到端) | Playwright | 24+ | 100% | [web-admin-test.md](docs/web-admin-test.md) |
| **小程序** | E2E(端到端) | Jest + miniprogram-automator | 7 | 100% | [miniapp-test.md](docs/miniapp-test.md) |
快速验证基础功能是否正常工作。
---
- `login-logout.spec.ts` - 登录登出基础流程
## 各端运行方式
### 核心旅程测试(journeys/
验证关键业务端到端流程。
- `admin-complete-workflow.spec.ts` - 管理员完整工作流
- `user-permission-boundary.spec.ts` - 用户权限边界验证
- `file-management-workflow.spec.ts` - 文件上传下载流程
- `audit-workflow.spec.ts` - 审计日志查看流程
## 运行测试
### 运行冒烟测试
```bash
# 后端 API
cd gym-manage-api && mvn test
# Web 后台 — 单元测试
cd gym-manage-web && npm run test
# Web 后台 — E2E 测试
cd gym-manage-web && npm run test:e2e
# 小程序 — E2E 测试
cd gym-manage-uniapp && npx jest --config e2e/jest.config.js
npm run test:e2e:smoke
```
---
### 运行核心旅程测试
## 自动化触发时机
| 触发条件 | 后端 API | Web 单元 | Web E2E | 小程序 E2E |
|---|---|---|---|---|
| **Push 到功能分支** | ✅ 自动 | ✅ 自动 | ❌ | ❌ |
| **PR 提交到 main/master** | ✅ 自动 | ✅ 自动 | ✅ 自动 | ✅ 自动 |
| **合并到 main/master** | ✅ 自动 | ✅ 自动 | ✅ 自动 | ✅ 自动 |
| **每日定时(凌晨 2:00** | ✅ 自动 | ✅ 自动 | ✅ 自动 | ❌ |
| **手动触发** | ✅ | ✅ | ✅ | ✅ |
### 触发策略说明
**Push 到功能分支**(快速反馈,< 5 分钟):
- 运行后端单元测试 + Web 单元测试
- E2E 测试不触发(耗时较长,避免阻塞开发)
**PR / 合并到 main**(完整验证,< 15 分钟):
- 运行全部三端测试
- 小程序 E2E 需微信开发者工具环境,无环境时跳过
**每日定时**(全量回归):
- 凌晨自动运行全部测试,生成报告
- 小程序 E2E 除外(需 GUI 环境)
---
## 测试分层架构
```
┌─────────────────────────────────────────────────────┐
│ 三端测试体系 │
├──────────────┬──────────────────┬───────────────────┤
│ 后端 API │ Web 后台管理 │ 小程序 │
├──────────────┼──────────────────┼───────────────────┤
│ JUnit 5 │ Vitest (单元) │ Jest + automator │
│ Mockito │ jsdom (DOM模拟) │ (E2E) │
│ Reactor Test │ Playwright (E2E) │ │
├──────────────┼──────────────────┼───────────────────┤
│ 105 测试文件 │ 24 单元文件 │ 3 套件 │
│ 15 模块 │ 24+ E2E文件 │ 7 用例 │
│ 1,094 用例 │ 185+ 用例 │ 5 Page Object │
└──────────────┴──────────────────┴───────────────────┘
```bash
npm run test:e2e:journeys
```
---
### 运行所有测试
## 快速链接
```bash
npm run test:e2e
```
| 文档 | 内容 |
|---|---|
| [backend-api-test.md](docs/backend-api-test.md) | 后端 15 模块详细测试清单、API 路由覆盖、状态机测试矩阵 |
| [web-admin-test.md](docs/web-admin-test.md) | Vitest 24 文件详情 + Playwright 4 项目详情 + 17 个 Page Object |
| [miniapp-test.md](docs/miniapp-test.md) | 3 套件详情、预约+签到流程、Mock 策略、环境配置 |
| [../docs/test-report-2026-07-21.md](../docs/test-report-2026-07-21.md) | 全量测试报告(含测试路线图) |
| [../Jenkinsfile](../Jenkinsfile) | CI/CD 流水线配置 |
## 测试数据
---
测试使用的用户账号:
- 管理员:username: `admin`, password: `Test@123`
- 普通用户:username: `user`, password: `Test@123`
## 测试策略
- **冒烟测试**:每次代码提交时运行,快速反馈
- **核心旅程测试**:PR合并前运行,验证关键业务流程
- **单元测试**:补充功能覆盖率,目标80%
## 维护指南
1. **新增后端接口** → 在对应模块 `src/test/` 下添加 JUnit 测试,更新 [backend-api-test.md](docs/backend-api-test.md)
2. **新增 Web 页面** → 添加 Vitest 组件测试 + Page Object + E2E 旅程,更新 [web-admin-test.md](docs/web-admin-test.md)
3. **新增小程序功能** → 添加 E2E 用例或 Page Object,更新 [miniapp-test.md](docs/miniapp-test.md)
4. **修改 CI 触发规则** → 编辑 `Jenkinsfile`,同步更新本文档「自动化触发时机」章
1. 新增核心业务功能时,在 `journeys/` 目录下添加测试
2. 新增基础功能时,在 `smoke/` 目录下添加测试
3. 保持测试文件数量精简,避免重复测试
4. 优先使用单元测试覆盖功能细
-363
View File
@@ -1,363 +0,0 @@
# 后端 API 测试文档
> **位置**: `gym-manage-api/` | **框架**: JUnit 5 + Mockito + Maven | **用例数**: 1,094 | **通过率**: 100%
---
## 一、概览
后端 API 由 15 个 Maven 模块组成,采用 **Spring WebFlux** 响应式架构,测试覆盖 Handler(HTTP 入口)、Service(业务逻辑)、Util(工具类)、Filter(过滤器)、Converter(数据转换)等全层级。
| 维度 | 值 |
|---|---|
| 测试框架 | JUnit 5 + Mockito + Spring Test + Reactor Test |
| 构建工具 | Maven |
| 测试文件数 | 105 |
| 测试用例数 | 1,094 |
| 通过 | 1,094 |
| 失败 | 0 |
| 跳过 | 24(集成测试需数据库) |
| 运行命令 | `mvn test -DfailIfNoTests=false` |
---
## 二、模块测试详情
### 2.1 manage-sys(系统管理核心)— 658 tests
最核心的模块,覆盖用户、角色、菜单、字典、配置、日志、审计、认证、安全等全部子系统。
#### Handler 层(HTTP 入口,共 135 tests
| 测试类 | 文件 | 用例数 | 测试内容 |
|---|---|---|---|
| `SysAuthHandlerTest` | `handler/auth/` | 9 | 登录、注册、登出 |
| `SysUserHandlerTest` | `handler/user/` | 20 | 用户 CRUD、分页、批量操作、角色分配 |
| `SysRoleHandlerTest` | `handler/role/` | 16 | 角色 CRUD、软删除/恢复、权限分配 |
| `MenuHandlerTest` | `handler/menu/` | 13 | 菜单树查询、按类型筛选、父子关系 |
| `MenuHandlerDataIntegrityTest` | `handler/menu/` | 11 | 菜单数据完整性、循环引用检测、并发 |
| `SysDictHandlerTest` | `handler/dict/` | 17 | 字典类型+数据 CRUD、缓存刷新 |
| `DictionaryHandlerTest` | `handler/dictionary/` | 9 | 字典管理完整流程 |
| `SysConfigHandlerTest` | `handler/config/` | 9 | 系统配置增删改查、按 key 查询 |
| `SysLogHandlerTest` | `handler/log/` | 18 | 登录日志查询、筛选、统计 |
| `OperationLogHandlerTest` | `handler/log/` | 7 | 操作日志查询、按模块筛选 |
| `StatsHandlerTest` | `handler/stats/` | 1 | 统计概览 |
| `AuditLogControllerTest` | `audit/controller/` | 11 | 审计日志 CRUD、按实体/操作人/时间查询 |
#### Service 层(业务逻辑,共 157 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `SysUserServiceTest` | 30 | 用户创建、密码加密、角色绑定、分页、批量删除 |
| `SysUserServiceIntegrationTest` | 20 | 集成测试:用户+角色关联、事务回滚 |
| `SysRoleServiceTest` | 25 | 角色权限分配、菜单绑定、软删除恢复 |
| `SysMenuServiceTest` | 15 | 菜单树构建、排序、层级校验 |
| `SysDictTypeServiceTest` | 12 | 字典类型 CRUD、数据校验 |
| `SysDictDataServiceTest` | 12 | 字典数据 CRUD、类型关联 |
| `DictionaryServiceTest` | 10 | 字典管理综合逻辑 |
| `SysConfigServiceTest` | 8 | 配置参数校验、默认值 |
| `SysLoginLogServiceTest` | 10 | 登录日志记录、统计 |
| `SysExceptionLogServiceTest` | 8 | 异常日志记录、堆栈截断 |
| `OperationLogServiceTest` | 7 | 操作日志切面逻辑 |
| `AuditLogServiceTest` | 5 | 审计日志持久化、DTO转换 |
#### Domain / Primitive / DTO(值对象校验,共 180 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `SysUserTest` | 23 | 用户领域模型验证(字段约束、状态转换) |
| `UsernameTest` | 15 | 用户名格式校验(长度、字符集、特殊字符) |
| `PasswordTest` | 45 | 密码强度规则、加密格式、哈希验证 |
| `PasswordDetailedTest` | 40 | 密码复杂性详细规则(大小写、数字、特殊字符) |
| `EmailTest` | 18 | 邮箱格式校验(RFC标准、中文邮箱) |
| `SysUserQueryTest` | 8 | 用户查询对象(分页、排序、筛选条件) |
| `SysRoleQueryTest` | 6 | 角色查询对象 |
| `CreateUserCommandTest` | 10 | 创建用户命令校验 |
| `UpdateUserCommandTest` | 8 | 更新用户命令校验 |
| `CreateRoleCommandTest` | 7 | 创建角色命令校验 |
| `UserResponseTest` | 5 | 用户响应 DTO |
| `AuthResponseTest` | 3 | 认证响应 DTO |
| `FilePreviewResponseTest` | 3 | 文件预览响应 DTO |
| `AuditLogTest` | 6 | 审计日志领域模型 |
| `AuditLogQueryRequestTest` | 5 | 审计查询请求校验 |
#### 安全 / 过滤器(共 52 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `JwtTokenProviderTest` | 20 | JWT 生成/解析/过期/签名验证/刷新 |
| `JwtAuthenticationFilterTest` | 15 | 认证过滤器(Token提取、路径白名单、401响应) |
| `RateLimitFilterTest` | 12 | 限流过滤器(IP限制、令牌桶、滑动窗口) |
| `SecurityConfigTest` | 5 | Spring Security 配置验证 |
#### 工具类 / 辅助(共 20 tests
| 测试类 | 用例数 |
|---|---|
| `IpUtilsTest` | 12 |
| `UserAgentParserTest` | 8 |
#### 回归测试(共 37 tests
| 测试类 | 用例数 | 测试场景 |
|---|---|---|
| `SystemConfigRegressionTest` | 37 | 边界条件、并发操作、SQL注入防护、大菜单性能、事务回滚 |
---
### 2.2 manage-gateway(网关)— 171 tests
微服务网关,负责 JWT 认证、RBAC 授权、签名验证、限流、熔断、路由、负载均衡。
#### 过滤器(共 65 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `GatewayJwtAuthenticationFilterTest` | 13 | JWT 解析:有效Token放行、无Token→401、无效Token→401、过期Token→401、公开路径放行 |
| `RbacAuthorizationFilterTest` | 13 | RBAC 授权:管理员全路径、普通用户受限、多 HTTP 方法、权限继承 |
| `SignatureFilterTest` | 9 | 请求签名:生成/验证/过期/篡改检测/重放防护 |
| `ResilienceFilterTest` | 7 | 弹性策略:超时、重试、熔断半开状态 |
| `RateLimitFilterTest` | 12 | 限流:IP维度、用户维度、令牌桶算法、并发控制 |
| `CompressionFilterTest` | 11 | 响应压缩:gzip、brotli、大小阈值 |
#### 服务层(共 55 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `SignatureServiceImplTest` | 12 | 签名服务实现 |
| `PermissionServiceImplTest` | 10 | 权限校验服务 |
| `JwtKeyServiceImplTest` | 8 | JWT 密钥管理 |
| `DynamicRouteServiceTest` | 8 | 动态路由加载/更新/删除 |
| `RequestCacheServiceTest` | 5 | 请求缓存 |
| `AuditLogServiceTest` | 7 | 网关审计日志 |
| `CustomLoadBalancerTest` | 5 | 自定义负载均衡 |
#### 集成测试(共 6 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `RbacIntegrationTest` | 6 | `/api/admin/users`→403 拦截,`/api/users/profile`→放行 |
#### 监控 / 指标(共 30 tests
| 测试类 | 用例数 |
|---|---|
| `GatewayMetricsTest` | 12 |
| `PerformanceMonitorTest` | 8 |
| `GatewayHealthIndicatorTest` | 5 |
| `ResilienceConfigTest` | 5 |
---
### 2.3 manage-db(数据库)— 72 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `QueryUtilTest` | 8 | 动态 SQL 构建(等值、范围、IN、LIKE、排序) |
| `QueryUtilOrTest` | 6 | OR 条件组合查询 |
| `QueryUtilDetailedTest` | 8 | 嵌套查询、子查询 |
| `SysUserConverterTest` | 5 | PO ↔ VO 转换 |
| `SysRoleConverterTest` | 5 | 角色转换 |
| `SysMenuConverterTest` | 5 | 菜单转换 |
| `SysLoginLogConverterTest` | 5 | 登录日志转换 |
| `SysExceptionLogConverterTest` | 5 | 异常日志转换 |
| `SysDictTypeConverterTest` | 5 | 字典类型转换 |
| `SysDictDataConverterTest` | 5 | 字典数据转换 |
| `SysConfigConverterTest` | 5 | 配置转换 |
| `OperationLogConverterTest` | 5 | 操作日志转换 |
| `DictionaryConverterTest` | 5 | 字典转换 |
---
### 2.4 manage-common(通用工具)— 62 tests
覆盖 Redis、签名、JWT、加密、序列化等公共工具类。
---
### 2.5 manage-notify(通知公告)— 21 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `SysNoticeHandlerTest` | 12 | 公告 CRUD、发布/撤回、分页 |
| `SysWebSocketHandlerTest` | 9 | WebSocket 连接、消息推送、广播/单播 |
---
### 2.6 manage-file(文件管理)— 17 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `SysFileHandlerTest` | 9 | 文件 CRUD、下载、预览 |
| `SysFileServiceTest` | 8 | 文件存储、路径生成、MIME 检测 |
---
### 2.7 manage-app(管理端)— 22 tests
| 测试类 | 用例数 | 类型 | 说明 |
|---|---|---|---|
| `RateLimitConfigTest` | 2 | 单元 | 限流配置验证 |
| `MultipartConfigTest` | 2 | 单元 | 文件上传配置 |
| `ManualTableCreationTest` | 1 | 集成 | 手动建表验证 |
| `DatabaseInitTest` | 5 | 集成 | 数据库初始化 |
| `SysUserServiceIntegrationTest` | 5 | 集成 | 用户服务集成 |
| `OperationLogIntegrationTest` | 4 | 集成 | 操作日志集成 |
| `OperationLogExportIntegrationTest` | 3 | 集成 | 日志导出 |
> 注:15 个集成测试需数据库连接,标记为 SKIP(跳过 17 个含 setup 方法)
---
### 2.8 gym-member(会员管理)✨ 新增 — 40 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `MemberCardStateMachineTest` | 18 | 状态机全路径:ACTIVE/USED_UP/EXPIRED/REFUNDED × 6 事件、非法转换拦截、`canTransition`/`validateTransition` |
| `MemberNoGeneratorTest` | 15 | GYM前缀格式、8位合法字符集、不重复性验证、不含易混淆字符(0/O/1/I/l)、批量生成唯一性、count=0边界 |
| `BeanConvertUtilTest` | 7 | 正常转换、部分字段、null输入→null、批量转换、空列表、单元素 |
#### 状态机测试覆盖表
| 状态 → 事件 | USE | RENEW | EXPIRE | REFUND | DISABLE | ACTIVATE |
|---|---|---|---|---|---|---|
| ACTIVE | ACTIVE ✅ | ACTIVE ✅ | EXPIRED ✅ | REFUNDED ✅ | 非法 ❌ | - |
| USED_UP | 非法 ❌ | ACTIVE ✅ | - | REFUNDED ✅ | - | - |
| EXPIRED | 非法 ❌ | ACTIVE ✅ | - | - | - | - |
| REFUNDED (终态) | 非法 ❌ | 非法 ❌ | 非法 ❌ | 非法 ❌ | 非法 ❌ | 非法 ❌ |
---
### 2.9 gym-auth(手机号认证)✨ 新增 — 10 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `PhoneAuthHandlerTest` | 5 | 一键登录正常返回、发送验证码成功/频率限制、验证码登录成功/错误异常传播 |
| `SmsServiceImplTest` | 5 | 60秒频率限制、首次发送、Redis缓存获取/不存在、配置属性验证 |
#### 涉及 API
| 端点 | 方法 | Handler |
|---|---|---|
| `/api/auth/one-click-login` | POST | `PhoneAuthHandler.oneClickLogin` |
| `/api/auth/send-sms-code` | POST | `PhoneAuthHandler.sendSmsCode` |
| `/api/auth/code-login` | POST | `PhoneAuthHandler.codeLogin` |
---
### 2.10 gym-dataCount(数据统计)✨ 新增 — 8 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `DataStatisticsHandlerTest` | 8 | 综合/会员/预约/签到统计正常返回、异常降级空结果、历史查询、导出Excel正常+异常降级 |
#### 涉及 API
| 端点 | 测试场景 |
|---|---|
| `GET /api/statistics/summary` | MemberStatistics + BookingStatistics + SignInStatistics 聚合 |
| `GET /api/statistics/member` | 新增/活跃/累计/签到/预约/取消会员 |
| `GET /api/statistics/booking` | 新增/取消/出席/缺席/出席率/取消率 |
| `GET /api/statistics/signin` | 总数/成功/失败/成功率/扫码/手动/人脸 |
| `GET /api/statistics/history` | 历史统计列表 |
| `GET /api/statistics/export` | Excel 导出(4 Sheet |
---
### 2.11 gym-checkIn(签到)— 10 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `CheckInModuleTest` | 10 | 二维码生成/有效性校验、签到成功/失败(无效二维码/不存在)、记录查询/单条/不存在、统计/每日统计、导出 |
#### 涉及 API
| 端点 | 方法 |
|---|---|
| `/api/checkin/qrcode` | GET |
| `/api/checkin` | POST |
| `/api/checkin/records` | GET |
| `/api/checkin/records/{id}` | GET |
| `/api/checkin/stats` | GET |
| `/api/checkin/stats/daily` | GET |
| `/api/checkin/records/export` | GET |
---
### 2.12 gym-groupCourse(团课)— 3 tests
| 测试类 | 用例数 | 测试内容 |
|---|---|---|
| `QRCodeUtilTest` | 3 | QR 码生成、内容编码/解码、边界尺寸 |
---
### 2.13 无测试模块
| 模块 | 状态 | 原因 |
|---|---|---|
| gym-payment | 0 tests | 模块未编写测试 |
| manage-audit | 0 tests | 模块未编写测试 |
---
## 三、完整的 API 路由覆盖汇总
| 分类 | API 路由 | 测试数 | 覆盖层 |
|---|---|---|---|
| 认证 | `POST /api/auth/login`, `/register`, `/logout` | 9 | Handler |
| 认证 | `POST /api/auth/one-click-login`, `/send-sms-code`, `/code-login` | 5 | Handler |
| 用户 | `GET/POST /api/users`, `GET/PUT/DEL /api/users/{id}`, `/page`, `/batch` | 20 | Handler |
| 角色 | `GET/POST /api/roles`, `GET/DEL /api/roles/{id}`, `/page` | 16 | Handler |
| 菜单 | `GET/POST /api/menus`, `GET /api/menus/{id}`, `/tree`, `/parent/{id}` | 24 | Handler |
| 字典 | `GET/POST /api/dict-types`, `GET/POST /api/dict-data` | 26 | Handler |
| 配置 | `GET/POST /api/configs`, `GET /api/configs/{id}`, `/key/{key}` | 9 | Handler |
| 文件 | `GET/POST /api/files`, `GET/DEL /api/files/{id}`, `/download`, `/preview` | 17 | Handler+Service |
| 通知 | `GET/POST /api/notices`, `GET/PUT/DEL /api/notices/{id}` | 21 | Handler |
| 操作日志 | `GET /api/operation-logs`, `/page`, `/export` | 7 | Handler+集成 |
| 登录日志 | `GET /api/logs/login` | 18 | Handler |
| 审计日志 | `GET /api/audit-logs/*` | 11 | Handler |
| 签到 | `GET /api/checkin/qrcode`, `POST /api/checkin`, `GET /...{id}`, `/stats`, `/export` | 10 | Handler |
| 统计 | `GET /api/statistics/summary`, `/member`, `/booking`, `/signin`, `/history`, `/export` | 8 | Handler |
| 统计 | `GET /api/stats/overview` | 1 | Handler |
| 网关 | JWT/RBAC/签名/限流/熔断/路由(非HTTP端点) | 171 | Filter+Service |
---
## 四、运行方式
```bash
# 进入后端目录
cd gym-manage-api
# 运行全量测试
mvn test -DfailIfNoTests=false
# 运行单个模块
mvn test -pl gym-member -DfailIfNoTests=false
# 运行单个测试类
mvn test -pl gym-member "-Dtest=cn.novalon.gym.manage.member.handler.MemberCardStateMachineTest"
# 编译但不运行测试
mvn compile -DskipTests
```
---
## 五、测试架构
```
测试层级:
Handler → Mock Service → 验证 HTTP 状态码 + 响应体
Service → Mock Repository → 验证业务逻辑 + 事务
Filter → Mock Exchange → 验证过滤规则 + 异常处理
Util → 纯单元测试 → 验证输入输出 + 边界
Domain → 值对象测试 → 验证构造/校验/不变性
Converter→ Mock 源对象 → 验证字段映射完整
Integration → 真实 DB/H2 → 端到端业务流程
```
---
**文档生成时间**: 2026-07-21 | **测试工具**: JUnit 5 + Mockito + Reactor Test + Maven
-312
View File
@@ -1,312 +0,0 @@
# 小程序端 — 测试文档
> **位置**: `gym-manage-uniapp/e2e/` | **框架**: Jest + miniprogram-automator | **用例数**: 7 | **通过率**: 100%
---
## 一、概览
小程序端 E2E 测试基于 **miniprogram-automator**(微信官方自动化工具),在微信开发者工具中运行,模拟用户操作并验证页面行为。
| 维度 | 值 |
|---|---|
| 测试框架 | Jest 29 + miniprogram-automator |
| 目标环境 | 微信小程序(微信开发者工具) |
| 测试文件数 | 1 配置文件 + 3 测试套件 + 5 Page Object + 2 辅助 |
| 测试用例数 | 7 |
| 通过率 | 100% |
| 运行命令 | `npx jest --config e2e/jest.config.js` |
---
## 二、测试套件详览
### 2.1 冒烟测试 — `smoke/app-launch.spec.js`2 用例)
验证小程序基础启动和导航功能。
| 用例 | 测试内容 |
|---|---|
| 首页加载与基本内容显示 | 验证小程序正常启动、首页数据加载、关键元素渲染 |
| 四个 TabBar 页面导航 | 依次切换到:首页 → 搜索 → 我的课程 → 个人中心 → 返回首页,验证每个页面正确跳转 |
### 2.2 团课预约旅程 — `journeys/booking-journey.spec.js`3 用例)
验证从首页到团课预约再到扫码签到的完整流程。
| 用例 | 测试步骤 |
|---|---|
| 首页课程元素展示 | 首页加载 → 课程卡片渲染 → 验证推荐课程数据 |
| 搜索页搜索功能 | 切换到搜索页 → 输入"瑜伽"关键词 → 验证搜索结果绑定 |
| **预约「流瑜伽」并扫码签到** ✨ | 进入我的课程页 → 注入「流瑜伽」(id:2) 预约数据 → Mock `wx.scanCode` → 点击扫码签到按钮 → 验证签到流程完成 |
#### 核心流程:预约+扫码签到详细步骤
```
步骤 1: 进入「我的课程」页面(TabBar 导航)
↓ 使用 miniProgram.switchTab('/pages/my-courses/my-courses')
验证: page.path 包含 'my-courses'
步骤 2: 注入模拟预约数据
↓ 使用 miniProgram.evaluate() 注入 bookings 数据
数据: { id: 100, courseId: 2, courseName: '流瑜伽',
location: 'A馆 · 瑜伽厅', statusValue: 0, canCancel: true }
验证: pageData.bookings.length > 0
步骤 3: Mock 扫码并签到
↓ 使用 miniProgram.mockWxMethod('scanCode', { result: QR_CONTENT })
点击 MyCoursesPage.scanSignIn('流瑜伽')
验证: 签到按钮点击成功,页面未崩溃
```
> **核心实现**:
> - **测试课程**: 流瑜伽(`courseId: 2`
> - **二维码内容**: `COURSE_QR_2`(模拟 `fl.png` 扫码结果)
> - **绕过 API 依赖**: 使用 `evaluate()` 直接注入页面数据,无需后端服务运行
> - **Mock 微信 API**: 使用 `mockWxMethod('scanCode')` 模拟扫码返回
### 2.3 个人中心旅程 — `journeys/profile-journey.spec.js`2 用例)
| 用例 | 测试内容 |
|---|---|
| 「我的课程」页面数据 | 切换到我的课程页 → 验证页面数据加载 |
| 「个人中心」会员信息 | 切换到个人中心 → 验证昵称、会员号、签到天数等展示 |
---
## 三、Page Object 模式(5 个文件)
| 文件 | 对应页面 | 核心方法 |
|---|---|---|
| `HomePage.js` | 首页 (`pages/index/index`) | `goto()`, `getPageData()`, `clickCourseCard(index)`, `switchTab()` |
| `CourseDetailPage.js` | 课程详情 (`pages/course-detail/course-detail`) | `getPageData()`, `clickBook()` |
| `MyCoursesPage.js` | 我的课程 (`pages/my-courses/my-courses`) | `getPageData()`, `scanSignIn(courseName)` |
| `ProfilePage.js` | 个人中心 (`pages/profile/profile`) | `getPageData()`, `getMemberInfo()` |
| `SearchPage.js` | 搜索 (`pages/search/search`) | `getPageData()`, `search(keyword)` |
### Page Object 核心实现细节
#### `HomePage.clickCourseCard(index)`
```javascript
// 支持 .recommend-card、.course-card、.course-item 等多选择器
async clickCourseCard(index = 0) {
const page = await this.mp.currentPage();
const cards = await page.$$('.recommend-card, .course-card, .course-item, [class*="course"]');
if (cards.length > index) { await cards[index].tap(); }
}
```
#### `CourseDetailPage.clickBook()`
```javascript
// 精准定位 .booking-btn 并检查禁用状态
async clickBook() {
const page = await this.mp.currentPage();
const bookBtn = await page.$('.booking-btn');
if (bookBtn) {
const disabled = await bookBtn.attribute('disabled');
if (disabled === 'true' || disabled === 'disabled') return false;
await bookBtn.tap();
return true;
}
return false;
}
```
#### `MyCoursesPage.scanSignIn(courseName)`
```javascript
// 通过 page.data() 按索引匹配 DOM 卡片,精准定位扫码签到按钮
async scanSignIn(courseName) {
const page = await this.mp.currentPage();
// 1. 通过 page data 匹配目标课程索引
const pageData = await page.data();
const targetBooking = (pageData.bookings || []).find(b => b.courseName === courseName);
const targetIndex = pageData.bookings.indexOf(targetBooking);
// 2. 通过索引定位 DOM 卡片
const cards = await page.$$('.booking-card');
if (cards.length > targetIndex) {
const signBtn = await cards[targetIndex].$('.signin-btn');
if (signBtn) { await signBtn.tap(); return true; }
}
// 3. 回退:wxml 文本匹配
// ...
}
```
---
## 四、测试覆盖的小程序页面路由
| 页面 | 路由 | TabBar | 测试内容 |
|---|---|---|---|
| **首页** | `pages/index/index` | ✅ 是 | 渲染、课程卡片(`.recommend-card`)、轮播图、今日推荐、数据获取 |
| **搜索** | `pages/search/search` | ✅ 是 | 关键词搜索"瑜伽"、输入绑定 |
| **我的课程** | `pages/my-courses/my-courses` | ✅ 是 | 预约数据注入(`evaluate`)、扫码签到按钮(`.signin-btn` |
| **个人中心** | `pages/profile/profile` | ✅ 是 | 会员信息(昵称/头像/签到天数/待上课)、退出登录 |
| **课程详情** | `pages/course-detail/course-detail` | ❌ 否 | 从首页跳转、预约按钮(`.booking-btn` |
---
## 五、配置与辅助文件
### Jest 配置 — `e2e/jest.config.js`
```javascript
{
testTimeout: 120000, // 测试超时 120 秒
globalSetup: '<rootDir>/e2e/globalSetup.js',
setupFilesAfterFramework: ['<rootDir>/e2e/setup.js'],
projects: [
{ displayName: 'smoke', testMatch: ['**/smoke/**'] },
{ displayName: 'journeys', testMatch: ['**/journeys/**'] }
]
}
```
### 全局初始化 — `e2e/globalSetup.js`
启动微信开发者工具 CLI,打开小程序项目并建立 WebSocket 连接:
```javascript
module.exports = async () => {
const automator = require('miniprogram-automator');
// 连接或启动微信开发者工具
const miniProgram = await automator.launch({
projectPath: path.resolve(__dirname, '..'),
});
// 存储到全局,供测试使用
global.__MINIPROGRAM__ = miniProgram;
};
```
### 测试设置 — `e2e/setup.js`
每个测试文件执行前的通用设置:
```javascript
beforeAll(async () => {
miniProgram = global.__MINIPROGRAM__;
// Mock 常用微信 API
await miniProgram.mockWxMethod('showToast', {});
await miniProgram.mockWxMethod('showModal', { confirm: true });
});
```
---
## 六、测试数据
### 预约测试数据(注入到我的课程页)
```javascript
{
bookings: [{
id: 100,
courseId: 2, // 流瑜伽
courseName: '流瑜伽',
location: 'A馆 · 瑜伽厅',
fullDate: '2026-07-21',
shortTime: '10:00',
endShortTime: '11:00',
bookingTime: '2026-07-20 15:30',
statusValue: 0,
statusLabel: '已预约',
checkedIn: false,
canCancel: true
}]
}
```
### 签到测试数据(Mock wx.scanCode
```javascript
{
result: 'COURSE_QR_2', // 流瑜伽的二维码内容(模拟 fl.png)
scanType: 'QR_CODE',
charSet: 'UTF-8',
errMsg: 'scanCode:ok'
}
```
### 二维码文件
- 路径: `d:\Work\BIG_project\week2\base13-small-uniapp\gym-manage\fl.png`
- 用途: 测试指定的团课「流瑜伽」二维码
---
## 七、环境依赖
| 依赖 | 版本 | 用途 |
|---|---|---|
| miniprogram-automator | ^0.10.x | 微信小程序自动化驱动 |
| Jest | 29.x | 测试运行器 |
| 微信开发者工具 | 稳定版 | 小程序运行载体 |
### 安装
```bash
# 安装测试依赖
npm install -D jest miniprogram-automator
# 或者
npx @wechat-miniprogram/automator-cli install
```
---
## 八、运行方式
### 前置条件
1. 安装**微信开发者工具**(稳定版)
2. 在开发者工具中打开 `gym-manage-uniapp` 项目
3. 开启**服务端口**(设置 → 安全 → 服务端口:打开)
4. 在 HbuilderX 中编译小程序:发行 → 小程序-微信
### 运行命令
```bash
# 进入小程序目录
cd gym-manage-uniapp
# 冒烟测试
npx jest --config e2e/jest.config.js --testPathPattern="smoke"
# 团课预约旅程
npx jest --config e2e/jest.config.js --testPathPattern="booking-journey"
# 个人中心旅程
npx jest --config e2e/jest.config.js --testPathPattern="profile-journey"
# 所有测试
npx jest --config e2e/jest.config.js
# 详细输出
npx jest --config e2e/jest.config.js --verbose --forceExit
```
---
## 九、关键设计决策
### 为什么不直接调用后端 API?
小程序的 `onLoad()` 在页面加载时自动调用后端 API 获取数据。但在测试环境中:
- 后端服务可能未运行
- API 响应可能不稳定
因此采用 **页面数据注入** (`evaluate()`) 策略,直接将预置数据注入到页面 `data` 中,绕过 API 依赖,专注于验证 UI 交互和业务流程。
### 为什么 Mock wx.scanCode
微信小程序的 `wx.scanCode()` 调用真机摄像头,无法在自动化测试中真实触发。使用 `mockWxMethod()` 模拟返回二维码内容,验证签到按钮点击后的逻辑链路。
### 索引匹配 vs wxml 匹配
`scanSignIn()` 通过 `wxml()` 方法获取 DOM 文本进行匹配,但在 UniApp 项目中 `wxml()` 可能不包含渲染后的文本内容。优化后先通过 `page.data()` 获取数据中的对应索引,再通过索引定位 DOM 元素,大幅提高测试稳定性。
---
**文档生成时间**: 2026-07-21 | **测试工具**: Jest 29 + miniprogram-automator + 微信开发者工具
-298
View File
@@ -1,298 +0,0 @@
# Web 后台管理系统 — 测试文档
> **位置**: `gym-manage-web/` | **框架**: Vitest + Playwright | **用例数**: 185+ (单元 171 + E2E 14+) | **通过率**: 100%
---
## 一、概览
Web 后台管理系统有两层测试体系:
| 测试类型 | 框架 | 用例数 | 通过率 | 运行命令 |
|---|---|---|---|---|
| **单元测试** | Vitest + jsdom | 171 | 100% | `npm run test` |
| **E2E 测试** | Playwright | 24+(按需指定)| 100% | `npm run test:e2e` |
---
## 二、Vitest 单元测试(24 文件,171 用例)
### 2.1 组件测试(13 文件,141 用例)
覆盖所有管理页面的 Vue 组件渲染和行为。
| 测试文件 | 用例数 | 测试的 Vue 组件 |
|---|---|---|
| `Login.test.ts` | 12 | 登录表单(用户名/密码输入、提交、错误提示、记住我) |
| `Dashboard.test.ts` | 10 | 仪表盘(统计卡片、数据加载、模块渲染) |
| `UserManagement.test.ts` | 15 | 用户管理(列表渲染、搜索、新增/编辑对话框、角色分配、删除确认) |
| `RoleManagement.test.ts` | 12 | 角色管理(列表、权限树、菜单分配、状态切换) |
| `MenuManagement.test.ts` | 14 | 菜单管理(树形表格、新增/编辑、图标选择、排序) |
| `DictManagement.test.ts` | 12 | 字典管理(类型+数据 Tab切换、新增、编辑、删除) |
| `ConfigManagement.test.ts` | 10 | 参数配置(列表、新增、编辑、key 唯一性) |
| `NoticeManagement.test.ts` | 10 | 通知公告(发布、撤回、富文本编辑) |
| `FileManagement.test.ts` | 8 | 文件管理(上传、下载、预览、删除、类型过滤) |
| `OperationLog.test.ts` | 8 | 操作日志(列表、筛选、详情查看) |
| `LoginLog.test.ts` | 8 | 登录日志(列表、状态筛选、时间范围) |
| `ExceptionLog.test.ts` | 7 | 异常日志(列表、堆栈展开、级别过滤) |
| `MenuItem.test.ts` | 5 | 菜单项渲染、路由跳转、权限隐藏 |
### 2.2 状态管理(1 文件,10 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `permission.test.ts` | 10 | Pinia Permission Store`setPermissions`/`clearPermissions``hasRole`/`hasPermission`、空权限处理、管理员特殊处理 |
### 2.3 指令(1 文件,5 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `permission.test.ts` | 5 | `v-permission` 指令:角色检查、权限检查、数组参数、无权限隐藏/禁用 |
### 2.4 路由守卫(1 文件,5 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `permission.guard.test.ts` | 5 | 未登录 → 重定向 `/login`、已登录访问 `/login` → 重定向 `/dashboard`、Token过期处理、白名单路径、动态路由加载 |
### 2.5 基于角色的测试(3 文件,15 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `admin.role.test.ts` | 6 | 管理员角色:全权限、全菜单、无限制操作 |
| `base.role.test.ts` | 5 | 基础角色:受限菜单、操作按钮隐藏 |
| `role-factory.test.ts` | 4 | 角色工厂:动态创建测试角色、权限组合 |
### 2.6 角色测试辅助(3 文件,13 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `test-data-manager.test.ts` | 5 | 测试数据生成器(用户、角色、菜单) |
| `role-auth-manager.test.ts` | 4 | 角色认证管理器 |
| `permission-helper.test.ts` | 4 | 权限辅助工具 |
### 2.7 工具函数(1 文件,6 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `errorHandler.test.ts` | 6 | 统一错误处理:网络错误、401 自动登出、403 提示、超时回调 |
### 2.8 配置验证(1 文件,2 用例)
| 测试文件 | 用例数 | 测试内容 |
|---|---|---|
| `config.test.ts` | 2 | Vitest 框架配置验证:基础断言、异步支持 |
### 2.9 Vitest 单元测试目录结构
```
src/__tests__/
├── components/ # 14 组件测试
│ ├── Login.test.ts
│ ├── Dashboard.test.ts
│ ├── UserManagement.test.ts
│ ├── RoleManagement.test.ts
│ ├── MenuManagement.test.ts
│ ├── MenuItem.test.ts
│ ├── DictManagement.test.ts
│ ├── ConfigManagement.test.ts
│ ├── NoticeManagement.test.ts
│ ├── FileManagement.test.ts
│ ├── OperationLog.test.ts
│ ├── LoginLog.test.ts
│ └── ExceptionLog.test.ts
├── stores/
│ └── permission.test.ts # Pinia Store
├── directives/
│ └── permission.test.ts # v-permission
├── router/
│ └── permission.guard.test.ts # 路由守卫
├── utils/
│ └── errorHandler.test.ts # 错误处理
├── config.test.ts # 框架验证
└── role-based-tests/ # 基于角色
├── roles/__tests__/
│ ├── admin.role.test.ts
│ ├── base.role.test.ts
│ └── role-factory.test.ts
└── shared/__tests__/
├── test-data-manager.test.ts
├── role-auth-manager.test.ts
└── permission-helper.test.ts
```
---
## 三、Playwright E2E 测试(24+ 用例)
### 3.1 测试体系
由 4 个项目组成,分别覆盖不同层级:
| 项目 | 目录 | 描述 | 用例数 |
|---|---|---|---|
| `setup` | `auth.setup.ts` | 认证 Token 预获取(全局前置) | 1 |
| `smoke` | `e2e/smoke/` | 基础冒烟测试 | 1 |
| `root` | `e2e/*.spec.ts` | 独立功能验证 | 7 |
| `journeys` | `e2e/journeys/` | 端到端旅程 | 16 |
| `debug` | `e2e/debug/` | 调试辅助 | 3 |
### 3.2 运行命令
```bash
npm run test:e2e # 全部项目
npm run test:e2e:smoke # 冒烟测试
npm run test:e2e:journeys # 旅程测试
npm run test:e2e:headed # 有头模式(可视化)
npm run test:e2e:debug # 调试模式(逐步执行)
npm run test:e2e:perf # 性能基准
```
### 3.3 配置参数
| 参数 | 值 | 说明 |
|---|---|---|
| baseURL | `http://localhost:3002` | Web 前端地址 |
| timeout | 120s | 测试超时 |
| expect.timeout | 30s | 断言超时 |
| actionTimeout | 30s | 操作超时 |
| navigationTimeout | 60s | 页面跳转超时 |
| retries | CI: 2, 本地: 1 | 失败重试次数 |
| workers | CI: 4, 本地: 50% | 并行 Worker 数 |
| headless | CI: true, 本地: false | 无头模式 |
| viewport | 1280×720 | 浏览器窗口 |
| locale | zh-CN | 语言 |
| slowMo | CI: 0, 本地: 100ms | 操作延迟 |
### 3.4 测试文件详情
#### 冒烟测试 (smoke/)
| 文件 | 用例数 | 测试内容 |
|---|---|---|
| `login-logout.spec.ts` | 1 | 管理员登录 → 导航验证 → 登出 |
#### 根级测试
| 文件 | 用例数 | 测试内容 |
|---|---|---|
| `api-connectivity.spec.ts` | 3 | 网关健康检查 `/actuator/health`、前端页面加载、数据库连接状态 |
| `auth-test.spec.ts` | 3 | JWT Token 获取/验证、未授权 401、登录 UI、权限验证 |
| `basic-ui-test.spec.ts` | 1 | 首页加载、登录页表单元素、导航栏、响应式 (375×667) |
| `unauthorized-redirect.spec.ts` | 1 | 未登录访问 `/members``/courses``/statistics` → 自动重定向 `/login` |
| `menu-management.spec.ts` | 1 | 登录 → 菜单管理 → 表格数据渲染 |
| `dict-management.spec.ts` | 1 | 登录 → 字典管理 → 类型+数据列表 |
| `config-management.spec.ts` | 1 | 登录 → 参数配置 → 列表显示 |
#### 旅程测试 (journeys/)
| 文件 | 用例数 | 业务链路 |
|---|---|---|
| `admin-complete-workflow.spec.ts` | 1 | 创建角色 → 分配权限 → 创建用户 → 绑定角色 → 验证权限 |
| `audit-workflow.spec.ts` | 1 | 导航审计日志 → 筛选条件 → 时间范围 → 详情查看 |
| `coach-banner-workflow.spec.ts` | 1 | 教练管理 → 轮播图管理 → 新增/编辑 |
| `config-workflow.spec.ts` | 1 | 参数配置 → 新增配置 → 编辑 → 删除 |
| `dict-workflow.spec.ts` | 1 | 字典类型创建 → 字典数据录入 → 编辑 → 删除 |
| `dictionary-complete-workflow.spec.ts` | 1 | 字典类型+数据完整增删改查流程 |
| `exception-log-workflow.spec.ts` | 1 | 异常日志查看 → 堆栈展开 → 级别筛选 |
| `extended-role-boundary.spec.ts` | 1 | 角色权限扩展 → 边界条件 → 多角色叠加 |
| `file-management-workflow.spec.ts` | 1 | 文件上传 → 列表查看 → 下载 → 预览 → 删除 |
| `groupcourse-workflow.spec.ts` | 1 | 课程类型 → 课程标签 → 课程推荐 → 团课管理 |
| `member-workflow.spec.ts` | 1 | 会员列表 → 会员卡管理 → 储值卡 → 退款申请 |
| `notice-workflow.spec.ts` | 1 | 创建公告 → 发布 → 查看 → 撤回 |
| `performance.spec.ts` | 1 | 首屏加载时间、路由切换性能、API 响应耗时 |
| `statistics-workflow.spec.ts` | 1 | 数据统计看板 → 会员统计 → 预约统计 → 签到统计 |
| `system-config-complete-workflow.spec.ts` | 1 | 系统配置完整增删改查 → 缓存刷新 → 验证生效 |
| `user-permission-boundary.spec.ts` | 1 | 普通用户权限边界 → 受限菜单 → 按钮隐藏 → 403 处理 |
---
## 四、Page Object 模式(11 个页面对象)
所有页面交互封装在 `e2e/pages/` 下:
| Page Object | 对应页面 | 核心方法 |
|---|---|---|
| `LoginPage.ts` | 登录 | `goto()`, `login(username, password)`, `getErrorMessage()` |
| `DashboardPage.ts` | 仪表盘 | `getStats()`, `navigateTo(menu)` |
| `UserManagementPage.ts` | 用户管理 | `searchUser()`, `addUser()`, `editUser()`, `deleteUser()` |
| `RoleManagementPage.ts` | 角色管理 | `addRole()`, `assignPermissions()`, `toggleStatus()` |
| `MenuManagementPage.ts` | 菜单管理 | `addMenu()`, `editMenu()`, `deleteMenu()`, `getTree()` |
| `DictionaryManagementPage.ts` | 字典管理 | `addType()`, `addData()`, `editData()`, `deleteData()` |
| `SystemConfigPage.ts` | 参数配置 | `addConfig()`, `editConfig()`, `deleteConfig()` |
| `NotificationPage.ts` | 通知公告 | `createNotice()`, `publish()`, `revoke()` |
| `FileManagementPage.ts` | 文件管理 | `uploadFile()`, `downloadFile()`, `previewFile()` |
| `OperationLogPage.ts` | 操作日志 | `filterByModule()`, `viewDetail()` |
| `LoginLogPage.ts` | 登录日志 | `filterByStatus()`, `filterByDate()` |
| `ExceptionLogPage.ts` | 异常日志 | `expandStack()`, `filterByLevel()` |
### 业务 Page Object6 个)
| Page Object | 用途 |
|---|---|
| `CoachManagementPage.ts` | 教练 CRUD |
| `BannerManagementPage.ts` | 轮播图管理 |
| `CourseTypeManagementPage.ts` | 课程类型管理 |
| `CourseLabelManagementPage.ts` | 课程标签管理 |
| `CourseRecommendManagementPage.ts` | 课程推荐管理 |
| `GroupCourseManagementPage.ts` | 团课管理 |
| `MemberManagementPage.ts` | 会员管理 |
| `MemberCardManagementPage.ts` | 会员卡管理 |
| `StatisticsDashboardPage.ts` | 统计看板 |
---
## 五、辅助模块
### Helpers
| 文件 | 用途 |
|---|---|
| `auth.ts` | 登录认证、Token 存储/获取/清除 |
| `TestStabilityHelper.ts` | 测试稳定性(重试、等待、超时处理) |
| `TestDataManager.ts` | 测试数据 CRUD 管理 |
### Utils
| 文件 | 用途 |
|---|---|
| `api-client.ts` | HTTP API 客户端封装 |
| `testHelper.ts` | 通用测试辅助函数 |
| `TestDataFactory.ts` | 测试数据工厂(用户/角色/菜单/字典生成) |
| `TestDataCleanup.ts` | 测试后数据清理 |
| `RetryHelper.ts` | 智能重试策略 |
| `testDataManager.ts` | 测试数据管理 |
### Fixtures
| 文件 | 用途 |
|---|---|
| `test-data.ts` | 静态测试数据(账号、权限、菜单结构) |
| `test-file.txt` | 文件上传测试用文件 |
---
## 六、运行方式
```bash
# 进入 Web 后台目录
cd gym-manage-web
# 单元测试
npm run test # 全量单元测试
npx vitest --run # 同全量
npx vitest --run Login # 运行匹配 "Login" 的测试
npx vitest --ui # Vitest UI 模式
# E2E 测试(需先启动后端和前端服务)
npm run test:e2e # 全部 Playwright 项目
npm run test:e2e:smoke # 仅冒烟
npm run test:e2e:journeys # 仅旅程
npm run test:e2e:headed # 可视化浏览器
npm run test:e2e:debug # 逐步执行
npm run test:e2e:perf # 性能基准
```
---
**文档生成时间**: 2026-07-21 | **测试工具**: Vitest + jsdom / Playwright + Chromium
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

@@ -1,139 +0,0 @@
package cn.novalon.gym.manage.auth.handler;
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
import cn.novalon.gym.manage.auth.dto.SendCodeRequest;
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
import cn.novalon.gym.manage.auth.vo.PhoneLoginVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/**
* 手机号认证 Handler 单元测试
*/
class PhoneAuthHandlerTest {
@Mock
private PhoneAuthService phoneAuthService;
private PhoneAuthHandler handler;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
handler = new PhoneAuthHandler(phoneAuthService);
}
@Test
@DisplayName("一键登录 - 正常返回登录信息")
void testOneClickLoginSuccess() {
PhoneLoginVO vo = PhoneLoginVO.builder()
.memberId(1L)
.memberNo("GYM001")
.phone("138****0001")
.accessToken("jwt-token-xxx")
.expiresIn(86400)
.isNewUser(true)
.build();
when(phoneAuthService.oneClickLogin(any(PhoneLoginDto.class)))
.thenReturn(Mono.just(vo));
Mono<ServerResponse> result = handler.oneClickLogin(
MockServerRequest.builder()
.body(Mono.just(new PhoneLoginDto())));
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("发送短信验证码 - 发送成功")
void testSendSmsCodeSuccess() {
when(phoneAuthService.sendSmsCode("13800000001"))
.thenReturn(Mono.just(true));
PhoneLoginDto dto = new PhoneLoginDto();
dto.setPhone("13800000001");
Mono<ServerResponse> result = handler.sendSmsCode(
MockServerRequest.builder()
.body(Mono.just(new SendCodeRequest("13800000001"))));
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("发送短信验证码 - 发送失败(60秒内重复发送)")
void testSendSmsCodeRateLimited() {
when(phoneAuthService.sendSmsCode("13800000001"))
.thenReturn(Mono.just(false));
Mono<ServerResponse> result = handler.sendSmsCode(
MockServerRequest.builder()
.body(Mono.just(new SendCodeRequest("13800000001"))));
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("验证码登录 - 正常登录")
void testCodeLoginSuccess() {
PhoneLoginVO vo = PhoneLoginVO.builder()
.memberId(2L)
.memberNo("GYM002")
.accessToken("jwt-token-yyy")
.expiresIn(86400)
.isNewUser(false)
.build();
when(phoneAuthService.codeLogin(any(PhoneCodeLoginDto.class)))
.thenReturn(Mono.just(vo));
PhoneCodeLoginDto loginDto = new PhoneCodeLoginDto();
loginDto.setPhone("13800000002");
loginDto.setCode("123456");
Mono<ServerResponse> result = handler.codeLogin(
MockServerRequest.builder()
.body(Mono.just(loginDto)));
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("验证码登录 - 验证码错误导致异常")
void testCodeLoginWrongCode() {
when(phoneAuthService.codeLogin(any(PhoneCodeLoginDto.class)))
.thenReturn(Mono.error(new RuntimeException("验证码错误")));
PhoneCodeLoginDto loginDto = new PhoneCodeLoginDto();
loginDto.setPhone("13800000002");
loginDto.setCode("000000");
Mono<ServerResponse> result = handler.codeLogin(
MockServerRequest.builder()
.body(Mono.just(loginDto)));
StepVerifier.create(result)
.expectError(RuntimeException.class)
.verify();
}
}
@@ -1,130 +0,0 @@
package cn.novalon.gym.manage.auth.service;
import cn.novalon.gym.manage.auth.config.SmsProperties;
import cn.novalon.gym.manage.auth.service.impl.SmsServiceImpl;
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
import cn.novalon.gym.manage.common.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* 短信服务单元测试
*/
class SmsServiceImplTest {
@Mock
private SmsProperties smsProperties;
@Mock
private RedisUtil redisUtil;
private ObjectMapper objectMapper;
private SmsServiceImpl smsService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
objectMapper = new ObjectMapper();
smsService = new SmsServiceImpl(smsProperties, redisUtil, objectMapper);
}
@Test
@DisplayName("发送验证码 - 频率限制内重复发送")
void testSendVerificationCodeRateLimited() {
String phone = "13800000001";
String rateLimitKey = RedisKeyConstants.SMS_CODE + phone + ":rate_limit";
// 最近60秒内已发送
long recentTime = System.currentTimeMillis() / 1000;
when(redisUtil.get(eq(rateLimitKey), eq(Long.class)))
.thenReturn(Mono.just(recentTime));
Mono<Boolean> result = smsService.sendVerificationCode(phone);
StepVerifier.create(result)
.expectNext(false)
.verifyComplete();
}
@Test
@DisplayName("发送验证码 - 首次发送(频率限制不触发)")
void testSendVerificationCodeFirstTime() {
String phone = "13800000002";
String rateLimitKey = RedisKeyConstants.SMS_CODE + phone + ":rate_limit";
// 从未发送过(返回 0,表示很久以前)
long oldTime = 0L;
when(redisUtil.get(eq(rateLimitKey), eq(Long.class)))
.thenReturn(Mono.just(oldTime));
// 由于会真实调用阿里云API(会失败),mock redis set
when(redisUtil.setWithExpire(anyString(), anyLong(), anyLong()))
.thenReturn(Mono.just(true));
Mono<Boolean> result = smsService.sendVerificationCode(phone);
// 阿里云API调用会失败,但逻辑上 rate limit 已通过
// 验证码逻辑在 Mono.fromCallable 内部,阿里云不可用时会返回 false
StepVerifier.create(result)
.consumeNextWith(success -> {
// 阿里云不可用时会返回 false
})
.verifyComplete();
}
@Test
@DisplayName("获取验证码 - 从Redis获取成功")
void testGetVerificationCodeFound() {
String phone = "13812345678";
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
when(redisUtil.get(eq(cacheKey), eq(String.class)))
.thenReturn(Mono.just("654321"));
Mono<String> result = smsService.getVerificationCode(phone);
StepVerifier.create(result)
.expectNext("654321")
.verifyComplete();
}
@Test
@DisplayName("获取验证码 - Redis中不存在")
void testGetVerificationCodeNotFound() {
String phone = "13800000000";
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
when(redisUtil.get(eq(cacheKey), eq(String.class)))
.thenReturn(Mono.empty());
Mono<String> result = smsService.getVerificationCode(phone);
StepVerifier.create(result)
.verifyComplete();
}
@Test
@DisplayName("短信配置属性验证")
void testSmsProperties() {
when(smsProperties.getSignName()).thenReturn("测试签名");
when(smsProperties.getTemplateCode()).thenReturn("SMS_001");
when(smsProperties.getCodeLength()).thenReturn(6);
when(smsProperties.getCodeExpireSeconds()).thenReturn(300L);
assert "测试签名".equals(smsProperties.getSignName());
assert "SMS_001".equals(smsProperties.getTemplateCode());
assert smsProperties.getCodeLength() == 6;
assert smsProperties.getCodeExpireSeconds() == 300L;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.novalon.gym.manage</groupId>
<artifactId>gym-manage-api</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>gym-coach</artifactId>
<packaging>jar</packaging>
<name>Gym Coach</name>
<description>Coach Management Module - Course Start/End, Violation Tracking</description>
<dependencies>
<dependency>
<groupId>cn.novalon.gym.manage</groupId>
<artifactId>manage-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cn.novalon.gym.manage</groupId>
<artifactId>manage-db</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cn.novalon.gym.manage</groupId>
<artifactId>manage-sys</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cn.novalon.gym.manage</groupId>
<artifactId>gym-groupCourse</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,15 @@
package cn.novalon.gym.manage.coach.dao;
import cn.novalon.gym.manage.coach.entity.CoachViolationEntity;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.stereotype.Repository;
/**
* 教练违规记录 DAO
*
* @author 张翔
* @date 2026-07-20
*/
@Repository
public interface CoachViolationDao extends R2dbcRepository<CoachViolationEntity, Long> {
}
@@ -0,0 +1,61 @@
package cn.novalon.gym.manage.coach.entity;
import cn.novalon.gym.manage.db.entity.BaseEntity;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import java.time.LocalDateTime;
/**
* 教练违规记录实体类 - 对应 coach_violation 表
*
* @author 张翔
* @date 2026-07-20
*/
@Table("coach_violation")
public class CoachViolationEntity extends BaseEntity {
@Column("coach_id")
private Long coachId;
@Column("course_id")
private Long courseId;
@Column("violation_time")
private LocalDateTime violationTime;
@Column("violation_reason")
private String violationReason;
public Long getCoachId() {
return coachId;
}
public void setCoachId(Long coachId) {
this.coachId = coachId;
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
public LocalDateTime getViolationTime() {
return violationTime;
}
public void setViolationTime(LocalDateTime violationTime) {
this.violationTime = violationTime;
}
public String getViolationReason() {
return violationReason;
}
public void setViolationReason(String violationReason) {
this.violationReason = violationReason;
}
}
@@ -0,0 +1,42 @@
package cn.novalon.gym.manage.coach.enums;
/**
* 团课预约状态枚举
*
* @author 张翔
* @date 2026-07-20
*/
public enum BookingStatus {
BOOKED("0", "已预约"),
CANCELLED("1", "已取消"),
ATTENDED("2", "已出席"),
ABSENT("3", "缺席"),
COACH_ABSENT("4", "教练缺席"),
LATE("5", "迟到");
private final String value;
private final String desc;
BookingStatus(String value, String desc) {
this.value = value;
this.desc = desc;
}
public String getValue() {
return value;
}
public String getDesc() {
return desc;
}
public static BookingStatus fromValue(String value) {
for (BookingStatus status : values()) {
if (status.value.equals(value)) {
return status;
}
}
return BOOKED;
}
}
@@ -0,0 +1,30 @@
package cn.novalon.gym.manage.coach.enums;
/**
* 教练违规原因枚举
*
* @author 张翔
* @date 2026-07-20
*/
public enum ViolationReason {
COACH_LATE("COACH_LATE", "教练迟到"),
COACH_ABSENT("COACH_ABSENT", "教练缺席"),
NOT_MANUAL_END("NOT_MANUAL_END", "教练未手动结课");
private final String value;
private final String desc;
ViolationReason(String value, String desc) {
this.value = value;
this.desc = desc;
}
public String getValue() {
return value;
}
public String getDesc() {
return desc;
}
}
@@ -0,0 +1,68 @@
package cn.novalon.gym.manage.coach.handler;
import cn.novalon.gym.manage.coach.service.CoachCourseService;
import cn.novalon.gym.manage.sys.util.AuthUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* 教练开课/结课处理器
*
* @author 张翔
* @date 2026-07-20
*/
@Component
@Tag(name = "教练开课结课", description = "教练开课与结课操作")
public class CoachCourseHandler {
private static final Logger logger = LoggerFactory.getLogger(CoachCourseHandler.class);
private final CoachCourseService coachCourseService;
private final AuthUtil authUtil;
public CoachCourseHandler(CoachCourseService coachCourseService, AuthUtil authUtil) {
this.coachCourseService = coachCourseService;
this.authUtil = authUtil;
}
@Operation(summary = "教练开课", description = "教练手动开课,记录实际开课时间,若超时则判定迟到")
public Mono<ServerResponse> startCourse(ServerRequest request) {
Long courseId = Long.valueOf(request.pathVariable("courseId"));
Long coachId = authUtil.getMemberIdOrThrow(request);
return coachCourseService.startCourse(courseId, coachId)
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
"message", "开课成功",
"status", result.getStatus(),
"actualStartTime", result.getActualStartTime() != null ? result.getActualStartTime().toString() : ""
)))
.onErrorResume(e -> {
logger.error("开课失败: {}", e.getMessage());
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
});
}
@Operation(summary = "教练结课", description = "教练手动结课,记录实际结课时间")
public Mono<ServerResponse> endCourse(ServerRequest request) {
Long courseId = Long.valueOf(request.pathVariable("courseId"));
Long coachId = authUtil.getMemberIdOrThrow(request);
return coachCourseService.endCourse(courseId, coachId)
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
"message", "结课成功",
"status", result.getStatus(),
"actualEndTime", result.getActualEndTime() != null ? result.getActualEndTime().toString() : ""
)))
.onErrorResume(e -> {
logger.error("结课失败: {}", e.getMessage());
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
});
}
}
@@ -1,6 +1,6 @@
package cn.novalon.gym.manage.app.handler;
package cn.novalon.gym.manage.coach.handler;
import cn.novalon.gym.manage.app.service.CoachService;
import cn.novalon.gym.manage.coach.service.CoachCourseService;
import cn.novalon.gym.manage.sys.core.domain.SysUser;
import cn.novalon.gym.manage.sys.dto.request.CoachCreateRequest;
import cn.novalon.gym.manage.sys.dto.request.CoachUpdateRequest;
@@ -20,7 +20,7 @@ import java.util.List;
import java.util.Map;
/**
* 教练处理器放在 manage-app 中避免模块循环依赖
* 教练管理处理器 manage-app 迁移至 gym-coach 模块
*
* @author 张翔
* @date 2026-07-19
@@ -30,18 +30,18 @@ import java.util.Map;
public class CoachHandler {
private static final Logger logger = LoggerFactory.getLogger(CoachHandler.class);
private final CoachService coachService;
private final CoachCourseService coachCourseService;
private final Validator validator;
public CoachHandler(CoachService coachService, Validator validator) {
this.coachService = coachService;
public CoachHandler(CoachCourseService coachCourseService, Validator validator) {
this.coachCourseService = coachCourseService;
this.validator = validator;
}
@Operation(summary = "获取所有教练", description = "获取系统中所有教练列表")
public Mono<ServerResponse> getAllCoaches(ServerRequest request) {
return ServerResponse.ok()
.body(coachService.getAllCoaches(), SysUser.class);
.body(coachCourseService.getAllCoaches(), SysUser.class);
}
@Operation(summary = "创建教练", description = "创建新教练(创建用户并分配教练角色)")
@@ -54,7 +54,7 @@ public class CoachHandler {
violations.forEach(v -> errors.put(v.getPropertyPath().toString(), v.getMessage()));
return ServerResponse.badRequest().bodyValue(errors);
}
return coachService.createCoach(
return coachCourseService.createCoach(
req.getUsername(), req.getPassword(),
req.getNickname(), req.getEmail(), req.getPhone())
.flatMap(user -> ServerResponse.status(HttpStatus.CREATED).bodyValue(user))
@@ -70,7 +70,7 @@ public class CoachHandler {
public Mono<ServerResponse> updateCoach(ServerRequest request) {
Long id = Long.valueOf(request.pathVariable("id"));
return request.bodyToMono(CoachUpdateRequest.class)
.flatMap(req -> coachService.updateCoach(id, req.getNickname(), req.getEmail(), req.getPhone())
.flatMap(req -> coachCourseService.updateCoach(id, req.getNickname(), req.getEmail(), req.getPhone())
.flatMap(user -> ServerResponse.ok().bodyValue(user))
.switchIfEmpty(ServerResponse.notFound().build())
.onErrorResume(e -> {
@@ -83,7 +83,7 @@ public class CoachHandler {
@Operation(summary = "禁用教练", description = "禁用教练账号,自动取消其所有非进行中的团课")
public Mono<ServerResponse> disableCoach(ServerRequest request) {
Long id = Long.valueOf(request.pathVariable("id"));
return coachService.disableCoach(id)
return coachCourseService.disableCoach(id)
.then(ServerResponse.ok().bodyValue(Map.of("message", "教练已禁用")))
.onErrorResume(e -> {
logger.error("禁用教练失败: {}", e.getMessage());
@@ -94,9 +94,25 @@ public class CoachHandler {
@Operation(summary = "获取教练的团课", description = "获取指定教练教授的所有团课")
public Mono<ServerResponse> getCoachCourses(ServerRequest request) {
Long id = Long.valueOf(request.pathVariable("id"));
return coachService.getCoachCourses(id)
return coachCourseService.getCoachCourses(id)
.collectList()
.flatMap(courses -> ServerResponse.ok().bodyValue(courses))
.switchIfEmpty(ServerResponse.ok().bodyValue(List.of()));
}
@Operation(summary = "获取教练违规次数统计", description = "获取所有教练的违规次数")
public Mono<ServerResponse> getViolationCounts(ServerRequest request) {
return coachCourseService.getViolationCounts()
.collectList()
.flatMap(counts -> ServerResponse.ok().bodyValue(counts));
}
@Operation(summary = "获取教练违规记录", description = "获取指定教练的违规记录")
public Mono<ServerResponse> getCoachViolations(ServerRequest request) {
Long id = Long.valueOf(request.pathVariable("id"));
return coachCourseService.getCoachViolations(id)
.collectList()
.flatMap(violations -> ServerResponse.ok().bodyValue(violations))
.switchIfEmpty(ServerResponse.ok().bodyValue(List.of()));
}
}
@@ -0,0 +1,178 @@
package cn.novalon.gym.manage.coach.scheduler;
import cn.novalon.gym.manage.coach.enums.ViolationReason;
import cn.novalon.gym.manage.common.util.RedisUtil;
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseBookingDao;
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
import cn.novalon.gym.manage.groupcourse.enums.CourseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* 教练课程定时调度器
*
* 功能:
* 1. 检查未手动开课的课程,超时标记为教练缺席(5)并记录违规
* 2. 检查未手动结课的课程,超时标记为自动结束(6)并记录违规
*
* @author 张翔
* @date 2026-07-20
*/
@Component
public class CoachCourseScheduler {
private static final Logger logger = LoggerFactory.getLogger(CoachCourseScheduler.class);
private static final long ONE_HOUR_MINUTES = 60;
private static final long END_GRACE_MINUTES = 10;
private final GroupCourseDao groupCourseDao;
private final GroupCourseBookingDao groupCourseBookingDao;
private final DatabaseClient databaseClient;
private final RedisUtil redisUtil;
public CoachCourseScheduler(GroupCourseDao groupCourseDao,
GroupCourseBookingDao groupCourseBookingDao,
DatabaseClient databaseClient,
RedisUtil redisUtil) {
this.groupCourseDao = groupCourseDao;
this.groupCourseBookingDao = groupCourseBookingDao;
this.databaseClient = databaseClient;
this.redisUtil = redisUtil;
}
/**
* 每分钟检查一次:
* - status=0(NORMAL) 的课程是否已过开课缺席阈值
* - status=3(IN_PROGRESS) 或 status=7(COACH_LATE) 的课程是否已过结课宽限期
*/
@Scheduled(fixedRate = 60000)
public void checkAndProcessCourses() {
logger.debug("教练课程调度器开始检查");
LocalDateTime now = LocalDateTime.now();
// 1. 检查未开课的课程
processAbsentCourses(now)
.subscribe(
count -> {
if (count > 0) {
logger.info("教练课程调度器:处理了 {} 门教练缺席课程", count);
invalidateCache();
}
},
error -> logger.error("教练课程调度器(缺席检查)执行失败:{}", error.getMessage(), error)
);
// 2. 检查未结课的课程
processAutoEndCourses(now)
.subscribe(
count -> {
if (count > 0) {
logger.info("教练课程调度器:处理了 {} 门自动结束课程", count);
invalidateCache();
}
},
error -> logger.error("教练课程调度器(自动结课)执行失败:{}", error.getMessage(), error)
);
}
/**
* 处理缺席课程:status=0 且已过开课缺席阈值
*/
private Mono<Long> processAbsentCourses(LocalDateTime now) {
return groupCourseDao.findByStatusAndStartTimeBefore(databaseClient, "0", now)
.filter(course -> isAbsentThresholdExceeded(course, now))
.flatMap(course -> markAsCoachAbsent(course, now))
.count();
}
/**
* 处理自动结课:status IN ('3','7') 且 end_time + 10分钟 已过
*/
private Mono<Long> processAutoEndCourses(LocalDateTime now) {
LocalDateTime endThreshold = now.minusMinutes(END_GRACE_MINUTES);
return groupCourseDao.findByStatusInAndEndTimeBefore(databaseClient,
new String[]{String.valueOf(CourseStatus.IN_PROGRESS.getValue()),
String.valueOf(CourseStatus.COACH_LATE.getValue())},
endThreshold)
.flatMap(course -> markAsAutoEnded(course, now))
.count();
}
/**
* 判断课程是否已过缺席阈值
*/
private boolean isAbsentThresholdExceeded(GroupCourseEntity course, LocalDateTime now) {
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
return minutesSinceStart > 30;
} else {
long thresholdB = Math.max(1, (long) (courseDurationMinutes * 0.25));
return minutesSinceStart > thresholdB;
}
}
/**
* 标记课程为教练缺席(5),更新预约记录为教练缺席(4),记录违规
*/
private Mono<GroupCourseEntity> markAsCoachAbsent(GroupCourseEntity course, LocalDateTime now) {
logger.info("课程 {} 教练缺席,标记为 COACH_ABSENT", course.getId());
return insertViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_ABSENT)
.then(groupCourseDao.updateToCoachAbsent(course.getId(), now, now))
.then(groupCourseBookingDao.updateStatusByCourseId(course.getId(), "0", "4"))
.thenReturn(course);
}
/**
* 标记课程为自动结束(6),记录违规
*/
private Mono<GroupCourseEntity> markAsAutoEnded(GroupCourseEntity course, LocalDateTime now) {
logger.info("课程 {} 未手动结课,标记为 AUTO_ENDED", course.getId());
return insertViolation(course.getCoachId(), course.getId(), now, ViolationReason.NOT_MANUAL_END)
.then(groupCourseDao.updateToAutoEnded(course.getId(), now, now))
.thenReturn(course);
}
/**
* 插入违规记录(使用 DatabaseClient 直连)
*/
private Mono<Void> insertViolation(Long coachId, Long courseId, LocalDateTime violationTime,
ViolationReason reason) {
return databaseClient.sql("""
INSERT INTO coach_violation (coach_id, course_id, violation_time, violation_reason, created_at, updated_at)
VALUES (:coachId, :courseId, :violationTime, :reason, :now, :now)
""")
.bind("coachId", coachId)
.bind("courseId", courseId)
.bind("violationTime", violationTime)
.bind("reason", reason.getValue())
.bind("now", LocalDateTime.now())
.then();
}
/**
* 清除统计缓存和团课缓存 —— 调度器触发时,如有课程状态变更则必须及时失效
*/
private void invalidateCache() {
redisUtil.deleteByPattern("datacount:statistics:*").subscribe(
deleted -> logger.debug("调度器清除统计缓存,已删除 {} 条", deleted),
error -> logger.warn("调度器清除统计缓存失败: {}", error.getMessage())
);
redisUtil.deleteByPattern("group_course:*").subscribe(
deleted -> logger.debug("调度器清除团课缓存,已删除 {} 条", deleted),
error -> logger.warn("调度器清除团课缓存失败: {}", error.getMessage())
);
}
}
@@ -0,0 +1,357 @@
package cn.novalon.gym.manage.coach.service;
import cn.novalon.gym.manage.coach.dao.CoachViolationDao;
import cn.novalon.gym.manage.coach.entity.CoachViolationEntity;
import cn.novalon.gym.manage.coach.enums.ViolationReason;
import cn.novalon.gym.manage.common.util.RedisUtil;
import cn.novalon.gym.manage.common.util.StatusConstants;
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseBookingDao;
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
import cn.novalon.gym.manage.groupcourse.enums.CourseStatus;
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
import cn.novalon.gym.manage.sys.core.domain.SysRole;
import cn.novalon.gym.manage.sys.core.domain.SysUser;
import cn.novalon.gym.manage.sys.core.domain.UserRole;
import cn.novalon.gym.manage.sys.core.repository.ISysRoleRepository;
import cn.novalon.gym.manage.sys.core.repository.ISysUserRepository;
import cn.novalon.gym.manage.sys.core.repository.IUserRoleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
/**
* 教练课程服务(含教练管理 + 开课/结课逻辑 + 违规记录)
*
* @author 张翔
* @date 2026-07-20
*/
@Service
public class CoachCourseService {
private static final Logger logger = LoggerFactory.getLogger(CoachCourseService.class);
private static final String COACH_ROLE_NAME = "教练";
private static final long ONE_HOUR_MINUTES = 60;
private final ISysUserRepository userRepository;
private final ISysRoleRepository roleRepository;
private final IUserRoleRepository userRoleRepository;
private final IGroupCourseRepository groupCourseRepository;
private final IGroupCourseBookingRepository bookingRepository;
private final GroupCourseDao groupCourseDao;
private final GroupCourseBookingDao groupCourseBookingDao;
private final CoachViolationDao violationDao;
private final DatabaseClient databaseClient;
private final PasswordEncoder passwordEncoder;
private final RedisUtil redisUtil;
public CoachCourseService(ISysUserRepository userRepository,
ISysRoleRepository roleRepository,
IUserRoleRepository userRoleRepository,
IGroupCourseRepository groupCourseRepository,
IGroupCourseBookingRepository bookingRepository,
GroupCourseDao groupCourseDao,
GroupCourseBookingDao groupCourseBookingDao,
CoachViolationDao violationDao,
DatabaseClient databaseClient,
PasswordEncoder passwordEncoder,
RedisUtil redisUtil) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.userRoleRepository = userRoleRepository;
this.groupCourseRepository = groupCourseRepository;
this.bookingRepository = bookingRepository;
this.groupCourseDao = groupCourseDao;
this.groupCourseBookingDao = groupCourseBookingDao;
this.violationDao = violationDao;
this.databaseClient = databaseClient;
this.passwordEncoder = passwordEncoder;
this.redisUtil = redisUtil;
}
// ==================== 教练管理(从原 CoachService 迁移) ====================
public Flux<SysUser> getAllCoaches() {
return getCoachRoleId()
.flatMapMany(roleId -> userRoleRepository.findByRoleId(roleId)
.map(UserRole::getUserId)
.collectList()
.flatMapMany(userIds -> {
if (userIds.isEmpty()) {
return Flux.empty();
}
return Flux.fromIterable(userIds)
.flatMap(userRepository::findById)
.filter(user -> user.getDeletedAt() == null);
}));
}
public Mono<SysUser> createCoach(String username, String password, String nickname, String email, String phone) {
return getCoachRoleId().flatMap(coachRoleId -> {
SysUser user = new SysUser();
user.generateId();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(password));
user.setNickname(nickname);
user.setEmail(email);
user.setPhone(phone);
user.setStatus(StatusConstants.ENABLED);
return userRepository.save(user)
.flatMap(saved -> {
UserRole userRole = new UserRole();
userRole.setUserId(saved.getId());
userRole.setRoleId(coachRoleId);
return userRoleRepository.save(userRole).thenReturn(saved);
});
});
}
public Mono<SysUser> updateCoach(Long id, String nickname, String email, String phone) {
return userRepository.findById(id)
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
.flatMap(user -> {
if (nickname != null) user.setNickname(nickname);
if (email != null) user.setEmail(email);
if (phone != null) user.setPhone(phone);
user.setUpdatedAt(LocalDateTime.now());
return userRepository.update(user);
});
}
@Transactional(transactionManager = "connectionFactoryTransactionManager")
public Mono<Void> disableCoach(Long id) {
return userRepository.findById(id)
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
.flatMap(user ->
groupCourseRepository.countByCoachIdAndStatus(id, 3L)
.flatMap(inProgressCount -> {
if (inProgressCount > 0) {
return Mono.error(new RuntimeException(
"该教练有 " + inProgressCount + " 门正在进行中的团课,无法禁用"));
}
return groupCourseRepository.cancelCoursesByCoachIdExceptStatus(id, 3L)
.then();
})
.then(Mono.defer(() -> {
user.setStatus(StatusConstants.DISABLED);
user.setUpdatedAt(LocalDateTime.now());
return userRepository.update(user).then();
}))
)
.then(invalidateStatisticsCache());
}
public Flux<GroupCourse> getCoachCourses(Long coachId) {
return groupCourseRepository.findByCoachId(coachId, Sort.by(Sort.Direction.DESC, "startTime"))
.flatMap(course ->
bookingRepository.countValidBookings(course.getId())
.map(count -> {
course.setCurrentMembers(count.intValue());
return course;
})
.defaultIfEmpty(course)
);
}
public Mono<Long> getCoachRoleId() {
return roleRepository.findByRoleName(COACH_ROLE_NAME)
.map(SysRole::getId)
.switchIfEmpty(Mono.error(new RuntimeException("教练角色未找到,请先执行数据库迁移")));
}
// ==================== 开课逻辑 ====================
/**
* 教练手动开课
* 判定逻辑:
* - 长课时(>=1h): 10分钟内正常,10~30分钟迟到,>30分钟拒绝
* - 短课时(<1h): 10%时长内正常,10%~25%迟到,>25%拒绝
*/
public Mono<GroupCourseEntity> startCourse(Long courseId, Long coachId) {
return groupCourseDao.findByIdIsAndDeletedAtIsNull(courseId)
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
.flatMap(course -> {
// 验证教练身份
if (!course.getCoachId().equals(coachId)) {
return Mono.error(new RuntimeException("您不是该课程的教练,无权开课"));
}
// 验证课程状态:只有 NORMAL(0) 可以开课
if (!CourseStatus.NORMAL.getValue().equals(course.getStatus())) {
return Mono.error(new RuntimeException("当前课程状态不允许开课,当前状态: " + course.getStatus()));
}
LocalDateTime now = LocalDateTime.now();
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
return handleLongCourseStart(course, now);
} else {
return handleShortCourseStart(course, now, courseDurationMinutes);
}
});
}
private Mono<GroupCourseEntity> handleLongCourseStart(GroupCourseEntity course, LocalDateTime now) {
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
if (minutesSinceStart < 0) {
return Mono.error(new RuntimeException("课程尚未到开课时间"));
}
if (minutesSinceStart <= 10) {
// 正常开课
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
}
if (minutesSinceStart <= 30) {
// 教练迟到
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
}
// >30分钟,拒绝(调度器应已标记为缺席)
return Mono.error(new RuntimeException("已超过开课时间30分钟,无法开课"));
}
private Mono<GroupCourseEntity> handleShortCourseStart(GroupCourseEntity course, LocalDateTime now,
long courseDurationMinutes) {
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
long thresholdA = Math.max(1, (long) (courseDurationMinutes * 0.10));
long thresholdB = Math.max(1, (long) (courseDurationMinutes * 0.25));
if (minutesSinceStart < 0) {
return Mono.error(new RuntimeException("课程尚未到开课时间"));
}
if (minutesSinceStart <= thresholdA) {
// 正常开课
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
}
if (minutesSinceStart <= thresholdB) {
// 教练迟到
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
}
// >thresholdB,拒绝
return Mono.error(new RuntimeException("已超过开课时间,无法开课"));
}
private Mono<GroupCourseEntity> doStartCourse(GroupCourseEntity course, LocalDateTime now,
CourseStatus newStatus, ViolationReason violationReason) {
course.setStatus(newStatus.getValue());
course.setActualStartTime(now);
course.setUpdatedAt(now);
return groupCourseDao.updateStartInfo(course.getId(), String.valueOf(newStatus.getValue()), now, now)
.then(groupCourseDao.findByIdIsAndDeletedAtIsNull(course.getId()))
.flatMap(entity -> invalidateStatisticsCache().thenReturn(entity));
}
// ==================== 结课逻辑 ====================
/**
* 教练手动结课
* 可在 IN_PROGRESS(3) 或 COACH_LATE(7) 状态下结课
* 必须在标注结课时间 + 10分钟内
*/
public Mono<GroupCourseEntity> endCourse(Long courseId, Long coachId) {
return groupCourseDao.findByIdIsAndDeletedAtIsNull(courseId)
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
.flatMap(course -> {
// 验证教练身份
if (!course.getCoachId().equals(coachId)) {
return Mono.error(new RuntimeException("您不是该课程的教练,无权结课"));
}
// 验证状态:IN_PROGRESS(3) 或 COACH_LATE(7)
Long status = course.getStatus();
if (!CourseStatus.IN_PROGRESS.getValue().equals(status)
&& !CourseStatus.COACH_LATE.getValue().equals(status)) {
return Mono.error(new RuntimeException("当前课程状态不允许结课,当前状态: " + status));
}
LocalDateTime now = LocalDateTime.now();
long minutesAfterEnd = Duration.between(course.getEndTime(), now).toMinutes();
if (minutesAfterEnd > 10) {
return Mono.error(new RuntimeException("已超过结课时间10分钟,请等待系统自动结课"));
}
course.setStatus(CourseStatus.ENDED.getValue());
course.setActualEndTime(now);
course.setUpdatedAt(now);
return groupCourseDao.updateEndInfo(course.getId(), String.valueOf(CourseStatus.ENDED.getValue()), now, now)
.then(groupCourseDao.findByIdIsAndDeletedAtIsNull(course.getId()))
.flatMap(entity -> invalidateStatisticsCache().thenReturn(entity));
});
}
// ==================== 违规记录 ====================
/**
* 记录教练违规行为(使用 DatabaseClient 直连,避免 R2DBC Entity 映射问题)
*/
public Mono<Void> recordViolation(Long coachId, Long courseId, LocalDateTime violationTime,
ViolationReason reason) {
LocalDateTime now = LocalDateTime.now();
return databaseClient.sql("""
INSERT INTO coach_violation (coach_id, course_id, violation_time, violation_reason, created_at, updated_at)
VALUES (:coachId, :courseId, :violationTime, :reason, :now, :now)
""")
.bind("coachId", coachId)
.bind("courseId", courseId)
.bind("violationTime", violationTime)
.bind("reason", reason.getValue())
.bind("now", now)
.then();
}
// ==================== 违规查询 ====================
/**
* 获取所有教练的违规次数统计
*/
public Flux<Map<String, Object>> getViolationCounts() {
return databaseClient.sql("""
SELECT coach_id, COUNT(*) AS count
FROM coach_violation
WHERE deleted_at IS NULL
GROUP BY coach_id
""")
.fetch()
.all();
}
/**
* 获取指定教练的违规记录
*/
public Flux<Map<String, Object>> getCoachViolations(Long coachId) {
return databaseClient.sql("""
SELECT v.*, gc.course_name
FROM coach_violation v
LEFT JOIN group_course gc ON v.course_id = gc.id AND gc.deleted_at IS NULL
WHERE v.coach_id = :coachId AND v.deleted_at IS NULL
ORDER BY v.violation_time DESC
""")
.bind("coachId", coachId)
.fetch()
.all();
}
/**
* 清除统计缓存和团课缓存 —— 课程状态变更后调用,返回 Mono 确保链式执行
*/
private Mono<Void> invalidateStatisticsCache() {
return redisUtil.deleteByPattern("datacount:statistics:*")
.then(redisUtil.deleteByPattern("group_course:*"))
.doOnNext(count -> {})
.then();
}
}
-5
View File
@@ -100,11 +100,6 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -6,6 +6,7 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
import java.util.Map;
/**
* 数据统计 DAO - 使用 DatabaseClient 执行跨表聚合查询
@@ -180,4 +181,68 @@ public class DataStatisticsDao {
this.count = count;
}
}
// ========== 教练相关统计 ==========
/** 统计教练总数(角色为"教练"的用户) */
public Mono<Long> countTotalCoaches() {
return databaseClient.sql("""
SELECT COUNT(*) FROM sys_user u
INNER JOIN user_role ur ON u.id = ur.user_id
INNER JOIN sys_role sr ON ur.role_id = sr.id
WHERE sr.role_name = '教练' AND u.deleted_at IS NULL
""")
.map(row -> row.get(0, Long.class))
.one();
}
/** 统计违规总数(时间范围) */
public Mono<Long> countTotalViolations(LocalDateTime startTime, LocalDateTime endTime) {
return databaseClient.sql("""
SELECT COUNT(*) FROM coach_violation
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
""")
.bind("startTime", startTime)
.bind("endTime", endTime)
.map(row -> row.get(0, Long.class))
.one();
}
/** 按违规类型统计次数 */
public Flux<Map<String, Object>> countViolationsByReason(LocalDateTime startTime, LocalDateTime endTime) {
return databaseClient.sql("""
SELECT violation_reason, COUNT(*) AS count
FROM coach_violation
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
GROUP BY violation_reason
""")
.bind("startTime", startTime)
.bind("endTime", endTime)
.fetch()
.all();
}
/** 统计有违规记录的教练数 */
public Mono<Long> countViolatedCoaches(LocalDateTime startTime, LocalDateTime endTime) {
return databaseClient.sql("""
SELECT COUNT(DISTINCT coach_id) FROM coach_violation
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
""")
.bind("startTime", startTime)
.bind("endTime", endTime)
.map(row -> row.get(0, Long.class))
.one();
}
/** 统计区间内开课的团课数 */
public Mono<Long> countCourses(LocalDateTime startTime, LocalDateTime endTime) {
return databaseClient.sql("""
SELECT COUNT(*) FROM group_course
WHERE start_time >= :startTime AND start_time < :endTime AND deleted_at IS NULL
""")
.bind("startTime", startTime)
.bind("endTime", endTime)
.map(row -> row.get(0, Long.class))
.one();
}
}
@@ -0,0 +1,40 @@
package cn.novalon.gym.manage.datacount.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 教练统计数据
*
* @author 张翔
* @date 2026-07-20
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CoachStatistics {
/** 教练总数 */
private Long totalCoaches;
/** 违规总数 */
private Long totalViolations;
/** 迟到次数 */
private Long lateCount;
/** 缺席次数 */
private Long absentCount;
/** 未手动结课次数 */
private Long notManualEndCount;
/** 有违规记录的教练数 */
private Long violatedCoaches;
/** 统计区间内开课的团课数 */
private Long totalCourses;
}
@@ -37,6 +37,11 @@ public class StatisticsSummary {
*/
private SignInStatistics signInStatistics;
/**
* 教练统计数据
*/
private CoachStatistics coachStatistics;
/**
* 统计数据生成时间
*/
@@ -171,18 +171,47 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
return count != null ? count : 0L;
}
private Mono<CoachStatistics> getCoachStatistics(StatisticsQuery query) {
LocalDateTime startTime = getStartTime(query);
LocalDateTime endTime = getEndTime(query);
Mono<Long> totalCoachesMono = dataStatisticsDao.countTotalCoaches();
Mono<Long> totalViolationsMono = dataStatisticsDao.countTotalViolations(startTime, endTime);
Mono<Long> violatedCoachesMono = dataStatisticsDao.countViolatedCoaches(startTime, endTime);
Mono<Long> totalCoursesMono = dataStatisticsDao.countCourses(startTime, endTime);
Mono<Map<String, Long>> violationByReasonMono = dataStatisticsDao.countViolationsByReason(startTime, endTime)
.collectMap(row -> (String) row.get("violation_reason"),
row -> ((Number) row.get("count")).longValue());
return Mono.zip(totalCoachesMono, totalViolationsMono, violatedCoachesMono, totalCoursesMono, violationByReasonMono)
.map(tuple -> {
Map<String, Long> reasonMap = tuple.getT5();
return CoachStatistics.builder()
.totalCoaches(tuple.getT1())
.totalViolations(tuple.getT2())
.lateCount(reasonMap.getOrDefault("COACH_LATE", 0L))
.absentCount(reasonMap.getOrDefault("COACH_ABSENT", 0L))
.notManualEndCount(reasonMap.getOrDefault("NOT_MANUAL_END", 0L))
.violatedCoaches(tuple.getT3())
.totalCourses(tuple.getT4())
.build();
});
}
@Override
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query);
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query);
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query);
Mono<CoachStatistics> coachStatsMono = getCoachStatistics(query);
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono)
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono, coachStatsMono)
.map(tuple -> StatisticsSummary.builder()
.statDate(LocalDateTime.now().toLocalDate().toString())
.memberStatistics(tuple.getT1())
.bookingStatistics(tuple.getT2())
.signInStatistics(tuple.getT3())
.coachStatistics(tuple.getT4())
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
.build());
}
@@ -1,205 +0,0 @@
package cn.novalon.gym.manage.datacount.handler;
import cn.novalon.gym.manage.datacount.domain.*;
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/**
* 数据统计 Handler 单元测试
*/
class DataStatisticsHandlerTest {
@Mock
private IDataStatisticsService dataStatisticsService;
private DataStatisticsHandler handler;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
handler = new DataStatisticsHandler();
// 通过反射注入 mock
try {
var field = DataStatisticsHandler.class.getDeclaredField("dataStatisticsService");
field.setAccessible(true);
field.set(handler, dataStatisticsService);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
@DisplayName("综合统计 - 正常返回")
void testGetStatisticsSummary() {
StatisticsSummary summary = StatisticsSummary.builder()
.statDate("2026-07-21")
.memberStatistics(MemberStatistics.builder()
.newMembers(10L).totalMembers(500L).build())
.bookingStatistics(BookingStatistics.builder()
.newBookings(25L).attendanceRate(92.5).build())
.signInStatistics(SignInStatistics.builder()
.totalSignIns(80L).successRate(95.0).build())
.build();
when(dataStatisticsService.getStatisticsSummaryWithCache(any(StatisticsQuery.class)))
.thenReturn(Mono.just(summary));
Mono<ServerResponse> result = handler.getStatisticsSummary(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("综合统计 - 异常降级返回空结果")
void testGetStatisticsSummaryErrorFallback() {
when(dataStatisticsService.getStatisticsSummaryWithCache(any(StatisticsQuery.class)))
.thenReturn(Mono.error(new RuntimeException("数据库连接失败")));
Mono<ServerResponse> result = handler.getStatisticsSummary(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> {
return response.statusCode().is2xxSuccessful();
})
.verifyComplete();
}
@Test
@DisplayName("会员统计 - 正常返回")
void testGetMemberStatistics() {
MemberStatistics stats = MemberStatistics.builder()
.statDate("2026-07-21")
.newMembers(15L)
.activeMembers(120L)
.totalMembers(500L)
.signInMembers(80L)
.bookingMembers(60L)
.cancelBookingMembers(5L)
.build();
when(dataStatisticsService.getMemberStatistics(any(StatisticsQuery.class)))
.thenReturn(Mono.just(stats));
Mono<ServerResponse> result = handler.getMemberStatistics(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("预约统计 - 正常返回含出席率和取消率")
void testGetBookingStatistics() {
BookingStatistics stats = BookingStatistics.builder()
.statDate("2026-07-21")
.newBookings(30L)
.cancelBookings(3L)
.attendBookings(26L)
.absentBookings(1L)
.attendanceRate(96.3)
.cancelRate(10.0)
.bookingMembers(28L)
.cancelMembers(3L)
.build();
when(dataStatisticsService.getBookingStatistics(any(StatisticsQuery.class)))
.thenReturn(Mono.just(stats));
Mono<ServerResponse> result = handler.getBookingStatistics(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("签到统计 - 正常返回含细分类型")
void testGetSignInStatistics() {
SignInStatistics stats = SignInStatistics.builder()
.statDate("2026-07-21")
.totalSignIns(100L)
.successSignIns(95L)
.failedSignIns(5L)
.successRate(95.0)
.signInMembers(80L)
.qrCodeSignIns(60L)
.manualSignIns(20L)
.faceSignIns(15L)
.build();
when(dataStatisticsService.getSignInStatistics(any(StatisticsQuery.class)))
.thenReturn(Mono.just(stats));
Mono<ServerResponse> result = handler.getSignInStatistics(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("历史统计 - 返回统计列表")
void testQueryHistoricalStatistics() {
DataStatistics ds1 = new DataStatistics();
ds1.setStatType("MEMBER");
ds1.setCount(100L);
when(dataStatisticsService.queryHistoricalStatistics(any(StatisticsQuery.class)))
.thenReturn(Flux.just(ds1));
Mono<ServerResponse> result = handler.queryHistoricalStatistics(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("导出统计 - 返回Excel字节数组")
void testExportStatistics() {
byte[] excelBytes = new byte[]{0x50, 0x4B, 0x03, 0x04}; // ZIP magic bytes (xlsx)
when(dataStatisticsService.exportStatistics(any(StatisticsQuery.class)))
.thenReturn(Mono.just(excelBytes));
Mono<ServerResponse> result = handler.exportStatistics(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
@Test
@DisplayName("导出统计 - 异常降级返回错误消息")
void testExportStatisticsError() {
when(dataStatisticsService.exportStatistics(any(StatisticsQuery.class)))
.thenReturn(Mono.error(new RuntimeException("导出失败")));
Mono<ServerResponse> result = handler.exportStatistics(
MockServerRequest.builder().build());
StepVerifier.create(result)
.expectNextMatches(response -> response.statusCode().is2xxSuccessful())
.verifyComplete();
}
}
@@ -114,4 +114,11 @@ public interface GroupCourseBookingDao extends R2dbcRepository<GroupCourseBookin
@org.springframework.data.r2dbc.repository.Modifying
@org.springframework.data.r2dbc.repository.Query("UPDATE group_course_booking SET status = '3', updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
Mono<Integer> updateToAbsent(Long id, java.time.LocalDateTime updatedAt);
/**
* 批量更新某课程的预约状态(教练缺席场景)
*/
@org.springframework.data.r2dbc.repository.Modifying
@org.springframework.data.r2dbc.repository.Query("UPDATE group_course_booking SET status = :newStatus, updated_at = NOW() WHERE course_id = :courseId AND status = :oldStatus AND deleted_at IS NULL")
Mono<Integer> updateStatusByCourseId(Long courseId, String oldStatus, String newStatus);
}
@@ -37,9 +37,45 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
// ---------- 教练相关 SQL 方法 ----------
@Modifying
@Query("UPDATE group_course SET status = '2', updated_at = :updatedAt WHERE status = '0' AND end_time <= NOW() AND deleted_at IS NULL")
Mono<Integer> completeExpiredCourses(LocalDateTime updatedAt);
@Query("UPDATE group_course SET status = :status, actual_start_time = :actualStartTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
Mono<Integer> updateStartInfo(Long id, String status, LocalDateTime actualStartTime, LocalDateTime updatedAt);
@Modifying
@Query("UPDATE group_course SET status = :status, actual_end_time = :actualEndTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
Mono<Integer> updateEndInfo(Long id, String status, LocalDateTime actualEndTime, LocalDateTime updatedAt);
@Modifying
@Query("UPDATE group_course SET status = '5', actual_end_time = :actualEndTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
Mono<Integer> updateToCoachAbsent(Long id, LocalDateTime actualEndTime, LocalDateTime updatedAt);
@Modifying
@Query("UPDATE group_course SET status = '6', actual_end_time = :actualEndTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
Mono<Integer> updateToAutoEnded(Long id, LocalDateTime actualEndTime, LocalDateTime updatedAt);
/**
* 查询指定状态且开始时间早于指定时间的课程(用于缺席检查)
*/
default Flux<GroupCourseEntity> findByStatusAndStartTimeBefore(DatabaseClient databaseClient, String status, LocalDateTime time) {
return databaseClient.sql("SELECT * FROM group_course WHERE status = :status AND start_time < :time AND deleted_at IS NULL")
.bind("status", status)
.bind("time", time)
.map((row, meta) -> mapRowToEntity(row))
.all();
}
/**
* 查询指定状态集合且结束时间早于指定时间的课程(用于自动结课检查)
*/
default Flux<GroupCourseEntity> findByStatusInAndEndTimeBefore(DatabaseClient databaseClient, String[] statuses, LocalDateTime time) {
return databaseClient.sql("SELECT * FROM group_course WHERE status = ANY(:statuses::varchar[]) AND end_time < :time AND deleted_at IS NULL")
.bind("statuses", statuses)
.bind("time", time)
.map((row, meta) -> mapRowToEntity(row))
.all();
}
Flux<GroupCourseEntity> findByCourseTypeAndDeletedAtIsNull(Long courseType);
@@ -328,6 +364,8 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
entity.setCoverImage(row.get("cover_image", String.class));
entity.setDescription(row.get("description", String.class));
entity.setStoredValueAmount(row.get("stored_value_amount", java.math.BigDecimal.class));
entity.setActualStartTime(row.get("actual_start_time", LocalDateTime.class));
entity.setActualEndTime(row.get("actual_end_time", LocalDateTime.class));
entity.setQrCodePath(row.get("qr_code_path", String.class));
entity.setCreateBy(row.get("create_by", String.class));
entity.setUpdateBy(row.get("update_by", String.class));
@@ -40,6 +40,14 @@ public class GroupCourse extends BaseDomain{
@Schema(description = "课程状态", example = "0")
private Long status;
//实际开课时间
@Schema(description = "实际开课时间")
private LocalDateTime actualStartTime;
//实际结课时间
@Schema(description = "实际结课时间")
private LocalDateTime actualEndTime;
//上课地点
@Schema(description = "上课地点", example = "龙泉驿区幸福路")
private String location;
@@ -124,6 +132,22 @@ public class GroupCourse extends BaseDomain{
this.status = status;
}
public LocalDateTime getActualStartTime() {
return actualStartTime;
}
public void setActualStartTime(LocalDateTime actualStartTime) {
this.actualStartTime = actualStartTime;
}
public LocalDateTime getActualEndTime() {
return actualEndTime;
}
public void setActualEndTime(LocalDateTime actualEndTime) {
this.actualEndTime = actualEndTime;
}
public String getLocation() {
return location;
}
@@ -38,7 +38,15 @@ public class GroupCourseEntity extends BaseEntity {
@Column("current_members")
private Integer currentMembers;
//课程状态:0-正常,1-已取消,2-已结束
//实际开课时间
@Column("actual_start_time")
private LocalDateTime actualStartTime;
//实际结课时间
@Column("actual_end_time")
private LocalDateTime actualEndTime;
//课程状态:0-正常,1-已取消,2-已结束,3-进行中,5-教练缺席,6-自动结束,7-教练迟到
@Column("status")
private Long status;
@@ -158,6 +166,22 @@ public class GroupCourseEntity extends BaseEntity {
this.storedValueAmount = storedValueAmount;
}
public LocalDateTime getActualStartTime() {
return actualStartTime;
}
public void setActualStartTime(LocalDateTime actualStartTime) {
this.actualStartTime = actualStartTime;
}
public LocalDateTime getActualEndTime() {
return actualEndTime;
}
public void setActualEndTime(LocalDateTime actualEndTime) {
this.actualEndTime = actualEndTime;
}
public String getQrCodePath() {
return qrCodePath;
}
@@ -11,7 +11,10 @@ public enum CourseStatus {
NORMAL(0L, "正常"),
CANCELLED(1L, "已取消"),
ENDED(2L, "已结束"),
IN_PROGRESS(3L, "进行中");
IN_PROGRESS(3L, "进行中"),
COACH_ABSENT(5L, "教练缺席"),
AUTO_ENDED(6L, "自动结束"),
COACH_LATE(7L, "教练迟到");
private final Long value;
private final String desc;
@@ -1,46 +0,0 @@
package cn.novalon.gym.manage.groupcourse.scheduler;
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 团课过期状态自动更新定时任务
*
* 功能:定期检查已过期的团课(end_time <= NOW()),自动将 status 从 0 更新为 2(已结束)
*
* @date 2026-06-24
*/
@Component
public class GroupCourseExpireScheduler {
private static final Logger logger = LoggerFactory.getLogger(GroupCourseExpireScheduler.class);
private final GroupCourseDao groupCourseDao;
public GroupCourseExpireScheduler(GroupCourseDao groupCourseDao) {
this.groupCourseDao = groupCourseDao;
}
/**
* 每分钟检查一次,将已过期但状态仍为 0 的团课标记为已结束(status = 2)
*/
@Scheduled(fixedRate = 60000)
public void completeExpiredCourses() {
logger.debug("定时任务开始检查已过期团课,更新状态为已结束");
groupCourseDao.completeExpiredCourses(LocalDateTime.now())
.subscribe(
count -> {
if (count > 0) {
logger.info("定时任务完成,更新了 {} 条过期团课状态为已结束", count);
}
},
error -> logger.error("过期团课状态更新定时任务执行失败:{}", error.getMessage(), error)
);
}
}
@@ -107,10 +107,10 @@ public class GroupCourseService implements IGroupCourseService {
return Mono.<GroupCourseDetail>just(detail);
} catch (JsonProcessingException e) {
logger.warn("缓存解析失败,删除缓存 - id: {}, error: {}", id, e.getMessage());
return redisUtil.delete(cacheKey).then(Mono.<GroupCourseDetail>empty());
return redisUtil.delete(cacheKey).then(Mono.empty());
}
}
return Mono.<GroupCourseDetail>empty();
return Mono.empty();
})
.switchIfEmpty(
groupCourseRepository.findByIdAndDeletedAtIsNull(id)
@@ -243,10 +243,10 @@ public class GroupCourseService implements IGroupCourseService {
return Mono.<GroupCourse>just(groupCourse);
} catch (JsonProcessingException e) {
logger.warn("缓存解析失败,删除缓存 - id: {}, error: {}", id, e.getMessage());
return redisUtil.delete(cacheKey).then(Mono.<GroupCourse>empty());
return redisUtil.delete(cacheKey).then(Mono.empty());
}
}
return Mono.<GroupCourse>empty();
return Mono.empty();
})
.switchIfEmpty(
groupCourseRepository.findByIdAndDeletedAtIsNull(id)
@@ -741,7 +741,9 @@ public class GroupCourseService implements IGroupCourseService {
private Mono<Void> clearCache() {
return redisUtil.deleteByPattern(CACHE_KEY_PREFIX + "*")
.then(redisUtil.deleteByPattern(CACHE_KEY_ID_PREFIX + "*"))
.then(redisUtil.deleteByPattern(CACHE_KEY_DETAIL_PREFIX + "*")).then();
.then(redisUtil.deleteByPattern(CACHE_KEY_DETAIL_PREFIX + "*"))
.then(redisUtil.deleteByPattern("datacount:statistics:*"))
.then();
}
@Override
@@ -21,6 +21,8 @@ public class GroupCourseVO {
private Long courseType;
private LocalDateTime startTime;
private LocalDateTime endTime;
private LocalDateTime actualStartTime;
private LocalDateTime actualEndTime;
private Integer maxMembers;
private Integer currentMembers;
private Long status;
@@ -48,6 +50,8 @@ public class GroupCourseVO {
vo.setCourseType(course.getCourseType());
vo.setStartTime(course.getStartTime());
vo.setEndTime(course.getEndTime());
vo.setActualStartTime(course.getActualStartTime());
vo.setActualEndTime(course.getActualEndTime());
vo.setMaxMembers(course.getMaxMembers());
vo.setCurrentMembers(course.getCurrentMembers());
vo.setStatus(course.getStatus());
@@ -86,6 +90,12 @@ public class GroupCourseVO {
public LocalDateTime getEndTime() { return endTime; }
public void setEndTime(LocalDateTime endTime) { this.endTime = endTime; }
public LocalDateTime getActualStartTime() { return actualStartTime; }
public void setActualStartTime(LocalDateTime actualStartTime) { this.actualStartTime = actualStartTime; }
public LocalDateTime getActualEndTime() { return actualEndTime; }
public void setActualEndTime(LocalDateTime actualEndTime) { this.actualEndTime = actualEndTime; }
public Integer getMaxMembers() { return maxMembers; }
public void setMaxMembers(Integer maxMembers) { this.maxMembers = maxMembers; }
@@ -35,7 +35,7 @@ class QRCodeUtilTest {
@Test
void testGenerateQrCodeBytesWithLongContent() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
for (int i = 0; i < 100; i++) {
sb.append("这是第").append(i).append("行测试数据\n");
}
@@ -44,6 +44,6 @@ class QRCodeUtilTest {
assertNotNull(bytes, "二维码字节数组不应为空");
assertTrue(bytes.length > 0, "长内容二维码应正常生成");
System.out.println("多行内容二维码字节大小: " + bytes.length + " bytes");
System.out.println("内容二维码字节大小: " + bytes.length + " bytes");
}
}
@@ -1,246 +0,0 @@
package cn.novalon.gym.manage.member.handler;
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
import cn.novalon.gym.manage.member.enums.CardEvent;
import cn.novalon.gym.manage.member.enums.MemberCardRecordStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.junit.jupiter.api.Assertions.*;
/**
* 会员卡状态机单元测试
*/
class MemberCardStateMachineTest {
private MemberCardStateMachine stateMachine;
@BeforeEach
void setUp() {
stateMachine = new MemberCardStateMachine();
}
// ======================= ACTIVE 状态的转换 =======================
@Test
@DisplayName("ACTIVE + USE = ACTIVE(继续使用)")
void testActiveUse() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.ACTIVE, CardEvent.USE);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.ACTIVE)
.verifyComplete();
}
@Test
@DisplayName("ACTIVE + RENEW = ACTIVE(续费保持有效)")
void testActiveRenew() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.ACTIVE, CardEvent.RENEW);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.ACTIVE)
.verifyComplete();
}
@Test
@DisplayName("ACTIVE + EXPIRE = EXPIRED(过期)")
void testActiveExpire() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.ACTIVE, CardEvent.EXPIRE);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.EXPIRED)
.verifyComplete();
}
@Test
@DisplayName("ACTIVE + REFUND = REFUNDED(退款)")
void testActiveRefund() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.ACTIVE, CardEvent.REFUND);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.REFUNDED)
.verifyComplete();
}
// ======================= USED_UP 状态的转换 =======================
@Test
@DisplayName("USED_UP + RENEW = ACTIVE(用完后续费恢复)")
void testUsedUpRenew() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.USED_UP, CardEvent.RENEW);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.ACTIVE)
.verifyComplete();
}
@Test
@DisplayName("USED_UP + REFUND = REFUNDED(用完后退款)")
void testUsedUpRefund() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.USED_UP, CardEvent.REFUND);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.REFUNDED)
.verifyComplete();
}
@Test
@DisplayName("USED_UP + USE = 非法(用完不能再使用)")
void testUsedUpUseInvalid() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.USED_UP, CardEvent.USE);
StepVerifier.create(result)
.expectError(IllegalStateException.class)
.verify();
}
// ======================= EXPIRED 状态的转换 =======================
@Test
@DisplayName("EXPIRED + RENEW = ACTIVE(过期后续费恢复)")
void testExpiredRenew() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.EXPIRED, CardEvent.RENEW);
StepVerifier.create(result)
.expectNext(MemberCardRecordStatus.ACTIVE)
.verifyComplete();
}
@Test
@DisplayName("EXPIRED + USE = 非法(过期不能使用)")
void testExpiredUseInvalid() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.EXPIRED, CardEvent.USE);
StepVerifier.create(result)
.expectError(IllegalStateException.class)
.verify();
}
// ======================= REFUNDED 状态(终态)=======================
@Test
@DisplayName("REFUNDED + RENEW = 非法(已退款终态)")
void testRefundedRenewInvalid() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.REFUNDED, CardEvent.RENEW);
StepVerifier.create(result)
.expectError(IllegalStateException.class)
.verify();
}
@Test
@DisplayName("REFUNDED + USE = 非法(已退款终态)")
void testRefundedUseInvalid() {
Mono<MemberCardRecordStatus> result = stateMachine.transition(
MemberCardRecordStatus.REFUNDED, CardEvent.USE);
StepVerifier.create(result)
.expectError(IllegalStateException.class)
.verify();
}
// ======================= canTransition 检查 =======================
@Test
@DisplayName("canTransition - ACTIVE可以RENEW")
void testCanTransitionActiveRenew() {
Mono<Boolean> result = stateMachine.canTransition(
MemberCardRecordStatus.ACTIVE, CardEvent.RENEW);
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
}
@Test
@DisplayName("canTransition - USED_UP不能USE")
void testCanTransitionUsedUpUse() {
Mono<Boolean> result = stateMachine.canTransition(
MemberCardRecordStatus.USED_UP, CardEvent.USE);
StepVerifier.create(result)
.expectNext(false)
.verifyComplete();
}
@Test
@DisplayName("canTransition - REFUNDED不能任何操作")
void testCanTransitionRefundedAny() {
Mono<Boolean> result = stateMachine.canTransition(
MemberCardRecordStatus.REFUNDED, CardEvent.RENEW);
StepVerifier.create(result)
.expectNext(false)
.verifyComplete();
}
// ======================= validateTransition 检查 =======================
@Test
@DisplayName("validateTransition - ACTIVE状态卡片使用通过")
void testValidateTransitionValid() {
MemberCardRecord card = MemberCardRecord.builder()
.memberCardRecordId(1L)
.status(MemberCardRecordStatus.ACTIVE)
.build();
Mono<Void> result = stateMachine.validateTransition(card, CardEvent.USE);
StepVerifier.create(result)
.verifyComplete();
}
@Test
@DisplayName("validateTransition - REFUNDED状态卡片拒绝所有操作")
void testValidateTransitionRefunded() {
MemberCardRecord card = MemberCardRecord.builder()
.memberCardRecordId(2L)
.status(MemberCardRecordStatus.REFUNDED)
.build();
Mono<Void> result = stateMachine.validateTransition(card, CardEvent.RENEW);
StepVerifier.create(result)
.expectError(IllegalStateException.class)
.verify();
}
// ======================= 枚举值验证 =======================
@Test
@DisplayName("MemberCardRecordStatus 枚举值完整")
void testStatusEnumValues() {
MemberCardRecordStatus[] values = MemberCardRecordStatus.values();
assertEquals(4, values.length);
assertEquals("有效", MemberCardRecordStatus.ACTIVE.getDesc());
assertEquals("用完", MemberCardRecordStatus.USED_UP.getDesc());
assertEquals("过期", MemberCardRecordStatus.EXPIRED.getDesc());
assertEquals("已退款", MemberCardRecordStatus.REFUNDED.getDesc());
}
@Test
@DisplayName("CardEvent 枚举值完整")
void testEventEnumValues() {
CardEvent[] values = CardEvent.values();
assertEquals(6, values.length);
assertEquals("激活卡片", CardEvent.ACTIVATE.getDesc());
assertEquals("使用卡片", CardEvent.USE.getDesc());
assertEquals("续费", CardEvent.RENEW.getDesc());
assertEquals("过期", CardEvent.EXPIRE.getDesc());
assertEquals("退款", CardEvent.REFUND.getDesc());
assertEquals("禁用", CardEvent.DISABLE.getDesc());
}
}
@@ -1,138 +0,0 @@
package cn.novalon.gym.manage.member.util;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* Bean转换工具类单元测试
*/
class BeanConvertUtilTest {
@Test
@DisplayName("toBean - 正常转换")
void testToBeanNormal() {
Source source = new Source();
source.setName("张三");
source.setAge(25);
source.setEmail("zhangsan@test.com");
Target target = BeanConvertUtil.toBean(source, Target.class);
assertNotNull(target);
assertEquals("张三", target.getName());
assertEquals(25, target.getAge());
assertEquals("zhangsan@test.com", target.getEmail());
}
@Test
@DisplayName("toBean - 部分字段转换")
void testToBeanPartial() {
Source source = new Source();
source.setName("李四");
source.setAge(30);
// email 不设置
Target target = BeanConvertUtil.toBean(source, Target.class);
assertNotNull(target);
assertEquals("李四", target.getName());
assertEquals(30, target.getAge());
assertNull(target.getEmail());
}
@Test
@DisplayName("toBean - null输入返回null")
void testToBeanNull() {
Target target = BeanConvertUtil.toBean(null, Target.class);
assertNull(target);
}
@Test
@DisplayName("toBeanList - 正常批量转换")
void testToBeanListNormal() {
Source s1 = new Source();
s1.setName("A"); s1.setAge(20);
Source s2 = new Source();
s2.setName("B"); s2.setAge(25);
Source s3 = new Source();
s3.setName("C"); s3.setAge(30);
List<Target> targets = BeanConvertUtil.toBeanList(
Arrays.asList(s1, s2, s3), Target.class);
assertEquals(3, targets.size());
assertEquals("A", targets.get(0).getName());
assertEquals(20, targets.get(0).getAge());
assertEquals("B", targets.get(1).getName());
assertEquals("C", targets.get(2).getName());
}
@Test
@DisplayName("toBeanList - null输入返回空列表")
void testToBeanListNull() {
List<Target> targets = BeanConvertUtil.toBeanList(null, Target.class);
assertNotNull(targets);
assertTrue(targets.isEmpty());
}
@Test
@DisplayName("toBeanList - 空列表输入返回空列表")
void testToBeanListEmpty() {
List<Target> targets = BeanConvertUtil.toBeanList(
Collections.emptyList(), Target.class);
assertNotNull(targets);
assertTrue(targets.isEmpty());
}
@Test
@DisplayName("toBeanList - 单元素列表")
void testToBeanListSingle() {
Source source = new Source();
source.setName("王五");
source.setAge(35);
List<Target> targets = BeanConvertUtil.toBeanList(
Collections.singletonList(source), Target.class);
assertEquals(1, targets.size());
assertEquals("王五", targets.get(0).getName());
assertEquals(35, targets.get(0).getAge());
}
// === 内部测试类 ===
public static class Source {
private String name;
private int age;
private String email;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
public static class Target {
private String name;
private int age;
private String email;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
}
@@ -1,85 +0,0 @@
package cn.novalon.gym.manage.member.util;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* 会员号生成器单元测试
*/
class MemberNoGeneratorTest {
@Test
@DisplayName("生成会员号 - 格式正确 GYM + 8位字符")
void testGenerateFormat() {
String memberNo = MemberNoGenerator.generate();
assertNotNull(memberNo);
assertEquals(11, memberNo.length());
assertTrue(memberNo.startsWith("GYM"));
// 后8位只包含合法字符
String suffix = memberNo.substring(3);
for (char c : suffix.toCharArray()) {
assertTrue("23456789ABCDEFGHJKLMNPQRSTUVWXYZ".indexOf(c) >= 0,
"非法字符: " + c);
}
}
@Test
@DisplayName("生成会员号 - 不包含易混淆字符")
void testGenerateNoAmbiguousChars() {
for (int i = 0; i < 50; i++) {
String memberNo = MemberNoGenerator.generate();
assertFalse(memberNo.contains("0"));
assertFalse(memberNo.contains("O"));
assertFalse(memberNo.contains("1"));
assertFalse(memberNo.contains("I"));
assertFalse(memberNo.contains("l"));
}
}
@RepeatedTest(10)
@DisplayName("生成会员号 - 高概率不重复")
void testGenerateUniqueness() {
String no1 = MemberNoGenerator.generate();
String no2 = MemberNoGenerator.generate();
// 极低概率重复(字符集30个字符取8位,总共 30^8 种组合)
assertNotEquals(no1, no2);
}
@Test
@DisplayName("批量生成 - 生成指定数量")
void testGenerateBatch() {
int count = 5;
String[] memberNos = MemberNoGenerator.generateBatch(count);
assertEquals(count, memberNos.length);
for (String no : memberNos) {
assertNotNull(no);
assertEquals(11, no.length());
assertTrue(no.startsWith("GYM"));
}
}
@Test
@DisplayName("批量生成 - 全部不重复")
void testGenerateBatchUnique() {
String[] memberNos = MemberNoGenerator.generateBatch(20);
for (int i = 0; i < memberNos.length; i++) {
for (int j = i + 1; j < memberNos.length; j++) {
assertNotEquals(memberNos[i], memberNos[j],
"重复会员号: " + memberNos[i]);
}
}
}
@Test
@DisplayName("批量生成 - count=0 返回空数组")
void testGenerateBatchZero() {
String[] memberNos = MemberNoGenerator.generateBatch(0);
assertEquals(0, memberNos.length);
}
}
+6
View File
@@ -169,6 +169,12 @@
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cn.novalon.gym.manage</groupId>
<artifactId>gym-coach</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@@ -25,7 +25,8 @@ import java.util.List;
"cn.novalon.gym.manage.member.repository",
"cn.novalon.gym.manage.groupcourse.dao",
"cn.novalon.gym.manage.checkIn.repository",
"cn.novalon.gym.manage.payment.repository"
"cn.novalon.gym.manage.payment.repository",
"cn.novalon.gym.manage.coach.dao"
})
@EnableReactiveElasticsearchRepositories(basePackages = "cn.novalon.gym.manage.member.es.repository")
public class ManageApplication {
@@ -20,7 +20,8 @@ import cn.novalon.gym.manage.notify.handler.BannerHandler;
import cn.novalon.gym.manage.notify.handler.SysNoticeHandler;
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
import cn.novalon.gym.manage.payment.handler.PaymentHandler;
import cn.novalon.gym.manage.app.handler.CoachHandler;
import cn.novalon.gym.manage.coach.handler.CoachCourseHandler;
import cn.novalon.gym.manage.coach.handler.CoachHandler;
import cn.novalon.gym.manage.sys.handler.auth.PasswordDiagnosticHandler;
import cn.novalon.gym.manage.sys.handler.auth.SysAuthHandler;
import cn.novalon.gym.manage.sys.handler.config.SysConfigHandler;
@@ -86,7 +87,8 @@ public class SystemRouter {
DataStatisticsHandler dataStatisticsHandler,
PhoneAuthHandler phoneAuthHandler,
PaymentHandler paymentHandler,
CoachHandler coachHandler) {
CoachHandler coachHandler,
CoachCourseHandler coachCourseHandler) {
return route()
// ========== 诊断路由 ==========
@@ -126,6 +128,10 @@ public class SystemRouter {
.PUT("/api/coach/{id}", coachHandler::updateCoach)
.POST("/api/coach/{id}/disable", coachHandler::disableCoach)
.GET("/api/coach/{id}/courses", coachHandler::getCoachCourses)
.GET("/api/coach/violation-counts", coachHandler::getViolationCounts)
.GET("/api/coach/{id}/violations", coachHandler::getCoachViolations)
.POST("/api/coach/courses/{courseId}/start", coachCourseHandler::startCourse)
.POST("/api/coach/courses/{courseId}/end", coachCourseHandler::endCourse)
// ========== 菜单路由 ==========
.GET("/api/menus", menuHandler::getAllMenus)
@@ -1,144 +0,0 @@
package cn.novalon.gym.manage.app.service;
import cn.novalon.gym.manage.common.util.StatusConstants;
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
import cn.novalon.gym.manage.sys.core.domain.SysRole;
import cn.novalon.gym.manage.sys.core.domain.SysUser;
import cn.novalon.gym.manage.sys.core.domain.UserRole;
import cn.novalon.gym.manage.sys.core.repository.ISysRoleRepository;
import cn.novalon.gym.manage.sys.core.repository.ISysUserRepository;
import cn.novalon.gym.manage.sys.core.repository.IUserRoleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
/**
* 教练服务(跨模块编排,放在 manage-app 中避免模块循环依赖)
*
* @author 张翔
* @date 2026-07-19
*/
@Service
public class CoachService {
private static final Logger logger = LoggerFactory.getLogger(CoachService.class);
private static final String COACH_ROLE_NAME = "教练";
private final ISysUserRepository userRepository;
private final ISysRoleRepository roleRepository;
private final IUserRoleRepository userRoleRepository;
private final IGroupCourseRepository groupCourseRepository;
private final IGroupCourseBookingRepository bookingRepository;
private final PasswordEncoder passwordEncoder;
public CoachService(ISysUserRepository userRepository,
ISysRoleRepository roleRepository,
IUserRoleRepository userRoleRepository,
IGroupCourseRepository groupCourseRepository,
IGroupCourseBookingRepository bookingRepository,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.userRoleRepository = userRoleRepository;
this.groupCourseRepository = groupCourseRepository;
this.bookingRepository = bookingRepository;
this.passwordEncoder = passwordEncoder;
}
public Flux<SysUser> getAllCoaches() {
return getCoachRoleId()
.flatMapMany(roleId -> userRoleRepository.findByRoleId(roleId)
.map(UserRole::getUserId)
.collectList()
.flatMapMany(userIds -> {
if (userIds.isEmpty()) {
return Flux.empty();
}
return Flux.fromIterable(userIds)
.flatMap(userRepository::findById)
.filter(user -> user.getDeletedAt() == null);
}));
}
public Mono<SysUser> createCoach(String username, String password, String nickname, String email, String phone) {
return getCoachRoleId().flatMap(coachRoleId -> {
SysUser user = new SysUser();
user.generateId();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(password));
user.setNickname(nickname);
user.setEmail(email);
user.setPhone(phone);
user.setStatus(StatusConstants.ENABLED);
return userRepository.save(user)
.flatMap(saved -> {
UserRole userRole = new UserRole();
userRole.setUserId(saved.getId());
userRole.setRoleId(coachRoleId);
return userRoleRepository.save(userRole).thenReturn(saved);
});
});
}
public Mono<SysUser> updateCoach(Long id, String nickname, String email, String phone) {
return userRepository.findById(id)
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
.flatMap(user -> {
if (nickname != null) user.setNickname(nickname);
if (email != null) user.setEmail(email);
if (phone != null) user.setPhone(phone);
user.setUpdatedAt(LocalDateTime.now());
return userRepository.update(user);
});
}
@Transactional(transactionManager = "connectionFactoryTransactionManager")
public Mono<Void> disableCoach(Long id) {
return userRepository.findById(id)
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
.flatMap(user ->
groupCourseRepository.countByCoachIdAndStatus(id, 3L)
.flatMap(inProgressCount -> {
if (inProgressCount > 0) {
return Mono.error(new RuntimeException(
"该教练有 " + inProgressCount + " 门正在进行中的团课,无法禁用"));
}
return groupCourseRepository.cancelCoursesByCoachIdExceptStatus(id, 3L)
.then();
})
.then(Mono.defer(() -> {
user.setStatus(StatusConstants.DISABLED);
user.setUpdatedAt(LocalDateTime.now());
return userRepository.update(user).then();
}))
);
}
public Flux<GroupCourse> getCoachCourses(Long coachId) {
return groupCourseRepository.findByCoachId(coachId, Sort.by(Sort.Direction.DESC, "startTime"))
.flatMap(course ->
bookingRepository.countValidBookings(course.getId())
.map(count -> {
course.setCurrentMembers(count.intValue());
return course;
})
.defaultIfEmpty(course)
);
}
public Mono<Long> getCoachRoleId() {
return roleRepository.findByRoleName(COACH_ROLE_NAME)
.map(SysRole::getId)
.switchIfEmpty(Mono.error(new RuntimeException("教练角色未找到,请先执行数据库迁移")));
}
}
@@ -66,121 +66,121 @@ ON CONFLICT DO NOTHING;
-- ============================================
-- 4. 团课课程数据(5个类型 × 5个课程 = 25个)
-- start_time / end_time 分布在 2026-07-20 至 2026-08-02
-- start_time / end_time 分布在 2026-07-22 至 2026-07-28
-- ============================================
-- ---------- 瑜伽课程(5个)----------
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '哈他瑜伽入门', gt.id, '2026-07-20 08:00:00'::TIMESTAMP, '2026-07-20 09:00:00'::TIMESTAMP, 25, 12, '0', '瑜伽室A', '/static/course/yoga_hatha.jpg', '经典哈他瑜伽,从基础体式入手,配合呼吸引导,帮助初学者建立正确的瑜伽练习基础,感受身心的和谐统一。', 88.00, 'system'
SELECT '哈他瑜伽入门', gt.id, '2026-07-22 08:00:00'::TIMESTAMP, '2026-07-22 09:00:00'::TIMESTAMP, 25, 12, '0', '瑜伽室A', '/static/course/yoga_hatha.jpg', '经典哈他瑜伽,从基础体式入手,配合呼吸引导,帮助初学者建立正确的瑜伽练习基础,感受身心的和谐统一。', 88.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '瑜伽';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '流瑜伽', gt.id, '2026-07-22 10:00:00'::TIMESTAMP, '2026-07-22 11:00:00'::TIMESTAMP, 20, 18, '0', '瑜伽室A', '/static/course/yoga_flow.jpg', '体式之间流畅串联,如行云流水般一气呵成。以拜日式为根基,结合站姿、平衡和扭转,提升力量与柔韧的整合能力。', 98.00, 'system'
SELECT '流瑜伽', gt.id, '2026-07-24 10:00:00'::TIMESTAMP, '2026-07-24 11:00:00'::TIMESTAMP, 20, 18, '0', '瑜伽室A', '/static/course/yoga_flow.jpg', '体式之间流畅串联,如行云流水般一气呵成。以拜日式为根基,结合站姿、平衡和扭转,提升力量与柔韧的整合能力。', 98.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '瑜伽';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '阴瑜伽', gt.id, '2026-07-24 18:00:00'::TIMESTAMP, '2026-07-24 19:15:00'::TIMESTAMP, 20, 8, '0', '瑜伽室B', '/static/course/yoga_yin.jpg', '阴瑜伽以长时间保持体式为特点,深度伸展筋膜和结缔组织,帮助你释放身体深层紧张,缓解一周的工作疲劳。适合所有级别。', 88.00, 'system'
SELECT '阴瑜伽', gt.id, '2026-07-26 18:00:00'::TIMESTAMP, '2026-07-26 19:15:00'::TIMESTAMP, 20, 8, '0', '瑜伽室B', '/static/course/yoga_yin.jpg', '阴瑜伽以长时间保持体式为特点,深度伸展筋膜和结缔组织,帮助你释放身体深层紧张,缓解一周的工作疲劳。适合所有级别。', 88.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '瑜伽';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '阿斯汤加瑜伽', gt.id, '2026-07-21 07:00:00'::TIMESTAMP, '2026-07-21 08:30:00'::TIMESTAMP, 15, 10, '0', '瑜伽室A', '/static/course/yoga_ashtanga.jpg', '阿斯汤加瑜伽以固定的体式序列和独特的呼吸法为核心,节奏紧凑,强度较高,能有效提升力量、柔韧和专注力。建议有一定瑜伽基础者参加。', 128.00, 'system'
SELECT '阿斯汤加瑜伽', gt.id, '2026-07-23 07:00:00'::TIMESTAMP, '2026-07-23 08:30:00'::TIMESTAMP, 15, 10, '0', '瑜伽室A', '/static/course/yoga_ashtanga.jpg', '阿斯汤加瑜伽以固定的体式序列和独特的呼吸法为核心,节奏紧凑,强度较高,能有效提升力量、柔韧和专注力。建议有一定瑜伽基础者参加。', 128.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '瑜伽';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '空中瑜伽', gt.id, '2026-07-23 19:00:00'::TIMESTAMP, '2026-07-23 20:00:00'::TIMESTAMP, 12, 12, '0', '瑜伽室B', '/static/course/yoga_aerial.jpg', '利用悬挂的瑜伽吊床完成各种体式,借助重力让脊柱自然延展,体验"飞翔"般的自由感。深受女性学员喜爱,名额有限请提前预约。', 128.00, 'system'
SELECT '空中瑜伽', gt.id, '2026-07-25 19:00:00'::TIMESTAMP, '2026-07-25 20:00:00'::TIMESTAMP, 12, 12, '0', '瑜伽室B', '/static/course/yoga_aerial.jpg', '利用悬挂的瑜伽吊床完成各种体式,借助重力让脊柱自然延展,体验"飞翔"般的自由感。深受女性学员喜爱,名额有限请提前预约。', 128.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '瑜伽';
-- ---------- 动感单车课程(5个)----------
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '初级燃脂骑行', gt.id, '2026-07-20 19:00:00'::TIMESTAMP, '2026-07-20 19:45:00'::TIMESTAMP, 30, 22, '0', '单车房', '/static/course/spin_beginner.jpg', '适合新手的入门级骑行课程,教练将带领你掌握正确的骑行姿势和阻力调节技巧。在动感音乐中轻松燃烧300-400卡路里。', 58.00, 'system'
SELECT '初级燃脂骑行', gt.id, '2026-07-22 19:00:00'::TIMESTAMP, '2026-07-22 19:45:00'::TIMESTAMP, 30, 22, '0', '单车房', '/static/course/spin_beginner.jpg', '适合新手的入门级骑行课程,教练将带领你掌握正确的骑行姿势和阻力调节技巧。在动感音乐中轻松燃烧300-400卡路里。', 58.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '动感单车';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '节奏爬坡', gt.id, '2026-07-22 18:30:00'::TIMESTAMP, '2026-07-22 19:15:00'::TIMESTAMP, 30, 15, '0', '单车房', '/static/course/spin_climb.jpg', '模拟山路爬坡骑行,通过逐渐增加阻力来挑战你的耐力和意志力。每一段爬坡后都有短暂的平路冲刺,节奏感十足,大汗淋漓的畅快体验。', 68.00, 'system'
SELECT '节奏爬坡', gt.id, '2026-07-24 18:30:00'::TIMESTAMP, '2026-07-24 19:15:00'::TIMESTAMP, 30, 15, '0', '单车房', '/static/course/spin_climb.jpg', '模拟山路爬坡骑行,通过逐渐增加阻力来挑战你的耐力和意志力。每一段爬坡后都有短暂的平路冲刺,节奏感十足,大汗淋漓的畅快体验。', 68.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '动感单车';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '极速冲刺', gt.id, '2026-07-24 20:00:00'::TIMESTAMP, '2026-07-24 20:45:00'::TIMESTAMP, 25, 25, '0', '单车房', '/static/course/spin_sprint.jpg', '高强度冲刺为主题的骑行课,多组30秒极限冲刺搭配短暂恢复,彻底引爆你的心肺极限。周五夜间的爆款课程,约满速度极快!', 68.00, 'system'
SELECT '极速冲刺', gt.id, '2026-07-26 20:00:00'::TIMESTAMP, '2026-07-26 20:45:00'::TIMESTAMP, 25, 25, '0', '单车房', '/static/course/spin_sprint.jpg', '高强度冲刺为主题的骑行课,多组30秒极限冲刺搭配短暂恢复,彻底引爆你的心肺极限。周五夜间的爆款课程,约满速度极快!', 68.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '动感单车';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '耐力骑行', gt.id, '2026-07-25 10:00:00'::TIMESTAMP, '2026-07-25 11:00:00'::TIMESTAMP, 30, 18, '0', '单车房', '/static/course/spin_endurance.jpg', '60分钟中低强度耐力骑行,适合周末早晨唤醒身体。在稳定的节奏中持续燃脂,配以舒缓的收尾拉伸,开启元气满满的周末。', 58.00, 'system'
SELECT '耐力骑行', gt.id, '2026-07-27 10:00:00'::TIMESTAMP, '2026-07-27 11:00:00'::TIMESTAMP, 30, 18, '0', '单车房', '/static/course/spin_endurance.jpg', '60分钟中低强度耐力骑行,适合周末早晨唤醒身体。在稳定的节奏中持续燃脂,配以舒缓的收尾拉伸,开启元气满满的周末。', 58.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '动感单车';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '音乐主题骑行', gt.id, '2026-07-21 19:30:00'::TIMESTAMP, '2026-07-21 20:15:00'::TIMESTAMP, 30, 20, '0', '单车房', '/static/course/spin_music.jpg', '以热门流行音乐为主题的骑行派对!每首歌曲对应一套骑行组合,跟着节拍加速、爬坡、冲刺,在音乐中忘记疲惫。', 68.00, 'system'
SELECT '音乐主题骑行', gt.id, '2026-07-23 19:30:00'::TIMESTAMP, '2026-07-23 20:15:00'::TIMESTAMP, 30, 20, '0', '单车房', '/static/course/spin_music.jpg', '以热门流行音乐为主题的骑行派对!每首歌曲对应一套骑行组合,跟着节拍加速、爬坡、冲刺,在音乐中忘记疲惫。', 68.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '动感单车';
-- ---------- HIIT训练课程(5个)----------
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT 'Tabata燃脂', gt.id, '2026-07-20 07:00:00'::TIMESTAMP, '2026-07-20 07:30:00'::TIMESTAMP, 15, 8, '0', '多功能训练区', '/static/course/hiit_tabata.jpg', '经典的Tabata模式:20秒全力运动 + 10秒休息,循环8轮共4分钟,搭配热身和拉伸,30分钟全身燃爆。早晨空腹训练燃脂效果加倍!', 98.00, 'system'
SELECT 'Tabata燃脂', gt.id, '2026-07-22 07:00:00'::TIMESTAMP, '2026-07-22 07:30:00'::TIMESTAMP, 15, 8, '0', '多功能训练区', '/static/course/hiit_tabata.jpg', '经典的Tabata模式:20秒全力运动 + 10秒休息,循环8轮共4分钟,搭配热身和拉伸,30分钟全身燃爆。早晨空腹训练燃脂效果加倍!', 98.00, 'system'
FROM group_course_type gt WHERE gt.type_name = 'HIIT训练';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '全身循环训练', gt.id, '2026-07-22 12:00:00'::TIMESTAMP, '2026-07-22 12:45:00'::TIMESTAMP, 15, 12, '0', '多功能训练区', '/static/course/hiit_circuit.jpg', '午间燃脂利器!8个动作站点轮流进行,涵盖深蹲跳、波比跳、壶铃摇摆、登山跑等,每个动作45秒,休息15秒,3轮循环让你全身湿透。', 98.00, 'system'
SELECT '全身循环训练', gt.id, '2026-07-24 12:00:00'::TIMESTAMP, '2026-07-24 12:45:00'::TIMESTAMP, 15, 12, '0', '多功能训练区', '/static/course/hiit_circuit.jpg', '午间燃脂利器!8个动作站点轮流进行,涵盖深蹲跳、波比跳、壶铃摇摆、登山跑等,每个动作45秒,休息15秒,3轮循环让你全身湿透。', 98.00, 'system'
FROM group_course_type gt WHERE gt.type_name = 'HIIT训练';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '核心爆发力', gt.id, '2026-07-24 17:30:00'::TIMESTAMP, '2026-07-24 18:15:00'::TIMESTAMP, 12, 5, '0', '多功能训练区', '/static/course/hiit_core.jpg', '专注于核心肌群的HIIT训练,结合药球砸地、悬垂举腿、俄罗斯转体和平板支撑变式,打造钢铁般的核心力量,提升所有运动表现。', 108.00, 'system'
SELECT '核心爆发力', gt.id, '2026-07-26 17:30:00'::TIMESTAMP, '2026-07-26 18:15:00'::TIMESTAMP, 12, 5, '0', '多功能训练区', '/static/course/hiit_core.jpg', '专注于核心肌群的HIIT训练,结合药球砸地、悬垂举腿、俄罗斯转体和平板支撑变式,打造钢铁般的核心力量,提升所有运动表现。', 108.00, 'system'
FROM group_course_type gt WHERE gt.type_name = 'HIIT训练';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '战绳挑战', gt.id, '2026-07-25 08:00:00'::TIMESTAMP, '2026-07-25 08:45:00'::TIMESTAMP, 10, 10, '0', '户外训练区', '/static/course/hiit_battle.jpg', '风靡全球的战绳训练!通过波浪、猛击、旋转等动作模式激活全身肌群,30秒一组高强度间歇,燃脂同时雕刻上肢线条。名额有限,已约满!', 128.00, 'system'
SELECT '战绳挑战', gt.id, '2026-07-27 08:00:00'::TIMESTAMP, '2026-07-27 08:45:00'::TIMESTAMP, 10, 10, '0', '户外训练区', '/static/course/hiit_battle.jpg', '风靡全球的战绳训练!通过波浪、猛击、旋转等动作模式激活全身肌群,30秒一组高强度间歇,燃脂同时雕刻上肢线条。名额有限,已约满!', 128.00, 'system'
FROM group_course_type gt WHERE gt.type_name = 'HIIT训练';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '药球HIIT', gt.id, '2026-07-26 10:00:00'::TIMESTAMP, '2026-07-26 10:45:00'::TIMESTAMP, 12, 6, '0', '多功能训练区', '/static/course/hiit_medball.jpg', '以药球为主要工具的HIIT训练。药球砸地、旋转投掷、过头抛接等动作兼具力量和爆发力训练,动作多样不枯燥,周日上午的爆汗之选。', 108.00, 'system'
SELECT '药球HIIT', gt.id, '2026-07-28 10:00:00'::TIMESTAMP, '2026-07-28 10:45:00'::TIMESTAMP, 12, 6, '0', '多功能训练区', '/static/course/hiit_medball.jpg', '以药球为主要工具的HIIT训练。药球砸地、旋转投掷、过头抛接等动作兼具力量和爆发力训练,动作多样不枯燥,周日上午的爆汗之选。', 108.00, 'system'
FROM group_course_type gt WHERE gt.type_name = 'HIIT训练';
-- ---------- 普拉提课程(5个)----------
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '垫上普拉提', gt.id, '2026-07-21 10:00:00'::TIMESTAMP, '2026-07-21 11:00:00'::TIMESTAMP, 20, 14, '0', '普拉提室', '/static/course/pilates_mat.jpg', '经典垫上普拉提,通过精准的动作控制激活深层核心肌群。从呼吸到骨盆稳定,从脊柱逐节卷动到四肢协调,一节课改善你的身体感知。', 108.00, 'system'
SELECT '垫上普拉提', gt.id, '2026-07-23 10:00:00'::TIMESTAMP, '2026-07-23 11:00:00'::TIMESTAMP, 20, 14, '0', '普拉提室', '/static/course/pilates_mat.jpg', '经典垫上普拉提,通过精准的动作控制激活深层核心肌群。从呼吸到骨盆稳定,从脊柱逐节卷动到四肢协调,一节课改善你的身体感知。', 108.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '普拉提';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '器械普拉提', gt.id, '2026-07-23 09:00:00'::TIMESTAMP, '2026-07-23 10:00:00'::TIMESTAMP, 10, 8, '0', '普拉提室', '/static/course/pilates_reformer.jpg', '使用专业普拉提核心床(Reformer)进行训练,弹簧阻力提供精准的负荷控制,适合需要针对性改善体态、康复训练或追求高效塑形的学员。', 158.00, 'system'
SELECT '器械普拉提', gt.id, '2026-07-25 09:00:00'::TIMESTAMP, '2026-07-25 10:00:00'::TIMESTAMP, 10, 8, '0', '普拉提室', '/static/course/pilates_reformer.jpg', '使用专业普拉提核心床(Reformer)进行训练,弹簧阻力提供精准的负荷控制,适合需要针对性改善体态、康复训练或追求高效塑形的学员。', 158.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '普拉提';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '核心塑形', gt.id, '2026-07-25 14:00:00'::TIMESTAMP, '2026-07-25 15:00:00'::TIMESTAMP, 15, 9, '0', '普拉提室', '/static/course/pilates_sculpt.jpg', '专注于腹部、腰部和臀部的普拉提塑形课程。百次拍击、剪刀腿、肩桥等经典动作持续刺激目标肌群,打造紧致核心线条。', 128.00, 'system'
SELECT '核心塑形', gt.id, '2026-07-27 14:00:00'::TIMESTAMP, '2026-07-27 15:00:00'::TIMESTAMP, 15, 9, '0', '普拉提室', '/static/course/pilates_sculpt.jpg', '专注于腹部、腰部和臀部的普拉提塑形课程。百次拍击、剪刀腿、肩桥等经典动作持续刺激目标肌群,打造紧致核心线条。', 128.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '普拉提';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '脊柱健康', gt.id, '2026-07-20 16:00:00'::TIMESTAMP, '2026-07-20 17:00:00'::TIMESTAMP, 15, 6, '0', '普拉提室', '/static/course/pilates_spine.jpg', '专为久坐办公人群设计,通过普拉提脊柱逐节运动改善驼背、圆肩等不良体态。融合猫牛式、脊柱旋转和游泳式,给你的脊柱一次深度保养。', 108.00, 'system'
SELECT '脊柱健康', gt.id, '2026-07-22 16:00:00'::TIMESTAMP, '2026-07-22 17:00:00'::TIMESTAMP, 15, 6, '0', '普拉提室', '/static/course/pilates_spine.jpg', '专为久坐办公人群设计,通过普拉提脊柱逐节运动改善驼背、圆肩等不良体态。融合猫牛式、脊柱旋转和游泳式,给你的脊柱一次深度保养。', 108.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '普拉提';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '产后恢复普拉提', gt.id, '2026-07-22 11:00:00'::TIMESTAMP, '2026-07-22 12:00:00'::TIMESTAMP, 10, 4, '0', '普拉提室', '/static/course/pilates_postnatal.jpg', '专为产后妈妈设计的温和修复课程,重点激活盆底肌和腹横肌,循序渐进恢复核心力量。小班教学,教练一对一关注每位学员的姿势质量。', 158.00, 'system'
SELECT '产后恢复普拉提', gt.id, '2026-07-24 11:00:00'::TIMESTAMP, '2026-07-24 12:00:00'::TIMESTAMP, 10, 4, '0', '普拉提室', '/static/course/pilates_postnatal.jpg', '专为产后妈妈设计的温和修复课程,重点激活盆底肌和腹横肌,循序渐进恢复核心力量。小班教学,教练一对一关注每位学员的姿势质量。', 158.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '普拉提';
-- ---------- 搏击操课程(5个)----------
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '有氧搏击基础', gt.id, '2026-07-21 18:00:00'::TIMESTAMP, '2026-07-21 19:00:00'::TIMESTAMP, 25, 20, '0', '操厅A', '/static/course/boxing_basic.jpg', '零基础友好的搏击操入门课。从直拳、摆拳、勾拳到前踢、侧踹,教练分步讲解每个动作的要领,配合动感音乐串联成完整的搏击组合。', 68.00, 'system'
SELECT '有氧搏击基础', gt.id, '2026-07-23 18:00:00'::TIMESTAMP, '2026-07-23 19:00:00'::TIMESTAMP, 25, 20, '0', '操厅A', '/static/course/boxing_basic.jpg', '零基础友好的搏击操入门课。从直拳、摆拳、勾拳到前踢、侧踹,教练分步讲解每个动作的要领,配合动感音乐串联成完整的搏击组合。', 68.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '搏击操';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT 'Kickboxing进阶', gt.id, '2026-07-23 19:00:00'::TIMESTAMP, '2026-07-23 20:00:00'::TIMESTAMP, 20, 15, '0', '操厅A', '/static/course/boxing_kickboxing.jpg', '融合踢拳技术的进阶搏击课程,增加连击组合、闪躲步法和膝肘技术。强度较基础课明显提升,汗如雨下的同时释放工作压力,宣泄效果一流。', 88.00, 'system'
SELECT 'Kickboxing进阶', gt.id, '2026-07-25 19:00:00'::TIMESTAMP, '2026-07-25 20:00:00'::TIMESTAMP, 20, 15, '0', '操厅A', '/static/course/boxing_kickboxing.jpg', '融合踢拳技术的进阶搏击课程,增加连击组合、闪躲步法和膝肘技术。强度较基础课明显提升,汗如雨下的同时释放工作压力,宣泄效果一流。', 88.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '搏击操';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '综合格斗体能', gt.id, '2026-07-25 16:00:00'::TIMESTAMP, '2026-07-25 17:00:00'::TIMESTAMP, 20, 12, '0', '操厅A', '/static/course/boxing_mma.jpg', '融合拳击、泰拳、摔跤元素的综合体能训练。沙袋击打、地面对抗和爆发力训练交替进行,全面提升力量、速度和耐力。周六下午的硬核之选!', 98.00, 'system'
SELECT '综合格斗体能', gt.id, '2026-07-27 16:00:00'::TIMESTAMP, '2026-07-27 17:00:00'::TIMESTAMP, 20, 12, '0', '操厅A', '/static/course/boxing_mma.jpg', '融合拳击、泰拳、摔跤元素的综合体能训练。沙袋击打、地面对抗和爆发力训练交替进行,全面提升力量、速度和耐力。周六下午的硬核之选!', 98.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '搏击操';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '燃脂拳击', gt.id, '2026-07-20 12:00:00'::TIMESTAMP, '2026-07-20 13:00:00'::TIMESTAMP, 25, 16, '0', '操厅A', '/static/course/boxing_fatburn.jpg', '午间燃脂拳击课。空击组合与沙袋击打间歇进行,心率维持在高燃脂区间。一节课可消耗500-700卡路里,中午来打拳比喝咖啡更提神!', 68.00, 'system'
SELECT '燃脂拳击', gt.id, '2026-07-22 12:00:00'::TIMESTAMP, '2026-07-22 13:00:00'::TIMESTAMP, 25, 16, '0', '操厅A', '/static/course/boxing_fatburn.jpg', '午间燃脂拳击课。空击组合与沙袋击打间歇进行,心率维持在高燃脂区间。一节课可消耗500-700卡路里,中午来打拳比喝咖啡更提神!', 68.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '搏击操';
INSERT INTO group_course (course_name, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by)
SELECT '泰拳基础', gt.id, '2026-07-26 15:00:00'::TIMESTAMP, '2026-07-26 16:00:00'::TIMESTAMP, 15, 7, '0', '操厅A', '/static/course/boxing_muaythai.jpg', '学习泰拳的八肢艺术(双拳、双腿、双膝、双肘),从基本站架到肘膝组合,感受泰拳的刚猛魅力。小班教学保证动作纠正质量。', 98.00, 'system'
SELECT '泰拳基础', gt.id, '2026-07-28 15:00:00'::TIMESTAMP, '2026-07-28 16:00:00'::TIMESTAMP, 15, 7, '0', '操厅A', '/static/course/boxing_muaythai.jpg', '学习泰拳的八肢艺术(双拳、双腿、双膝、双肘),从基本站架到肘膝组合,感受泰拳的刚猛魅力。小班教学保证动作纠正质量。', 98.00, 'system'
FROM group_course_type gt WHERE gt.type_name = '搏击操';
@@ -0,0 +1,30 @@
-- ============================================
-- 教练违规记录表
-- 版本: V23
-- 描述: 创建教练违规记录表
-- ============================================
CREATE TABLE IF NOT EXISTS coach_violation (
id BIGSERIAL PRIMARY KEY,
coach_id BIGINT NOT NULL,
course_id BIGINT NOT NULL,
violation_time TIMESTAMP NOT NULL,
violation_reason VARCHAR(50) NOT NULL,
create_by VARCHAR(50),
update_by VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
deleted_at TIMESTAMP
);
COMMENT ON TABLE coach_violation IS '教练违规记录表';
COMMENT ON COLUMN coach_violation.id IS '主键ID';
COMMENT ON COLUMN coach_violation.coach_id IS '教练ID(关联sys_user';
COMMENT ON COLUMN coach_violation.course_id IS '团课ID(关联group_course';
COMMENT ON COLUMN coach_violation.violation_time IS '违规时间';
COMMENT ON COLUMN coach_violation.violation_reason IS '违规原因(COACH_LATE-教练迟到, COACH_ABSENT-教练缺席, NOT_MANUAL_END-教练未手动结课)';
COMMENT ON COLUMN coach_violation.create_by IS '创建人';
COMMENT ON COLUMN coach_violation.update_by IS '更新人';
COMMENT ON COLUMN coach_violation.created_at IS '创建时间';
COMMENT ON COLUMN coach_violation.updated_at IS '更新时间';
COMMENT ON COLUMN coach_violation.deleted_at IS '删除时间(软删除)';
@@ -0,0 +1,82 @@
-- ============================================
-- V24: 教练测试数据
-- 描述: 创建5个教练用户并分配团课,每教练负责一种课型
-- 确保同教练的课程时间不冲突
-- ============================================
-- ============================================
-- 1. 教练用户数据(密码均为 Test@123)
-- ============================================
INSERT INTO sys_user (id, username, password, email, phone, nickname, status, create_by, update_by, created_at, updated_at)
VALUES
(11, 'coach_zhang', '$2a$12$nZ1EMUpZQljbnEdIKzH72eHlDJKUmHmHppnTTVth/SlHs5VpSAr8C', 'coach_zhang@novalon.com', '13800138011', '张教练(瑜伽)', 1, 'system', 'system', NOW(), NOW()),
(12, 'coach_li', '$2a$12$nZ1EMUpZQljbnEdIKzH72eHlDJKUmHmHppnTTVth/SlHs5VpSAr8C', 'coach_li@novalon.com', '13800138012', '李教练(动感单车)', 1, 'system', 'system', NOW(), NOW()),
(13, 'coach_wang', '$2a$12$nZ1EMUpZQljbnEdIKzH72eHlDJKUmHmHppnTTVth/SlHs5VpSAr8C', 'coach_wang@novalon.com', '13800138013', '王教练(HIIT', 1, 'system', 'system', NOW(), NOW()),
(14, 'coach_zhao', '$2a$12$nZ1EMUpZQljbnEdIKzH72eHlDJKUmHmHppnTTVth/SlHs5VpSAr8C', 'coach_zhao@novalon.com', '13800138014', '赵教练(普拉提)', 1, 'system', 'system', NOW(), NOW()),
(15, 'coach_chen', '$2a$12$nZ1EMUpZQljbnEdIKzH72eHlDJKUmHmHppnTTVth/SlHs5VpSAr8C', 'coach_chen@novalon.com', '13800138015', '陈教练(搏击操)', 1, 'system', 'system', NOW(), NOW())
ON CONFLICT (username) DO UPDATE SET
password = EXCLUDED.password,
status = EXCLUDED.status;
SELECT setval('sys_user_id_seq', 15);
-- ============================================
-- 2. 分配教练角色(role_id=5
-- ============================================
INSERT INTO user_role (user_id, role_id, created_by, created_at)
VALUES
(11, 5, 'system', NOW()),
(12, 5, 'system', NOW()),
(13, 5, 'system', NOW()),
(14, 5, 'system', NOW()),
(15, 5, 'system', NOW())
ON CONFLICT (user_id, role_id) DO NOTHING;
-- ============================================
-- 3. 为团课分配教练(按课型,无时间冲突)
-- coach_id=11 张教练: 瑜伽 5门
-- coach_id=12 李教练: 动感单车 5门
-- coach_id=13 王教练: HIIT训练 5门
-- coach_id=14 赵教练: 普拉提 5门
-- coach_id=15 陈教练: 搏击操 5门
-- ============================================
-- 瑜伽课程 → 张教练(11)
UPDATE group_course SET coach_id = 11, updated_at = NOW()
WHERE course_type = (SELECT id FROM group_course_type WHERE type_name = '瑜伽')
AND deleted_at IS NULL;
-- 动感单车课程 → 李教练(12)
UPDATE group_course SET coach_id = 12, updated_at = NOW()
WHERE course_type = (SELECT id FROM group_course_type WHERE type_name = '动感单车')
AND deleted_at IS NULL;
-- HIIT训练课程 → 王教练(13)
UPDATE group_course SET coach_id = 13, updated_at = NOW()
WHERE course_type = (SELECT id FROM group_course_type WHERE type_name = 'HIIT训练')
AND deleted_at IS NULL;
-- 普拉提课程 → 赵教练(14)
UPDATE group_course SET coach_id = 14, updated_at = NOW()
WHERE course_type = (SELECT id FROM group_course_type WHERE type_name = '普拉提')
AND deleted_at IS NULL;
-- 搏击操课程 → 陈教练(15)
UPDATE group_course SET coach_id = 15, updated_at = NOW()
WHERE course_type = (SELECT id FROM group_course_type WHERE type_name = '搏击操')
AND deleted_at IS NULL;
-- ============================================
-- 4. 验证:确认每个团课都有教练
-- ============================================
DO $$
DECLARE
null_count INTEGER;
BEGIN
SELECT COUNT(*) INTO null_count FROM group_course WHERE coach_id IS NULL AND deleted_at IS NULL;
IF null_count > 0 THEN
RAISE NOTICE '警告:仍有 % 门团课缺少教练', null_count;
ELSE
RAISE NOTICE '所有团课已成功分配教练';
END IF;
END $$;
@@ -53,7 +53,7 @@ COMMENT ON COLUMN group_course.start_time IS '开始时间';
COMMENT ON COLUMN group_course.end_time IS '结束时间';
COMMENT ON COLUMN group_course.max_members IS '最大参与人数';
COMMENT ON COLUMN group_course.current_members IS '当前参与人数';
COMMENT ON COLUMN group_course.status IS '状态(0正常 1已取消 2已结束 3进行中 4超时)';
COMMENT ON COLUMN group_course.status IS '状态(0正常 1已取消 2已结束 3进行中 4超时 5教练缺席 6自动结束 7教练迟到';
COMMENT ON COLUMN group_course.actual_start_time IS '实际开课时间(教练点击开课时记录)';
COMMENT ON COLUMN group_course.actual_end_time IS '实际结课时间(教练点击结课时记录)';
COMMENT ON COLUMN group_course.location IS '上课地点';
@@ -72,7 +72,7 @@ COMMENT ON COLUMN group_course_booking.course_id IS '团课ID';
COMMENT ON COLUMN group_course_booking.member_id IS '用户ID';
COMMENT ON COLUMN group_course_booking.member_card_id IS '会员卡ID';
COMMENT ON COLUMN group_course_booking.booking_time IS '预约时间';
COMMENT ON COLUMN group_course_booking.status IS '状态(0已预约 1已取消 2已出席 3缺席)';
COMMENT ON COLUMN group_course_booking.status IS '状态(0已预约 1已取消 2已出席 3缺席 4教练缺席 5迟到';
COMMENT ON COLUMN group_course_booking.cancel_time IS '取消时间';
COMMENT ON COLUMN group_course_booking.create_by IS '创建人';
COMMENT ON COLUMN group_course_booking.update_by IS '更新人';
@@ -66,7 +66,8 @@ public class SecurityConfig {
.pathMatchers("/api/payment/query").permitAll()
.pathMatchers("/api/payment/notify").permitAll()
.pathMatchers("/api/payment/refund").permitAll()
.pathMatchers("/api/files/**").permitAll();
.pathMatchers("/api/files/**").permitAll()
.pathMatchers("/api/coach/**").permitAll();
if (isDevOrTest) {
spec.pathMatchers("/swagger-ui.html").permitAll()
+1
View File
@@ -48,6 +48,7 @@
<module>gym-dataCount</module>
<module>gym-auth</module>
<module>gym-payment</module>
<module>gym-coach</module>
</modules>
<dependencyManagement>
+4
View File
@@ -0,0 +1,4 @@
node_modules/
unpackage/
.hbuilderx/
.DS_Store
+25
View File
@@ -0,0 +1,25 @@
<script>
export default {
onLaunch: function() {
console.log('Coach App Launch')
},
onShow: function() {
console.log('Coach App Show')
},
onHide: function() {
console.log('Coach App Hide')
}
}
</script>
<style>
page {
background: #F5F7FA;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
color: #1E1E1E;
font-size: 14px;
}
view, text, button, input {
box-sizing: border-box;
}
</style>
+52
View File
@@ -0,0 +1,52 @@
const http = require('../utils/request')
/**
* 教练登录(账号密码)
*/
function login(username, password) {
return http.post('/auth/login', { username, password })
}
/**
* 获取教练负责的团课列表
*/
function getCoachCourses(coachId) {
return http.get('/coach/' + coachId + '/courses')
}
/**
* 教练手动开课
*/
function startCourse(courseId) {
return http.post('/coach/courses/' + courseId + '/start')
}
/**
* 教练手动结课
*/
function endCourse(courseId) {
return http.post('/coach/courses/' + courseId + '/end')
}
/**
* 获取团课详情
*/
function getCourseDetail(courseId) {
return http.get('/groupCourse/' + courseId + '/detail')
}
/**
* 获取教练违规记录
*/
function getCoachViolations(coachId) {
return http.get('/coach/' + coachId + '/violations')
}
module.exports = {
login,
getCoachCourses,
startCourse,
endCourse,
getCourseDetail,
getCoachViolations
}
+20
View File
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
import App from './App'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif
+64
View File
@@ -0,0 +1,64 @@
{
"name" : "gym-manage-coach-uniapp",
"appid" : "",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"transformPx" : false,
"app-plus" : {
"usingComponents" : true,
"nvueStyleCompiler" : "uni-app",
"compilerVersion" : 3,
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
},
"modules" : {},
"distribute" : {
"android" : {
"permissions" : [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
"ios" : {},
"sdkConfigs" : {}
}
},
"quickapp" : {},
"mp-weixin" : {
"appid" : "",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true
},
"mp-alipay" : {
"usingComponents" : true
},
"mp-baidu" : {
"usingComponents" : true
},
"mp-toutiao" : {
"usingComponents" : true
},
"uniStatistics" : {
"enable" : false
},
"vueVersion" : "2"
}
+45
View File
@@ -0,0 +1,45 @@
{
"name": "gym-manage-coach-uniapp",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gym-manage-coach-uniapp",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@dcloudio/uni-ui": "^1.5.12",
"crypto-js": "^4.2.0",
"luch-request": "^3.1.1"
}
},
"node_modules/@dcloudio/types": {
"version": "2.6.12",
"resolved": "https://registry.npmjs.org/@dcloudio/types/-/types-2.6.12.tgz",
"integrity": "sha512-mrCMwcINy1IFjU9VUqLeWBkj404yWs5paLDttBcA+eqUjanuUQbBcTVPqlrGgkyzLXDcV2oDDZRSNxNpXi4kMQ==",
"license": "Apache-2.0"
},
"node_modules/@dcloudio/uni-ui": {
"version": "1.5.12",
"resolved": "https://registry.npmjs.org/@dcloudio/uni-ui/-/uni-ui-1.5.12.tgz",
"integrity": "sha512-mGDl2OZSz7D8xcUAzJegWDHOqB4MEFBSW9Esb/oJiu2/3Gk9+P/Z4bA4JZ9jv9VWBYbMrYwaTfK1Z728kABdYg==",
"license": "Apache-2.0"
},
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
},
"node_modules/luch-request": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/luch-request/-/luch-request-3.1.1.tgz",
"integrity": "sha512-p7+mlcEtgRcd0OfXC4XZbyiwSr1XgCeqNT7LlVUjnk7InYl/8d5Rk7BUqAYNA2WRafI1wRIUQWRWZRpeUwWR0w==",
"license": "MIT",
"dependencies": {
"@dcloudio/types": "^2.0.16"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "gym-manage-coach-uniapp",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"@dcloudio/uni-ui": "^1.5.12",
"crypto-js": "^4.2.0",
"luch-request": "^3.1.1"
}
}
+48
View File
@@ -0,0 +1,48 @@
{
"pages": [
{
"path": "pages/login/login",
"style": {
"navigationBarTitleText": "教练登录",
"navigationStyle": "custom"
}
},
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "教练首页",
"navigationStyle": "custom",
"enablePullDownRefresh": true
}
},
{
"path": "pages/course-list/course-list",
"style": {
"navigationBarTitleText": "我的团课",
"navigationStyle": "custom",
"enablePullDownRefresh": true
}
},
{
"path": "pages/course-detail/course-detail",
"style": {
"navigationBarTitleText": "课程详情",
"navigationStyle": "custom"
}
},
{
"path": "pages/profile/profile",
"style": {
"navigationBarTitleText": "个人中心",
"navigationStyle": "custom"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "white",
"navigationBarTitleText": "Novalon教练端",
"navigationBarBackgroundColor": "#1A1A1A",
"backgroundColor": "#F5F7FA"
},
"uniIdRouter": {}
}
@@ -0,0 +1,428 @@
<template>
<view class="detail-page">
<view class="header-wrap" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="nav-bar" :style="{ height: navBarHeight + 'px' }">
<text class="back-btn" @click="goBack">&#8592;</text>
<text class="nav-title">课程详情</text>
</view>
</view>
<!-- 封面区 -->
<view class="cover-area">
<image v-if="course.coverImage && !loading" class="cover-img" :src="course.coverImage" mode="aspectFill"
@error="course.coverError = true" />
<view v-if="!course.coverImage || course.coverError || loading" class="cover-bg">
<text class="cover-text">{{ (course.typeName ? course.typeName.slice(0, 2) : '团课') }}</text>
</view>
<view class="cover-status" :class="courseStatusClass" v-if="!loading">
<text>{{ courseStatusText }}</text>
</view>
</view>
<scroll-view class="content" scroll-y :style="{ height: 'calc(100vh - ' + totalHeaderHeight + 'px - 200px)' }">
<view class="content-inner" v-if="!loading">
<!-- 课程名称 -->
<view class="title-row">
<text class="detail-title">{{ course.courseName }}</text>
</view>
<!-- 信息卡片 -->
<view class="info-card">
<view class="info-item">
<text class="info-label">时间</text>
<text class="info-value">{{ formatDate(course.startTime) }} {{ formatTime(course.startTime) }} - {{ formatTime(course.endTime) }}</text>
</view>
<view class="info-item">
<text class="info-label">时长</text>
<text class="info-value">{{ duration }}</text>
</view>
<view class="info-item">
<text class="info-label">地点</text>
<text class="info-value">{{ course.location || '未设置' }}</text>
</view>
<view class="info-item">
<text class="info-label">人数</text>
<text class="info-value">{{ course.currentMembers || 0 }} / {{ course.maxMembers || 0 }}</text>
</view>
<view class="info-item" v-if="course.storedValueAmount">
<text class="info-label">消耗</text>
<text class="info-value price-text">¥{{ course.storedValueAmount }}</text>
</view>
</view>
<!-- 课程介绍 -->
<view class="desc-card" v-if="course.description">
<text class="desc-title">课程介绍</text>
<text class="desc-content">{{ course.description }}</text>
</view>
<!-- 操作区 -->
<view class="action-area">
<button
v-if="course.status == 0"
class="action-btn start-btn"
:class="{ disabled: !canStartCourse }"
:loading="actionLoading"
:disabled="actionLoading || !canStartCourse"
@click="handleStartCourse"
>
{{ actionLoading ? '开课中...' : (canStartCourse ? '开 课' : '尚未到开课时间') }}
</button>
<button
v-if="course.status == 3 || course.status == 7"
class="action-btn end-btn"
:class="{ disabled: !canEndCourse }"
:loading="actionLoading"
:disabled="actionLoading || !canEndCourse"
@click="handleEndCourse"
>
{{ actionLoading ? '结课中...' : (canEndCourse ? '结 课' : '尚未到结课时间') }}
</button>
<button
v-if="course.status != 0 && course.status != 3 && course.status != 7"
class="action-btn disabled-btn"
disabled
>
不可操作
</button>
</view>
<view class="bottom-safe"></view>
</view>
<view v-else class="loading-wrap">
<text class="loading-text">加载中...</text>
</view>
</scroll-view>
</view>
</template>
<script>
const coachApi = require('../../api/coach')
const store = require('../../store/index')
const { resolveCoverUrl } = require('../../utils/request')
export default {
data() {
return {
statusBarHeight: 0,
navBarHeight: 44,
totalHeaderHeight: 44,
courseId: '',
loading: true,
actionLoading: false,
course: {},
now: Date.now()
}
},
computed: {
duration() {
if (!this.course.startTime || !this.course.endTime) return '--'
const start = new Date(this.course.startTime).getTime()
const end = new Date(this.course.endTime).getTime()
const mins = Math.round((end - start) / 60000)
if (mins < 60) return mins + '分钟'
return Math.floor(mins / 60) + '小时' + (mins % 60 > 0 ? mins % 60 + '分钟' : '')
},
canStartCourse() {
return (this.course.status == 0) && this.now >= new Date(this.course.startTime || 0).getTime()
},
canEndCourse() {
return (this.course.status == 3 || this.course.status == 7) && this.now >= new Date(this.course.endTime || 0).getTime()
},
courseStatusClass() {
const map = { 0: 'normal', 1: 'cancelled', 2: 'ended', 3: 'in-progress', 4: 'timeout', 5: 'absent', 6: 'auto-ended', 7: 'late' }
return map[this.course.status] || ''
},
courseStatusText() {
const labels = { 0: '正常', 1: '已取消', 2: '已结束', 3: '进行中', 4: '超时', 5: '教练缺席', 6: '自动结束', 7: '教练迟到' }
return labels[this.course.status] || '未知'
}
},
onLoad(options) {
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = systemInfo.statusBarHeight || 20
let navBarHeight = 44
// #ifdef MP-WEIXIN
const menuButton = uni.getMenuButtonBoundingClientRect()
if (menuButton) {
navBarHeight = (menuButton.top - statusBarHeight) * 2 + menuButton.height
}
// #endif
this.statusBarHeight = statusBarHeight
this.navBarHeight = navBarHeight
this.totalHeaderHeight = statusBarHeight + navBarHeight
if (options && options.id) {
this.courseId = options.id
this.loadDetail()
}
},
onShow() {
if (!store.isLoggedIn) {
uni.reLaunch({ url: '/pages/login/login' })
}
},
methods: {
goBack() { uni.navigateBack() },
async loadDetail() {
this.loading = true
try {
const data = await coachApi.getCourseDetail(this.courseId)
this.course = {
...(data || {}),
coverImage: resolveCoverUrl((data || {}).coverImage),
coverError: false
}
this.now = Date.now()
} catch (e) {
console.error('加载课程详情失败:', e)
uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
this.loading = false
}
},
async handleStartCourse() {
if (this.actionLoading) return
this.now = Date.now()
if (!this.canStartCourse) {
uni.showToast({ title: '尚未到课程预计开始时间,无法开课', icon: 'none', duration: 3000 })
return
}
this.actionLoading = true
try {
await coachApi.startCourse(this.courseId)
uni.showToast({ title: '开课成功', icon: 'success' })
// 刷新课程详情
await this.loadDetail()
} catch (err) {
console.error('开课失败:', err)
let msg = '开课失败'
if (err && err.data && err.data.message) {
msg = err.data.message
} else if (err && err.message) {
msg = err.message
}
uni.showToast({ title: msg, icon: 'none', duration: 3000 })
} finally {
this.actionLoading = false
}
},
async handleEndCourse() {
if (this.actionLoading) return
this.now = Date.now()
if (!this.canEndCourse) {
uni.showToast({ title: '尚未到课程预计结束时间,无法结课', icon: 'none', duration: 3000 })
return
}
this.actionLoading = true
try {
await coachApi.endCourse(this.courseId)
uni.showToast({ title: '结课成功', icon: 'success' })
await this.loadDetail()
} catch (err) {
console.error('结课失败:', err)
let msg = '结课失败'
if (err && err.data && err.data.message) {
msg = err.data.message
} else if (err && err.message) {
msg = err.message
}
uni.showToast({ title: msg, icon: 'none', duration: 3000 })
} finally {
this.actionLoading = false
}
},
formatDate(timeStr) {
if (!timeStr) return '--'
return timeStr.substring(0, 10)
},
formatTime(timeStr) {
if (!timeStr) return '--'
return timeStr.substring(11, 16)
}
}
}
</script>
<style scoped>
.detail-page {
min-height: 100vh;
background: #F5F7FA;
overflow-x: hidden;
}
.header-wrap {
background: #1A1A1A;
}
.nav-bar {
padding: 0 16px;
display: flex;
align-items: center;
}
.back-btn {
font-size: 20px;
color: #FFFFFF;
margin-right: 12px;
}
.nav-title {
font-size: 18px;
font-weight: 700;
color: #FFFFFF;
}
.content-inner {
padding: 0 14px;
}
.loading-wrap {
display: flex;
justify-content: center;
padding: 60px 0;
}
.loading-text {
font-size: 14px;
color: #7A7E84;
}
/* 封面区 */
.cover-area { height: 200px; position: relative; overflow: hidden; }
.cover-img { width: 100%; height: 100%; }
.cover-bg { width: 100%; height: 100%; background: linear-gradient(135deg, #00C853, #00BFA5); display: flex; align-items: center; justify-content: center; }
.cover-text { font-size: 56px; font-weight: 700; color: rgba(255,255,255,0.9); }
.cover-status {
position: absolute;
top: 14px;
right: 14px;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.cover-status.normal, .cover-status.in-progress, .cover-status.late {
background: rgba(255,255,255,0.25);
color: #FFFFFF;
}
.cover-status.ended, .cover-status.auto-ended {
background: rgba(255,255,255,0.2);
color: rgba(255,255,255,0.8);
}
.cover-status.cancelled, .cover-status.timeout, .cover-status.absent {
background: rgba(244,67,54,0.2);
color: #FFCDD2;
}
/* 课程名称 */
.title-row {
padding: 0 4px;
margin-bottom: 12px;
}
.detail-title {
font-size: 20px;
font-weight: 700;
color: #1E1E1E;
}
/* 信息卡片 */
.info-card {
background: #FFFFFF;
border-radius: 16px;
padding: 16px;
margin-bottom: 14px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.info-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #F0F0F0;
}
.info-item:last-child {
border-bottom: none;
}
.info-label {
font-size: 14px;
color: #7A7E84;
}
.info-value {
font-size: 14px;
color: #1E1E1E;
font-weight: 500;
text-align: right;
flex: 1;
margin-left: 12px;
}
.price-text {
color: #00C853;
font-weight: 700;
font-size: 16px;
}
/* 课程介绍 */
.desc-card {
background: #FFFFFF;
border-radius: 16px;
padding: 16px;
margin-bottom: 14px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.desc-title {
font-size: 16px;
font-weight: 700;
color: #1E1E1E;
display: block;
margin-bottom: 8px;
}
.desc-content {
font-size: 14px;
color: #7A7E84;
line-height: 1.6;
}
/* 操作区 */
.action-area {
padding: 10px 0 20px;
}
.action-btn {
width: 100%;
height: 50px;
border-radius: 40px;
font-size: 17px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
border: none;
}
.action-btn::after { border: none; }
.start-btn {
background: #00E676;
color: #1A1A1A;
box-shadow: 0 4px 16px rgba(0,230,118,0.35);
}
.start-btn.disabled {
background: #E0E0E0;
color: #9E9E9E;
box-shadow: none;
}
.end-btn {
background: #FF9800;
color: #FFFFFF;
box-shadow: 0 4px 16px rgba(255,152,0,0.35);
}
.end-btn.disabled {
background: #E0E0E0;
color: #9E9E9E;
box-shadow: none;
}
.disabled-btn {
background: #E0E0E0;
color: #9E9E9E;
}
.bottom-safe {
height: 30px;
}
</style>
@@ -0,0 +1,292 @@
<template>
<view class="course-list-page">
<view class="header-wrap" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="nav-bar" :style="{ height: navBarHeight + 'px' }">
<text class="back-btn" @click="goBack">&#8592;</text>
<text class="nav-title">我的团课</text>
</view>
<!-- 状态筛选 Tab -->
<view class="tab-row">
<view
v-for="(tab, idx) in tabs"
:key="idx"
class="tab-item"
:class="{ active: currentTab === tab.value }"
@click="switchTab(tab.value)"
>
<text>{{ tab.label }}</text>
</view>
</view>
</view>
<scroll-view class="content" scroll-y :style="{ height: 'calc(100vh - ' + totalHeaderHeight + 'px)' }">
<view class="content-inner">
<view v-if="loading" class="loading-wrap">
<text class="loading-text">加载中...</text>
</view>
<view v-else-if="filteredCourses.length === 0" class="empty-wrap">
<text class="empty-text">暂无课程</text>
</view>
<view v-else class="course-list">
<view v-for="course in filteredCourses" :key="course.id" class="course-card" :class="{ grayed: !course._isToday }" @click="goToDetail(course.id)">
<view class="card-header">
<text class="course-name">{{ course.courseName }}</text>
<view class="status-tag" :class="course._statusClass">
<text>{{ course._statusLabel }}</text>
</view>
</view>
<view class="card-info">
<view class="info-row">
<text class="info-label">时间</text>
<text class="info-value">{{ formatDate(course.startTime) }} {{ formatTime(course.startTime) }} - {{ formatTime(course.endTime) }}</text>
</view>
<view class="info-row">
<text class="info-label">地点</text>
<text class="info-value">{{ course.location || '未设置' }}</text>
</view>
<view class="info-row">
<text class="info-label">人数</text>
<text class="info-value">{{ course.currentMembers || 0 }} / {{ course.maxMembers || 0 }}</text>
</view>
</view>
</view>
</view>
<view class="bottom-safe"></view>
</view>
</scroll-view>
</view>
</template>
<script>
const coachApi = require('../../api/coach')
const store = require('../../store/index')
export default {
data() {
return {
statusBarHeight: 0,
navBarHeight: 44,
totalHeaderHeight: 0,
loading: true,
courses: [],
currentTab: 'all',
tabs: [
{ label: '全部', value: 'all' },
{ label: '待开课', value: 'pending' },
{ label: '进行中', value: 'in_progress' },
{ label: '已结束', value: 'ended' }
]
}
},
computed: {
filteredCourses() {
switch (this.currentTab) {
case 'pending':
return this.courses.filter(c => c.status == 0)
case 'in_progress':
return this.courses.filter(c => c.status == 3 || c.status == 7)
case 'ended':
return this.courses.filter(c => c.status == 2 || c.status == 6 || c.status == 1 || c.status == 4 || c.status == 5)
default:
return this.courses
}
}
},
onLoad() {
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = systemInfo.statusBarHeight || 20
let navBarHeight = 44
// #ifdef MP-WEIXIN
const menuButton = uni.getMenuButtonBoundingClientRect()
if (menuButton) {
navBarHeight = (menuButton.top - statusBarHeight) * 2 + menuButton.height
}
// #endif
this.statusBarHeight = statusBarHeight
this.navBarHeight = navBarHeight
// 状态栏 + 导航栏 + tab行高度
this.totalHeaderHeight = statusBarHeight + navBarHeight + 44
},
onShow() {
if (!store.isLoggedIn) {
uni.reLaunch({ url: '/pages/login/login' })
return
}
this.loadCourses()
},
methods: {
goBack() { uni.navigateBack() },
goToDetail(id) {
uni.navigateTo({ url: '/pages/course-detail/course-detail?id=' + id })
},
switchTab(value) { this.currentTab = value },
async loadCourses() {
this.loading = true
try {
const coachId = store.getCoachId()
if (!coachId) return
const result = await coachApi.getCoachCourses(coachId)
const list = Array.isArray(result) ? result : (result && result.content ? result.content : [])
// 预计算状态 class 和 labeluni-app 模板不支持 :class 中调用方法
const classMap = { 0: 'normal', 1: 'cancelled', 2: 'ended', 3: 'in-progress', 4: 'timeout', 5: 'absent', 6: 'auto-ended', 7: 'late' }
const labelMap = { 0: '正常', 1: '已取消', 2: '已结束', 3: '进行中', 4: '超时', 5: '教练缺席', 6: '自动结束', 7: '教练迟到' }
const todayStr = new Date().toISOString().substring(0, 10)
this.courses = list
.map(c => ({
...c,
_statusClass: classMap[c.status] || '',
_statusLabel: labelMap[c.status] || '未知',
_isToday: (c.startTime || '').substring(0, 10) === todayStr
}))
.sort((a, b) => {
if (a._isToday && !b._isToday) return -1
if (!a._isToday && b._isToday) return 1
return 0
})
} catch (e) {
console.error('加载课程失败:', e)
uni.showToast({ title: '加载课程失败', icon: 'none' })
} finally {
this.loading = false
}
},
formatDate(timeStr) {
if (!timeStr) return '--'
return timeStr.substring(0, 10)
},
formatTime(timeStr) {
if (!timeStr) return '--'
return timeStr.substring(11, 16)
},
}
}
</script>
<style scoped>
.course-list-page {
min-height: 100vh;
background: #F5F7FA;
overflow-x: hidden;
}
.header-wrap {
background: #1A1A1A;
}
.nav-bar {
padding: 0 16px;
display: flex;
align-items: center;
}
.back-btn {
font-size: 20px;
color: #FFFFFF;
margin-right: 12px;
}
.nav-title {
font-size: 18px;
font-weight: 700;
color: #FFFFFF;
}
/* Tab 筛选 */
.tab-row {
display: flex;
padding: 8px 16px 10px;
}
.tab-item {
padding: 6px 16px;
border-radius: 20px;
margin-right: 8px;
font-size: 13px;
color: rgba(255,255,255,0.6);
background: rgba(255,255,255,0.1);
}
.tab-item.active {
color: #1A1A1A;
background: #00E676;
font-weight: 600;
}
/* 内容区 */
.content-inner {
padding: 14px 14px 0;
}
.loading-wrap, .empty-wrap {
display: flex;
justify-content: center;
padding: 60px 0;
}
.loading-text, .empty-text {
font-size: 14px;
color: #7A7E84;
}
/* 课程卡片 */
.course-card {
background: #FFFFFF;
border-radius: 16px;
padding: 16px;
margin-bottom: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.course-name {
font-size: 16px;
font-weight: 700;
color: #1E1E1E;
flex: 1;
}
.status-tag {
padding: 3px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
}
.status-tag.normal { background: rgba(0,230,118,0.15); color: #00C853; }
.status-tag.in-progress, .status-tag.late { background: rgba(33,150,243,0.15); color: #2196F3; }
.status-tag.ended, .status-tag.auto-ended { background: rgba(158,158,158,0.15); color: #9E9E9E; }
.status-tag.cancelled { background: rgba(255,152,0,0.15); color: #FF9800; }
.status-tag.timeout { background: rgba(244,67,54,0.15); color: #F44336; }
.status-tag.absent { background: rgba(244,67,54,0.15); color: #F44336; }
.card-info {
background: #F5F7FA;
border-radius: 10px;
padding: 10px 12px;
}
.info-row {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
}
.info-row:last-child {
margin-bottom: 0;
}
.info-label {
font-size: 12px;
color: #7A7E84;
}
.info-value {
font-size: 13px;
color: #1E1E1E;
font-weight: 500;
}
/* 操作按钮 - 已移除,仅保留按钮样式供可能复用 */
.course-card.grayed {
opacity: 0.5;
pointer-events: auto;
}
.bottom-safe {
height: 20px;
}
</style>
@@ -0,0 +1,282 @@
<template>
<view class="home-page">
<view class="header-wrap" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="nav-bar" :style="{ height: navBarHeight + 'px' }">
<text class="nav-title"> Novalon 教练端</text>
</view>
</view>
<scroll-view class="content" scroll-y :style="{ height: 'calc(100vh - ' + totalHeaderHeight + 'px)' }">
<view class="content-inner">
<!-- 教练欢迎卡片 -->
<view class="greeting-card">
<view class="greeting-text">
<text class="greeting-label">{{ greetingLabel }}</text>
<text class="coach-name">{{ coachName }} 教练</text>
</view>
<view class="greeting-desc">
<text>祝您今日授课顺利</text>
</view>
</view>
<!-- 今日统计 -->
<view class="stats-card">
<view class="stat-item">
<text class="stat-number">{{ todayStats.pending }}</text>
<text class="stat-label">待开课</text>
</view>
<view class="stat-divider"></view>
<view class="stat-item">
<text class="stat-number">{{ todayStats.inProgress }}</text>
<text class="stat-label">进行中</text>
</view>
<view class="stat-divider"></view>
<view class="stat-item">
<text class="stat-number">{{ todayStats.ended }}</text>
<text class="stat-label">已结束</text>
</view>
</view>
<!-- 功能入口 -->
<view class="section-header">
<text class="section-title">快捷功能</text>
</view>
<view class="entry-grid">
<view class="entry-card" @click="goToCourseList">
<view class="entry-icon-wrap green-bg">
<text class="entry-icon">&#9776;</text>
</view>
<text class="entry-name">我的团课</text>
<text class="entry-desc">查看和管理课程</text>
</view>
<view class="entry-card" @click="goToProfile">
<view class="entry-icon-wrap dark-bg">
<text class="entry-icon">&#9786;</text>
</view>
<text class="entry-name">个人中心</text>
<text class="entry-desc">信息与违规记录</text>
</view>
</view>
<view class="bottom-safe"></view>
</view>
</scroll-view>
</view>
</template>
<script>
const store = require('../../store/index')
const coachApi = require('../../api/coach')
export default {
data() {
return {
statusBarHeight: 0,
navBarHeight: 44,
totalHeaderHeight: 44,
coachName: '加载中...',
todayStats: {
pending: 0,
inProgress: 0,
ended: 0
}
}
},
computed: {
greetingLabel() {
const hour = new Date().getHours()
if (hour < 6) return '夜深了,'
if (hour < 12) return '早上好,'
if (hour < 18) return '下午好,'
return '晚上好,'
}
},
onLoad() {
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = systemInfo.statusBarHeight || 20
let navBarHeight = 44
// #ifdef MP-WEIXIN
const menuButton = uni.getMenuButtonBoundingClientRect()
if (menuButton) {
navBarHeight = (menuButton.top - statusBarHeight) * 2 + menuButton.height
}
// #endif
this.statusBarHeight = statusBarHeight
this.navBarHeight = navBarHeight
this.totalHeaderHeight = statusBarHeight + navBarHeight
},
onShow() {
if (!store.isLoggedIn) {
uni.reLaunch({ url: '/pages/login/login' })
return
}
this.coachName = store.getUsername() || '教练'
this.loadStats()
},
onPullDownRefresh() {
this.loadStats().finally(() => { uni.stopPullDownRefresh() })
},
methods: {
goToCourseList() {
uni.navigateTo({ url: '/pages/course-list/course-list' })
},
goToProfile() {
uni.navigateTo({ url: '/pages/profile/profile' })
},
async loadStats() {
try {
const coachId = store.getCoachId()
if (!coachId) return
const courses = await coachApi.getCoachCourses(coachId)
const list = Array.isArray(courses) ? courses : (courses && courses.content ? courses.content : [])
this.todayStats = {
pending: list.filter(c => c.status == 0).length,
inProgress: list.filter(c => c.status == 3 || c.status == 7).length,
ended: list.filter(c => c.status == 2 || c.status == 6).length
}
} catch (e) {
console.error('加载统计失败:', e)
}
}
}
}
</script>
<style scoped>
.home-page {
min-height: 100vh;
background: #F5F7FA;
overflow-x: hidden;
}
.header-wrap {
background: #1A1A1A;
}
.nav-bar {
background: #1A1A1A;
padding: 0 20px;
display: flex;
align-items: center;
}
.nav-title {
font-size: 18px;
font-weight: 700;
color: #FFFFFF;
}
.content-inner {
padding: 16px;
}
/* 欢迎卡片 */
.greeting-card {
background: #1A1A1A;
border-radius: 20px;
padding: 20px;
color: #FFFFFF;
margin-bottom: 16px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.greeting-text {
display: flex;
align-items: baseline;
}
.greeting-label {
font-size: 16px;
color: rgba(255,255,255,0.7);
}
.coach-name {
font-size: 22px;
font-weight: 700;
color: #00E676;
}
.greeting-desc {
margin-top: 6px;
font-size: 13px;
color: rgba(255,255,255,0.5);
}
/* 统计卡片 */
.stats-card {
background: #FFFFFF;
border-radius: 20px;
padding: 18px 20px;
display: flex;
justify-content: space-around;
margin-bottom: 20px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.stat-item {
display: flex;
flex-direction: column;
align-items: center;
}
.stat-number {
font-size: 28px;
font-weight: 700;
color: #00C853;
}
.stat-label {
font-size: 12px;
color: #7A7E84;
margin-top: 4px;
}
.stat-divider {
width: 1px;
background: #EEEEEE;
}
/* 功能入口 */
.section-header {
margin-bottom: 14px;
}
.section-title {
font-size: 18px;
font-weight: 700;
color: #1E1E1E;
}
.entry-grid {
display: flex;
justify-content: space-between;
}
.entry-card {
width: calc(50% - 6px);
background: #FFFFFF;
border-radius: 20px;
padding: 20px 16px;
display: flex;
flex-direction: column;
align-items: center;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.entry-icon-wrap {
width: 56px;
height: 56px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 10px;
}
.entry-icon-wrap.green-bg {
background: rgba(0,230,118,0.15);
}
.entry-icon-wrap.dark-bg {
background: rgba(26,26,26,0.1);
}
.entry-icon {
font-size: 24px;
color: #00C853;
}
.entry-name {
font-size: 16px;
font-weight: 600;
color: #1E1E1E;
margin-bottom: 4px;
}
.entry-desc {
font-size: 12px;
color: #7A7E84;
}
.bottom-safe {
height: 20px;
}
</style>
@@ -0,0 +1,217 @@
<template>
<view class="login-page" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="brand-area">
<view class="logo-icon">
<text class="logo-symbol"></text>
</view>
<text class="app-name">Novalon 教练端</text>
<text class="app-slogan">高效管理 · 轻松授课</text>
</view>
<view class="login-form">
<view class="input-group">
<text class="input-icon">&#128100;</text>
<input
class="login-input"
type="text"
v-model="username"
placeholder="请输入教练账号"
placeholder-style="color: #BDBDBD"
/>
</view>
<view class="input-group">
<text class="input-icon">&#128274;</text>
<input
class="login-input"
:type="showPassword ? 'text' : 'password'"
v-model="password"
placeholder="请输入密码"
placeholder-style="color: #BDBDBD"
/>
<text class="toggle-pwd" @click="showPassword = !showPassword">
{{ showPassword ? '&#128065;' : '&#128064;' }}
</text>
</view>
<button class="login-btn" :loading="loading" :disabled="loading || !username || !password" @click="handleLogin">
{{ loading ? '登录中...' : ' ' }}
</button>
</view>
<view class="footer-tip">
<text>Novalon 健身房管理系统</text>
</view>
</view>
</template>
<script>
const coachApi = require('../../api/coach')
const store = require('../../store/index')
export default {
data() {
return {
statusBarHeight: 0,
username: '',
password: '',
showPassword: false,
loading: false
}
},
onLoad() {
const systemInfo = uni.getSystemInfoSync()
this.statusBarHeight = systemInfo.statusBarHeight || 20
if (store.isLoggedIn) {
uni.reLaunch({ url: '/pages/index/index' })
}
},
methods: {
async handleLogin() {
if (!this.username.trim()) {
uni.showToast({ title: '请输入教练账号', icon: 'none' })
return
}
if (!this.password) {
uni.showToast({ title: '请输入密码', icon: 'none' })
return
}
if (this.loading) return
this.loading = true
try {
const res = await coachApi.login(this.username.trim(), this.password)
if (res && res.token) {
store.setLogin(res.token, {
coachId: res.userId,
username: res.username
})
uni.showToast({ title: '登录成功', icon: 'success' })
setTimeout(() => {
uni.reLaunch({ url: '/pages/index/index' })
}, 500)
} else {
uni.showToast({ title: '登录失败:账号或密码错误', icon: 'none' })
}
} catch (err) {
console.error('登录失败:', err)
let msg = '登录失败,请重试'
if (err && err.data && err.data.message) {
msg = err.data.message
} else if (err && err.message) {
msg = err.message
}
uni.showToast({ title: msg, icon: 'none' })
} finally {
this.loading = false
}
}
}
}
</script>
<style scoped>
.login-page {
min-height: 100vh;
background: #F5F7FA;
display: flex;
flex-direction: column;
align-items: center;
padding: 0 32px;
overflow-x: hidden;
}
.brand-area {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 80px;
margin-bottom: 60px;
}
.logo-icon {
width: 80px;
height: 80px;
background: rgba(0,230,118,0.15);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
}
.logo-symbol {
font-size: 36px;
color: #00C853;
}
.app-name {
font-size: 28px;
font-weight: 700;
color: #1E1E1E;
letter-spacing: 1px;
}
.app-slogan {
font-size: 14px;
color: #7A7E84;
margin-top: 8px;
letter-spacing: 2px;
}
.login-form {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.input-group {
width: 100%;
height: 52px;
background: #FFFFFF;
border-radius: 40px;
display: flex;
align-items: center;
padding: 0 18px;
margin-bottom: 14px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.input-icon {
font-size: 18px;
margin-right: 10px;
color: #7A7E84;
}
.login-input {
flex: 1;
height: 100%;
font-size: 15px;
color: #1E1E1E;
}
.toggle-pwd {
font-size: 18px;
color: #7A7E84;
padding-left: 8px;
}
.login-btn {
width: 100%;
height: 52px;
background: #00E676;
border-radius: 40px;
display: flex;
align-items: center;
justify-content: center;
border: none;
padding: 0;
margin-top: 10px;
font-size: 17px;
font-weight: 700;
color: #1A1A1A;
box-shadow: 0 4px 16px rgba(0,230,118,0.35);
}
.login-btn::after { border: none; }
.login-btn[disabled] { opacity: 0.5; }
.footer-tip {
position: absolute;
bottom: 60px;
font-size: 12px;
color: #BDBDBD;
}
</style>
@@ -0,0 +1,347 @@
<template>
<view class="profile-page">
<view class="header-wrap" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="nav-bar" :style="{ height: navBarHeight + 'px' }">
<text class="back-btn" @click="goBack">&#8592;</text>
<text class="nav-title">个人中心</text>
</view>
</view>
<scroll-view class="content" scroll-y :style="{ height: 'calc(100vh - ' + totalHeaderHeight + 'px)' }">
<view class="content-inner">
<!-- 教练信息卡片 -->
<view class="user-card">
<view class="user-header">
<view class="avatar">
<text class="avatar-text">CC</text>
</view>
<view class="user-info">
<text class="user-name">{{ coachInfo.username }}</text>
<view class="user-tag">
<text>教练</text>
</view>
</view>
</view>
<view class="user-details">
<view class="detail-row">
<text class="detail-label">教练 ID</text>
<text class="detail-value">{{ coachInfo.coachId }}</text>
</view>
</view>
</view>
<!-- 违规统计 -->
<view class="stats-card">
<view class="stat-item">
<text class="stat-number">{{ violations.length }}</text>
<text class="stat-label">违规次数</text>
</view>
</view>
<!-- 违规记录列表 -->
<view class="section-header">
<text class="section-title">违规记录</text>
</view>
<view v-if="violations.length === 0 && !loadingViolations" class="empty-wrap">
<text class="empty-text">暂无违规记录</text>
</view>
<view v-else class="violation-list">
<view v-for="(v, idx) in violations" :key="idx" class="violation-card">
<view class="violation-header">
<text class="violation-course">{{ v.course_name || '未知课程' }}</text>
<view class="violation-tag" :class="v._violationClass">
<text>{{ v._violationLabel }}</text>
</view>
</view>
<text class="violation-time">{{ formatViolationTime(v.violation_time) }}</text>
</view>
</view>
<!-- 退出登录 -->
<view class="logout-area">
<button class="logout-btn" @click="handleLogout">退出登录</button>
</view>
<view class="bottom-safe"></view>
</view>
</scroll-view>
</view>
</template>
<script>
const store = require('../../store/index')
const coachApi = require('../../api/coach')
export default {
data() {
return {
statusBarHeight: 0,
navBarHeight: 44,
totalHeaderHeight: 44,
coachInfo: {
username: '加载中...',
coachId: ''
},
violations: [],
loadingViolations: true
}
},
onLoad() {
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = systemInfo.statusBarHeight || 20
let navBarHeight = 44
// #ifdef MP-WEIXIN
const menuButton = uni.getMenuButtonBoundingClientRect()
if (menuButton) {
navBarHeight = (menuButton.top - statusBarHeight) * 2 + menuButton.height
}
// #endif
this.statusBarHeight = statusBarHeight
this.navBarHeight = navBarHeight
this.totalHeaderHeight = statusBarHeight + navBarHeight
},
onShow() {
if (!store.isLoggedIn) {
uni.reLaunch({ url: '/pages/login/login' })
return
}
this.coachInfo = store.getCoachInfo() || { username: '教练', coachId: '' }
this.loadViolations()
},
methods: {
goBack() { uni.navigateBack() },
async loadViolations() {
this.loadingViolations = true
try {
const coachId = store.getCoachId()
if (!coachId) return
const result = await coachApi.getCoachViolations(coachId)
const list = Array.isArray(result) ? result : (result && result.content ? result.content : [])
// 预计算违规 class 和 labeluni-app 模板不支持 :class 中调用方法
const classMap = { COACH_LATE: 'late', COACH_ABSENT: 'absent', NOT_MANUAL_END: 'no-manual-end' }
const labelMap = { COACH_LATE: '迟到', COACH_ABSENT: '缺席', NOT_MANUAL_END: '未手动结课' }
this.violations = list.map(v => ({
...v,
_violationClass: classMap[v.violation_reason] || '',
_violationLabel: labelMap[v.violation_reason] || v.violation_reason || '违规'
}))
} catch (e) {
console.error('加载违规记录失败:', e)
} finally {
this.loadingViolations = false
}
},
handleLogout() {
uni.showModal({
title: '提示',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
store.clearLogin()
uni.reLaunch({ url: '/pages/login/login' })
}
}
})
},
formatViolationTime(timeStr) {
if (!timeStr) return ''
return timeStr.replace('T', ' ').substring(0, 19)
}
}
}
</script>
<style scoped>
.profile-page {
min-height: 100vh;
background: #F5F7FA;
overflow-x: hidden;
}
.header-wrap {
background: #1A1A1A;
}
.nav-bar {
padding: 0 16px;
display: flex;
align-items: center;
}
.back-btn {
font-size: 20px;
color: #FFFFFF;
margin-right: 12px;
}
.nav-title {
font-size: 18px;
font-weight: 700;
color: #FFFFFF;
}
.content-inner {
padding: 16px 14px 0;
}
/* 用户卡片 */
.user-card {
background: #FFFFFF;
border-radius: 20px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.user-header {
display: flex;
align-items: center;
margin-bottom: 16px;
}
.avatar {
width: 56px;
height: 56px;
border-radius: 50%;
background: rgba(0,230,118,0.15);
display: flex;
align-items: center;
justify-content: center;
margin-right: 14px;
}
.avatar-text {
font-size: 20px;
font-weight: 700;
color: #00C853;
}
.user-info {
flex: 1;
}
.user-name {
font-size: 18px;
font-weight: 700;
color: #1E1E1E;
}
.user-tag {
font-size: 13px;
color: #00C853;
font-weight: 500;
}
.user-details {
background: #F5F7FA;
border-radius: 12px;
padding: 14px 16px;
}
.detail-row {
display: flex;
justify-content: space-between;
}
.detail-label {
font-size: 13px;
color: #7A7E84;
}
.detail-value {
font-size: 14px;
font-weight: 600;
color: #1E1E1E;
}
/* 违规统计 */
.stats-card {
background: #1A1A1A;
border-radius: 20px;
padding: 18px 20px;
margin-bottom: 16px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.stat-item {
display: flex;
flex-direction: column;
align-items: center;
}
.stat-number {
font-size: 28px;
font-weight: 700;
color: #F44336;
}
.stat-label {
font-size: 12px;
color: rgba(255,255,255,0.6);
margin-top: 4px;
}
/* 违规记录 */
.section-header {
margin-bottom: 12px;
}
.section-title {
font-size: 16px;
font-weight: 700;
color: #1E1E1E;
}
.empty-wrap {
display: flex;
justify-content: center;
padding: 30px 0;
}
.empty-text {
font-size: 14px;
color: #7A7E84;
}
.violation-list {
margin-bottom: 16px;
}
.violation-card {
background: #FFFFFF;
border-radius: 12px;
padding: 12px 16px;
margin-bottom: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.violation-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.violation-course {
font-size: 14px;
font-weight: 600;
color: #1E1E1E;
}
.violation-tag {
padding: 3px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
}
.violation-tag.late { background: rgba(255,152,0,0.15); color: #FF9800; }
.violation-tag.absent { background: rgba(244,67,54,0.15); color: #F44336; }
.violation-tag.no-manual-end { background: rgba(33,150,243,0.15); color: #2196F3; }
.violation-time {
font-size: 12px;
color: #7A7E84;
}
/* 退出登录 */
.logout-area {
padding: 20px 0;
}
.logout-btn {
width: 100%;
height: 50px;
background: #FFFFFF;
color: #F44336;
border-radius: 40px;
font-size: 16px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
border: 2px solid #F44336;
}
.logout-btn::after { border: none; }
.bottom-safe {
height: 30px;
}
</style>
@@ -0,0 +1,25 @@
{
"setting": {
"es6": true,
"postcss": true,
"minified": true,
"uglifyFileName": false,
"enhance": true,
"packNpmRelationList": [],
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
},
"useCompilerPlugins": false,
"minifyWXML": true
},
"compileType": "miniprogram",
"simulatorPluginLibVersion": {},
"packOptions": {
"ignore": [],
"include": []
},
"appid": "wxe734af0ea3f96437",
"editorSetting": {}
}
@@ -0,0 +1,14 @@
{
"libVersion": "3.17.0",
"projectname": "gym-manage-coach-uniapp",
"setting": {
"urlCheck": true,
"coverView": true,
"lazyloadPlaceholderEnable": false,
"skylineRenderEnable": false,
"preloadBackgroundData": false,
"autoAudits": false,
"showShadowRootInWxmlPanel": true,
"compileHotReLoad": true
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

+68
View File
@@ -0,0 +1,68 @@
/**
* 教练端全局状态管理 — 以 uni.Storage 为唯一数据源
*/
const TOKEN_KEY = 'coach_token'
const COACH_KEY = 'coach_info'
const store = {
/** 是否已登录 */
get isLoggedIn() {
try {
return !!uni.getStorageSync(TOKEN_KEY)
} catch (e) {
return false
}
},
/** 获取 token */
getToken() {
try {
return uni.getStorageSync(TOKEN_KEY) || null
} catch (e) {
return null
}
},
/** 获取教练信息 */
getCoachInfo() {
try {
return uni.getStorageSync(COACH_KEY) || null
} catch (e) {
return null
}
},
/** 获取教练 ID */
getCoachId() {
const info = this.getCoachInfo()
return info ? info.coachId : null
},
/** 获取教练用户名 */
getUsername() {
const info = this.getCoachInfo()
return info ? info.username : ''
},
/** 设置登录态 */
setLogin(token, coachInfo) {
try {
uni.setStorageSync(TOKEN_KEY, token)
if (coachInfo) uni.setStorageSync(COACH_KEY, coachInfo)
} catch (e) {
console.error('存储登录态失败:', e)
}
},
/** 清除登录态 */
clearLogin() {
try {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(COACH_KEY)
} catch (e) {
console.error('清除登录态失败:', e)
}
}
}
module.exports = store
@@ -0,0 +1,13 @@
uni.addInterceptor({
returnValue (res) {
if (!(!!res && (typeof res === "object" || typeof res === "function") && typeof res.then === "function")) {
return res;
}
return new Promise((resolve, reject) => {
res.then((res) => {
if (!res) return resolve(res)
return res[0] ? reject(res[0]) : resolve(res[1])
});
});
},
});
+76
View File
@@ -0,0 +1,76 @@
/**
* 这里是uni-app内置的常用样式变量
*
* uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量
* 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App
*
*/
/**
* 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能
*
* 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件
*/
/* 颜色变量 */
/* 行为相关颜色 */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;
/* 文字基本颜色 */
$uni-text-color:#333;//基本色
$uni-text-color-inverse:#fff;//反色
$uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080;
$uni-text-color-disable:#c0c0c0;
/* 背景颜色 */
$uni-bg-color:#ffffff;
$uni-bg-color-grey:#f8f8f8;
$uni-bg-color-hover:#f1f1f1;//点击状态颜色
$uni-bg-color-mask:rgba(0, 0, 0, 0.4);//遮罩颜色
/* 边框颜色 */
$uni-border-color:#c8c7cc;
/* 尺寸变量 */
/* 文字尺寸 */
$uni-font-size-sm:12px;
$uni-font-size-base:14px;
$uni-font-size-lg:16px;
/* 图片尺寸 */
$uni-img-size-sm:20px;
$uni-img-size-base:26px;
$uni-img-size-lg:40px;
/* Border Radius */
$uni-border-radius-sm: 2px;
$uni-border-radius-base: 3px;
$uni-border-radius-lg: 6px;
$uni-border-radius-circle: 50%;
/* 水平间距 */
$uni-spacing-row-sm: 5px;
$uni-spacing-row-base: 10px;
$uni-spacing-row-lg: 15px;
/* 垂直间距 */
$uni-spacing-col-sm: 4px;
$uni-spacing-col-base: 8px;
$uni-spacing-col-lg: 12px;
/* 透明度 */
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
/* 文章场景相关 */
$uni-color-title: #2C405A; // 文章标题颜色
$uni-font-size-title:20px;
$uni-color-subtitle: #555555; // 二级标题颜色
$uni-font-size-subtitle:26px;
$uni-color-paragraph: #3F536E; // 文章段落颜色
$uni-font-size-paragraph:15px;
@@ -0,0 +1,44 @@
## 2.0.122025-08-26
- 优化 uni-app x 下 size 类型问题
## 2.0.112025-08-18
- 修复 图标点击事件返回
## 2.0.92024-01-12
fix: 修复图标大小默认值错误的问题
## 2.0.82023-12-14
- 修复 项目未使用 ts 情况下,打包报错的bug
## 2.0.72023-12-14
- 修复 size 属性为 string 时,不加单位导致尺寸异常的bug
## 2.0.62023-12-11
- 优化 兼容老版本icon类型,如 top bottom 等
## 2.0.52023-12-11
- 优化 兼容老版本icon类型,如 top bottom 等
## 2.0.42023-12-06
- 优化 uni-app x 下示例项目图标排序
## 2.0.32023-12-06
- 修复 nvue下引入组件报错的bug
## 2.0.22023-12-05
-优化 size 属性支持单位
## 2.0.12023-12-05
- 新增 uni-app x 支持定义图标
## 1.3.52022-01-24
- 优化 size 属性可以传入不带单位的字符串数值
## 1.3.42022-01-24
- 优化 size 支持其他单位
## 1.3.32022-01-17
- 修复 nvue 有些图标不显示的bug,兼容老版本图标
## 1.3.22021-12-01
- 优化 示例可复制图标名称
## 1.3.12021-11-23
- 优化 兼容旧组件 type 值
## 1.3.02021-11-19
- 新增 更多图标
- 优化 自定义图标使用方式
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-icons](https://uniapp.dcloud.io/component/uniui/uni-icons)
## 1.1.72021-11-08
## 1.2.02021-07-30
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.1.52021-05-12
- 新增 组件示例地址
## 1.1.42021-02-05
- 调整为uni_modules目录规范
@@ -0,0 +1,91 @@
<template>
<text class="uni-icons" :style="styleObj">
<slot>{{unicode}}</slot>
</text>
</template>
<script>
import { fontData, IconsDataItem } from './uniicons_file'
/**
* Icons 图标
* @description 用于展示 icon 图标
* @tutorial https://ext.dcloud.net.cn/plugin?id=28
* @property {Number} size 图标大小
* @property {String} type 图标图案,参考示例
* @property {String} color 图标颜色
* @property {String} customPrefix 自定义图标
* @event {Function} click 点击 Icon 触发事件
*/
export default {
name: "uni-icons",
props: {
type: {
type: String,
default: ''
},
color: {
type: String,
default: '#333333'
},
size: {
type: [Number, String],
default: 16
},
fontFamily: {
type: String,
default: ''
}
},
data() {
return {};
},
computed: {
unicode() : string {
let codes = fontData.find((item : IconsDataItem) : boolean => { return item.font_class == this.type })
if (codes !== null) {
return codes.unicode
}
return ''
},
iconSize() : string {
const size = this.size
if (typeof size == 'string') {
const reg = /^[0-9]*$/g
return reg.test(size as string) ? '' + size + 'px' : '' + size;
// return '' + this.size
}
return this.getFontSize(size as number)
},
styleObj() : UTSJSONObject {
if (this.fontFamily !== '') {
return { color: this.color, fontSize: this.iconSize, fontFamily: this.fontFamily }
}
return { color: this.color, fontSize: this.iconSize }
}
},
created() { },
methods: {
/**
* 字体大小
*/
getFontSize(size : number) : string {
return size + 'px';
},
},
}
</script>
<style scoped>
@font-face {
font-family: UniIconsFontFamily;
src: url('./uniicons.ttf');
}
.uni-icons {
font-family: UniIconsFontFamily;
font-size: 18px;
font-style: normal;
color: #333;
}
</style>
@@ -0,0 +1,110 @@
<template>
<!-- #ifdef APP-NVUE -->
<text :style="styleObj" class="uni-icons" @click="_onClick">{{unicode}}</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<text :style="styleObj" class="uni-icons" :class="['uniui-'+type,customPrefix,customPrefix?type:'']" @click="_onClick">
<slot></slot>
</text>
<!-- #endif -->
</template>
<script>
import { fontData } from './uniicons_file_vue.js';
const getVal = (val) => {
const reg = /^[0-9]*$/g
return (typeof val === 'number' || reg.test(val)) ? val + 'px' : val;
}
// #ifdef APP-NVUE
var domModule = weex.requireModule('dom');
import iconUrl from './uniicons.ttf'
domModule.addRule('fontFace', {
'fontFamily': "uniicons",
'src': "url('" + iconUrl + "')"
});
// #endif
/**
* Icons 图标
* @description 用于展示 icons 图标
* @tutorial https://ext.dcloud.net.cn/plugin?id=28
* @property {Number} size 图标大小
* @property {String} type 图标图案,参考示例
* @property {String} color 图标颜色
* @property {String} customPrefix 自定义图标
* @event {Function} click 点击 Icon 触发事件
*/
export default {
name: 'UniIcons',
emits: ['click'],
props: {
type: {
type: String,
default: ''
},
color: {
type: String,
default: '#333333'
},
size: {
type: [Number, String],
default: 16
},
customPrefix: {
type: String,
default: ''
},
fontFamily: {
type: String,
default: ''
}
},
data() {
return {
icons: fontData
}
},
computed: {
unicode() {
let code = this.icons.find(v => v.font_class === this.type)
if (code) {
return code.unicode
}
return ''
},
iconSize() {
return getVal(this.size)
},
styleObj() {
if (this.fontFamily !== '') {
return `color: ${this.color}; font-size: ${this.iconSize}; font-family: ${this.fontFamily};`
}
return `color: ${this.color}; font-size: ${this.iconSize};`
}
},
methods: {
_onClick(e) {
this.$emit('click', e)
}
}
}
</script>
<style lang="scss">
/* #ifndef APP-NVUE */
@import './uniicons.css';
@font-face {
font-family: uniicons;
src: url('./uniicons.ttf');
}
/* #endif */
.uni-icons {
font-family: uniicons;
text-decoration: none;
text-align: center;
}
</style>
@@ -0,0 +1,664 @@
.uniui-cart-filled:before {
content: "\e6d0";
}
.uniui-gift-filled:before {
content: "\e6c4";
}
.uniui-color:before {
content: "\e6cf";
}
.uniui-wallet:before {
content: "\e6b1";
}
.uniui-settings-filled:before {
content: "\e6ce";
}
.uniui-auth-filled:before {
content: "\e6cc";
}
.uniui-shop-filled:before {
content: "\e6cd";
}
.uniui-staff-filled:before {
content: "\e6cb";
}
.uniui-vip-filled:before {
content: "\e6c6";
}
.uniui-plus-filled:before {
content: "\e6c7";
}
.uniui-folder-add-filled:before {
content: "\e6c8";
}
.uniui-color-filled:before {
content: "\e6c9";
}
.uniui-tune-filled:before {
content: "\e6ca";
}
.uniui-calendar-filled:before {
content: "\e6c0";
}
.uniui-notification-filled:before {
content: "\e6c1";
}
.uniui-wallet-filled:before {
content: "\e6c2";
}
.uniui-medal-filled:before {
content: "\e6c3";
}
.uniui-fire-filled:before {
content: "\e6c5";
}
.uniui-refreshempty:before {
content: "\e6bf";
}
.uniui-location-filled:before {
content: "\e6af";
}
.uniui-person-filled:before {
content: "\e69d";
}
.uniui-personadd-filled:before {
content: "\e698";
}
.uniui-arrowthinleft:before {
content: "\e6d2";
}
.uniui-arrowthinup:before {
content: "\e6d3";
}
.uniui-arrowthindown:before {
content: "\e6d4";
}
.uniui-back:before {
content: "\e6b9";
}
.uniui-forward:before {
content: "\e6ba";
}
.uniui-arrow-right:before {
content: "\e6bb";
}
.uniui-arrow-left:before {
content: "\e6bc";
}
.uniui-arrow-up:before {
content: "\e6bd";
}
.uniui-arrow-down:before {
content: "\e6be";
}
.uniui-arrowthinright:before {
content: "\e6d1";
}
.uniui-down:before {
content: "\e6b8";
}
.uniui-bottom:before {
content: "\e6b8";
}
.uniui-arrowright:before {
content: "\e6d5";
}
.uniui-right:before {
content: "\e6b5";
}
.uniui-up:before {
content: "\e6b6";
}
.uniui-top:before {
content: "\e6b6";
}
.uniui-left:before {
content: "\e6b7";
}
.uniui-arrowup:before {
content: "\e6d6";
}
.uniui-eye:before {
content: "\e651";
}
.uniui-eye-filled:before {
content: "\e66a";
}
.uniui-eye-slash:before {
content: "\e6b3";
}
.uniui-eye-slash-filled:before {
content: "\e6b4";
}
.uniui-info-filled:before {
content: "\e649";
}
.uniui-reload:before {
content: "\e6b2";
}
.uniui-micoff-filled:before {
content: "\e6b0";
}
.uniui-map-pin-ellipse:before {
content: "\e6ac";
}
.uniui-map-pin:before {
content: "\e6ad";
}
.uniui-location:before {
content: "\e6ae";
}
.uniui-starhalf:before {
content: "\e683";
}
.uniui-star:before {
content: "\e688";
}
.uniui-star-filled:before {
content: "\e68f";
}
.uniui-calendar:before {
content: "\e6a0";
}
.uniui-fire:before {
content: "\e6a1";
}
.uniui-medal:before {
content: "\e6a2";
}
.uniui-font:before {
content: "\e6a3";
}
.uniui-gift:before {
content: "\e6a4";
}
.uniui-link:before {
content: "\e6a5";
}
.uniui-notification:before {
content: "\e6a6";
}
.uniui-staff:before {
content: "\e6a7";
}
.uniui-vip:before {
content: "\e6a8";
}
.uniui-folder-add:before {
content: "\e6a9";
}
.uniui-tune:before {
content: "\e6aa";
}
.uniui-auth:before {
content: "\e6ab";
}
.uniui-person:before {
content: "\e699";
}
.uniui-email-filled:before {
content: "\e69a";
}
.uniui-phone-filled:before {
content: "\e69b";
}
.uniui-phone:before {
content: "\e69c";
}
.uniui-email:before {
content: "\e69e";
}
.uniui-personadd:before {
content: "\e69f";
}
.uniui-chatboxes-filled:before {
content: "\e692";
}
.uniui-contact:before {
content: "\e693";
}
.uniui-chatbubble-filled:before {
content: "\e694";
}
.uniui-contact-filled:before {
content: "\e695";
}
.uniui-chatboxes:before {
content: "\e696";
}
.uniui-chatbubble:before {
content: "\e697";
}
.uniui-upload-filled:before {
content: "\e68e";
}
.uniui-upload:before {
content: "\e690";
}
.uniui-weixin:before {
content: "\e691";
}
.uniui-compose:before {
content: "\e67f";
}
.uniui-qq:before {
content: "\e680";
}
.uniui-download-filled:before {
content: "\e681";
}
.uniui-pyq:before {
content: "\e682";
}
.uniui-sound:before {
content: "\e684";
}
.uniui-trash-filled:before {
content: "\e685";
}
.uniui-sound-filled:before {
content: "\e686";
}
.uniui-trash:before {
content: "\e687";
}
.uniui-videocam-filled:before {
content: "\e689";
}
.uniui-spinner-cycle:before {
content: "\e68a";
}
.uniui-weibo:before {
content: "\e68b";
}
.uniui-videocam:before {
content: "\e68c";
}
.uniui-download:before {
content: "\e68d";
}
.uniui-help:before {
content: "\e679";
}
.uniui-navigate-filled:before {
content: "\e67a";
}
.uniui-plusempty:before {
content: "\e67b";
}
.uniui-smallcircle:before {
content: "\e67c";
}
.uniui-minus-filled:before {
content: "\e67d";
}
.uniui-micoff:before {
content: "\e67e";
}
.uniui-closeempty:before {
content: "\e66c";
}
.uniui-clear:before {
content: "\e66d";
}
.uniui-navigate:before {
content: "\e66e";
}
.uniui-minus:before {
content: "\e66f";
}
.uniui-image:before {
content: "\e670";
}
.uniui-mic:before {
content: "\e671";
}
.uniui-paperplane:before {
content: "\e672";
}
.uniui-close:before {
content: "\e673";
}
.uniui-help-filled:before {
content: "\e674";
}
.uniui-paperplane-filled:before {
content: "\e675";
}
.uniui-plus:before {
content: "\e676";
}
.uniui-mic-filled:before {
content: "\e677";
}
.uniui-image-filled:before {
content: "\e678";
}
.uniui-locked-filled:before {
content: "\e668";
}
.uniui-info:before {
content: "\e669";
}
.uniui-locked:before {
content: "\e66b";
}
.uniui-camera-filled:before {
content: "\e658";
}
.uniui-chat-filled:before {
content: "\e659";
}
.uniui-camera:before {
content: "\e65a";
}
.uniui-circle:before {
content: "\e65b";
}
.uniui-checkmarkempty:before {
content: "\e65c";
}
.uniui-chat:before {
content: "\e65d";
}
.uniui-circle-filled:before {
content: "\e65e";
}
.uniui-flag:before {
content: "\e65f";
}
.uniui-flag-filled:before {
content: "\e660";
}
.uniui-gear-filled:before {
content: "\e661";
}
.uniui-home:before {
content: "\e662";
}
.uniui-home-filled:before {
content: "\e663";
}
.uniui-gear:before {
content: "\e664";
}
.uniui-smallcircle-filled:before {
content: "\e665";
}
.uniui-map-filled:before {
content: "\e666";
}
.uniui-map:before {
content: "\e667";
}
.uniui-refresh-filled:before {
content: "\e656";
}
.uniui-refresh:before {
content: "\e657";
}
.uniui-cloud-upload:before {
content: "\e645";
}
.uniui-cloud-download-filled:before {
content: "\e646";
}
.uniui-cloud-download:before {
content: "\e647";
}
.uniui-cloud-upload-filled:before {
content: "\e648";
}
.uniui-redo:before {
content: "\e64a";
}
.uniui-images-filled:before {
content: "\e64b";
}
.uniui-undo-filled:before {
content: "\e64c";
}
.uniui-more:before {
content: "\e64d";
}
.uniui-more-filled:before {
content: "\e64e";
}
.uniui-undo:before {
content: "\e64f";
}
.uniui-images:before {
content: "\e650";
}
.uniui-paperclip:before {
content: "\e652";
}
.uniui-settings:before {
content: "\e653";
}
.uniui-search:before {
content: "\e654";
}
.uniui-redo-filled:before {
content: "\e655";
}
.uniui-list:before {
content: "\e644";
}
.uniui-mail-open-filled:before {
content: "\e63a";
}
.uniui-hand-down-filled:before {
content: "\e63c";
}
.uniui-hand-down:before {
content: "\e63d";
}
.uniui-hand-up-filled:before {
content: "\e63e";
}
.uniui-hand-up:before {
content: "\e63f";
}
.uniui-heart-filled:before {
content: "\e641";
}
.uniui-mail-open:before {
content: "\e643";
}
.uniui-heart:before {
content: "\e639";
}
.uniui-loop:before {
content: "\e633";
}
.uniui-pulldown:before {
content: "\e632";
}
.uniui-scan:before {
content: "\e62a";
}
.uniui-bars:before {
content: "\e627";
}
.uniui-checkbox:before {
content: "\e62b";
}
.uniui-checkbox-filled:before {
content: "\e62c";
}
.uniui-shop:before {
content: "\e62f";
}
.uniui-headphones:before {
content: "\e630";
}
.uniui-cart:before {
content: "\e631";
}
@@ -0,0 +1,664 @@
export type IconsData = {
id : string
name : string
font_family : string
css_prefix_text : string
description : string
glyphs : Array<IconsDataItem>
}
export type IconsDataItem = {
font_class : string
unicode : string
}
export const fontData = [
{
"font_class": "arrow-down",
"unicode": "\ue6be"
},
{
"font_class": "arrow-left",
"unicode": "\ue6bc"
},
{
"font_class": "arrow-right",
"unicode": "\ue6bb"
},
{
"font_class": "arrow-up",
"unicode": "\ue6bd"
},
{
"font_class": "auth",
"unicode": "\ue6ab"
},
{
"font_class": "auth-filled",
"unicode": "\ue6cc"
},
{
"font_class": "back",
"unicode": "\ue6b9"
},
{
"font_class": "bars",
"unicode": "\ue627"
},
{
"font_class": "calendar",
"unicode": "\ue6a0"
},
{
"font_class": "calendar-filled",
"unicode": "\ue6c0"
},
{
"font_class": "camera",
"unicode": "\ue65a"
},
{
"font_class": "camera-filled",
"unicode": "\ue658"
},
{
"font_class": "cart",
"unicode": "\ue631"
},
{
"font_class": "cart-filled",
"unicode": "\ue6d0"
},
{
"font_class": "chat",
"unicode": "\ue65d"
},
{
"font_class": "chat-filled",
"unicode": "\ue659"
},
{
"font_class": "chatboxes",
"unicode": "\ue696"
},
{
"font_class": "chatboxes-filled",
"unicode": "\ue692"
},
{
"font_class": "chatbubble",
"unicode": "\ue697"
},
{
"font_class": "chatbubble-filled",
"unicode": "\ue694"
},
{
"font_class": "checkbox",
"unicode": "\ue62b"
},
{
"font_class": "checkbox-filled",
"unicode": "\ue62c"
},
{
"font_class": "checkmarkempty",
"unicode": "\ue65c"
},
{
"font_class": "circle",
"unicode": "\ue65b"
},
{
"font_class": "circle-filled",
"unicode": "\ue65e"
},
{
"font_class": "clear",
"unicode": "\ue66d"
},
{
"font_class": "close",
"unicode": "\ue673"
},
{
"font_class": "closeempty",
"unicode": "\ue66c"
},
{
"font_class": "cloud-download",
"unicode": "\ue647"
},
{
"font_class": "cloud-download-filled",
"unicode": "\ue646"
},
{
"font_class": "cloud-upload",
"unicode": "\ue645"
},
{
"font_class": "cloud-upload-filled",
"unicode": "\ue648"
},
{
"font_class": "color",
"unicode": "\ue6cf"
},
{
"font_class": "color-filled",
"unicode": "\ue6c9"
},
{
"font_class": "compose",
"unicode": "\ue67f"
},
{
"font_class": "contact",
"unicode": "\ue693"
},
{
"font_class": "contact-filled",
"unicode": "\ue695"
},
{
"font_class": "down",
"unicode": "\ue6b8"
},
{
"font_class": "bottom",
"unicode": "\ue6b8"
},
{
"font_class": "download",
"unicode": "\ue68d"
},
{
"font_class": "download-filled",
"unicode": "\ue681"
},
{
"font_class": "email",
"unicode": "\ue69e"
},
{
"font_class": "email-filled",
"unicode": "\ue69a"
},
{
"font_class": "eye",
"unicode": "\ue651"
},
{
"font_class": "eye-filled",
"unicode": "\ue66a"
},
{
"font_class": "eye-slash",
"unicode": "\ue6b3"
},
{
"font_class": "eye-slash-filled",
"unicode": "\ue6b4"
},
{
"font_class": "fire",
"unicode": "\ue6a1"
},
{
"font_class": "fire-filled",
"unicode": "\ue6c5"
},
{
"font_class": "flag",
"unicode": "\ue65f"
},
{
"font_class": "flag-filled",
"unicode": "\ue660"
},
{
"font_class": "folder-add",
"unicode": "\ue6a9"
},
{
"font_class": "folder-add-filled",
"unicode": "\ue6c8"
},
{
"font_class": "font",
"unicode": "\ue6a3"
},
{
"font_class": "forward",
"unicode": "\ue6ba"
},
{
"font_class": "gear",
"unicode": "\ue664"
},
{
"font_class": "gear-filled",
"unicode": "\ue661"
},
{
"font_class": "gift",
"unicode": "\ue6a4"
},
{
"font_class": "gift-filled",
"unicode": "\ue6c4"
},
{
"font_class": "hand-down",
"unicode": "\ue63d"
},
{
"font_class": "hand-down-filled",
"unicode": "\ue63c"
},
{
"font_class": "hand-up",
"unicode": "\ue63f"
},
{
"font_class": "hand-up-filled",
"unicode": "\ue63e"
},
{
"font_class": "headphones",
"unicode": "\ue630"
},
{
"font_class": "heart",
"unicode": "\ue639"
},
{
"font_class": "heart-filled",
"unicode": "\ue641"
},
{
"font_class": "help",
"unicode": "\ue679"
},
{
"font_class": "help-filled",
"unicode": "\ue674"
},
{
"font_class": "home",
"unicode": "\ue662"
},
{
"font_class": "home-filled",
"unicode": "\ue663"
},
{
"font_class": "image",
"unicode": "\ue670"
},
{
"font_class": "image-filled",
"unicode": "\ue678"
},
{
"font_class": "images",
"unicode": "\ue650"
},
{
"font_class": "images-filled",
"unicode": "\ue64b"
},
{
"font_class": "info",
"unicode": "\ue669"
},
{
"font_class": "info-filled",
"unicode": "\ue649"
},
{
"font_class": "left",
"unicode": "\ue6b7"
},
{
"font_class": "link",
"unicode": "\ue6a5"
},
{
"font_class": "list",
"unicode": "\ue644"
},
{
"font_class": "location",
"unicode": "\ue6ae"
},
{
"font_class": "location-filled",
"unicode": "\ue6af"
},
{
"font_class": "locked",
"unicode": "\ue66b"
},
{
"font_class": "locked-filled",
"unicode": "\ue668"
},
{
"font_class": "loop",
"unicode": "\ue633"
},
{
"font_class": "mail-open",
"unicode": "\ue643"
},
{
"font_class": "mail-open-filled",
"unicode": "\ue63a"
},
{
"font_class": "map",
"unicode": "\ue667"
},
{
"font_class": "map-filled",
"unicode": "\ue666"
},
{
"font_class": "map-pin",
"unicode": "\ue6ad"
},
{
"font_class": "map-pin-ellipse",
"unicode": "\ue6ac"
},
{
"font_class": "medal",
"unicode": "\ue6a2"
},
{
"font_class": "medal-filled",
"unicode": "\ue6c3"
},
{
"font_class": "mic",
"unicode": "\ue671"
},
{
"font_class": "mic-filled",
"unicode": "\ue677"
},
{
"font_class": "micoff",
"unicode": "\ue67e"
},
{
"font_class": "micoff-filled",
"unicode": "\ue6b0"
},
{
"font_class": "minus",
"unicode": "\ue66f"
},
{
"font_class": "minus-filled",
"unicode": "\ue67d"
},
{
"font_class": "more",
"unicode": "\ue64d"
},
{
"font_class": "more-filled",
"unicode": "\ue64e"
},
{
"font_class": "navigate",
"unicode": "\ue66e"
},
{
"font_class": "navigate-filled",
"unicode": "\ue67a"
},
{
"font_class": "notification",
"unicode": "\ue6a6"
},
{
"font_class": "notification-filled",
"unicode": "\ue6c1"
},
{
"font_class": "paperclip",
"unicode": "\ue652"
},
{
"font_class": "paperplane",
"unicode": "\ue672"
},
{
"font_class": "paperplane-filled",
"unicode": "\ue675"
},
{
"font_class": "person",
"unicode": "\ue699"
},
{
"font_class": "person-filled",
"unicode": "\ue69d"
},
{
"font_class": "personadd",
"unicode": "\ue69f"
},
{
"font_class": "personadd-filled",
"unicode": "\ue698"
},
{
"font_class": "personadd-filled-copy",
"unicode": "\ue6d1"
},
{
"font_class": "phone",
"unicode": "\ue69c"
},
{
"font_class": "phone-filled",
"unicode": "\ue69b"
},
{
"font_class": "plus",
"unicode": "\ue676"
},
{
"font_class": "plus-filled",
"unicode": "\ue6c7"
},
{
"font_class": "plusempty",
"unicode": "\ue67b"
},
{
"font_class": "pulldown",
"unicode": "\ue632"
},
{
"font_class": "pyq",
"unicode": "\ue682"
},
{
"font_class": "qq",
"unicode": "\ue680"
},
{
"font_class": "redo",
"unicode": "\ue64a"
},
{
"font_class": "redo-filled",
"unicode": "\ue655"
},
{
"font_class": "refresh",
"unicode": "\ue657"
},
{
"font_class": "refresh-filled",
"unicode": "\ue656"
},
{
"font_class": "refreshempty",
"unicode": "\ue6bf"
},
{
"font_class": "reload",
"unicode": "\ue6b2"
},
{
"font_class": "right",
"unicode": "\ue6b5"
},
{
"font_class": "scan",
"unicode": "\ue62a"
},
{
"font_class": "search",
"unicode": "\ue654"
},
{
"font_class": "settings",
"unicode": "\ue653"
},
{
"font_class": "settings-filled",
"unicode": "\ue6ce"
},
{
"font_class": "shop",
"unicode": "\ue62f"
},
{
"font_class": "shop-filled",
"unicode": "\ue6cd"
},
{
"font_class": "smallcircle",
"unicode": "\ue67c"
},
{
"font_class": "smallcircle-filled",
"unicode": "\ue665"
},
{
"font_class": "sound",
"unicode": "\ue684"
},
{
"font_class": "sound-filled",
"unicode": "\ue686"
},
{
"font_class": "spinner-cycle",
"unicode": "\ue68a"
},
{
"font_class": "staff",
"unicode": "\ue6a7"
},
{
"font_class": "staff-filled",
"unicode": "\ue6cb"
},
{
"font_class": "star",
"unicode": "\ue688"
},
{
"font_class": "star-filled",
"unicode": "\ue68f"
},
{
"font_class": "starhalf",
"unicode": "\ue683"
},
{
"font_class": "trash",
"unicode": "\ue687"
},
{
"font_class": "trash-filled",
"unicode": "\ue685"
},
{
"font_class": "tune",
"unicode": "\ue6aa"
},
{
"font_class": "tune-filled",
"unicode": "\ue6ca"
},
{
"font_class": "undo",
"unicode": "\ue64f"
},
{
"font_class": "undo-filled",
"unicode": "\ue64c"
},
{
"font_class": "up",
"unicode": "\ue6b6"
},
{
"font_class": "top",
"unicode": "\ue6b6"
},
{
"font_class": "upload",
"unicode": "\ue690"
},
{
"font_class": "upload-filled",
"unicode": "\ue68e"
},
{
"font_class": "videocam",
"unicode": "\ue68c"
},
{
"font_class": "videocam-filled",
"unicode": "\ue689"
},
{
"font_class": "vip",
"unicode": "\ue6a8"
},
{
"font_class": "vip-filled",
"unicode": "\ue6c6"
},
{
"font_class": "wallet",
"unicode": "\ue6b1"
},
{
"font_class": "wallet-filled",
"unicode": "\ue6c2"
},
{
"font_class": "weibo",
"unicode": "\ue68b"
},
{
"font_class": "weixin",
"unicode": "\ue691"
}
] as IconsDataItem[]
// export const fontData = JSON.parse<IconsDataItem>(fontDataJson)
@@ -0,0 +1,649 @@
export const fontData = [
{
"font_class": "arrow-down",
"unicode": "\ue6be"
},
{
"font_class": "arrow-left",
"unicode": "\ue6bc"
},
{
"font_class": "arrow-right",
"unicode": "\ue6bb"
},
{
"font_class": "arrow-up",
"unicode": "\ue6bd"
},
{
"font_class": "auth",
"unicode": "\ue6ab"
},
{
"font_class": "auth-filled",
"unicode": "\ue6cc"
},
{
"font_class": "back",
"unicode": "\ue6b9"
},
{
"font_class": "bars",
"unicode": "\ue627"
},
{
"font_class": "calendar",
"unicode": "\ue6a0"
},
{
"font_class": "calendar-filled",
"unicode": "\ue6c0"
},
{
"font_class": "camera",
"unicode": "\ue65a"
},
{
"font_class": "camera-filled",
"unicode": "\ue658"
},
{
"font_class": "cart",
"unicode": "\ue631"
},
{
"font_class": "cart-filled",
"unicode": "\ue6d0"
},
{
"font_class": "chat",
"unicode": "\ue65d"
},
{
"font_class": "chat-filled",
"unicode": "\ue659"
},
{
"font_class": "chatboxes",
"unicode": "\ue696"
},
{
"font_class": "chatboxes-filled",
"unicode": "\ue692"
},
{
"font_class": "chatbubble",
"unicode": "\ue697"
},
{
"font_class": "chatbubble-filled",
"unicode": "\ue694"
},
{
"font_class": "checkbox",
"unicode": "\ue62b"
},
{
"font_class": "checkbox-filled",
"unicode": "\ue62c"
},
{
"font_class": "checkmarkempty",
"unicode": "\ue65c"
},
{
"font_class": "circle",
"unicode": "\ue65b"
},
{
"font_class": "circle-filled",
"unicode": "\ue65e"
},
{
"font_class": "clear",
"unicode": "\ue66d"
},
{
"font_class": "close",
"unicode": "\ue673"
},
{
"font_class": "closeempty",
"unicode": "\ue66c"
},
{
"font_class": "cloud-download",
"unicode": "\ue647"
},
{
"font_class": "cloud-download-filled",
"unicode": "\ue646"
},
{
"font_class": "cloud-upload",
"unicode": "\ue645"
},
{
"font_class": "cloud-upload-filled",
"unicode": "\ue648"
},
{
"font_class": "color",
"unicode": "\ue6cf"
},
{
"font_class": "color-filled",
"unicode": "\ue6c9"
},
{
"font_class": "compose",
"unicode": "\ue67f"
},
{
"font_class": "contact",
"unicode": "\ue693"
},
{
"font_class": "contact-filled",
"unicode": "\ue695"
},
{
"font_class": "down",
"unicode": "\ue6b8"
},
{
"font_class": "bottom",
"unicode": "\ue6b8"
},
{
"font_class": "download",
"unicode": "\ue68d"
},
{
"font_class": "download-filled",
"unicode": "\ue681"
},
{
"font_class": "email",
"unicode": "\ue69e"
},
{
"font_class": "email-filled",
"unicode": "\ue69a"
},
{
"font_class": "eye",
"unicode": "\ue651"
},
{
"font_class": "eye-filled",
"unicode": "\ue66a"
},
{
"font_class": "eye-slash",
"unicode": "\ue6b3"
},
{
"font_class": "eye-slash-filled",
"unicode": "\ue6b4"
},
{
"font_class": "fire",
"unicode": "\ue6a1"
},
{
"font_class": "fire-filled",
"unicode": "\ue6c5"
},
{
"font_class": "flag",
"unicode": "\ue65f"
},
{
"font_class": "flag-filled",
"unicode": "\ue660"
},
{
"font_class": "folder-add",
"unicode": "\ue6a9"
},
{
"font_class": "folder-add-filled",
"unicode": "\ue6c8"
},
{
"font_class": "font",
"unicode": "\ue6a3"
},
{
"font_class": "forward",
"unicode": "\ue6ba"
},
{
"font_class": "gear",
"unicode": "\ue664"
},
{
"font_class": "gear-filled",
"unicode": "\ue661"
},
{
"font_class": "gift",
"unicode": "\ue6a4"
},
{
"font_class": "gift-filled",
"unicode": "\ue6c4"
},
{
"font_class": "hand-down",
"unicode": "\ue63d"
},
{
"font_class": "hand-down-filled",
"unicode": "\ue63c"
},
{
"font_class": "hand-up",
"unicode": "\ue63f"
},
{
"font_class": "hand-up-filled",
"unicode": "\ue63e"
},
{
"font_class": "headphones",
"unicode": "\ue630"
},
{
"font_class": "heart",
"unicode": "\ue639"
},
{
"font_class": "heart-filled",
"unicode": "\ue641"
},
{
"font_class": "help",
"unicode": "\ue679"
},
{
"font_class": "help-filled",
"unicode": "\ue674"
},
{
"font_class": "home",
"unicode": "\ue662"
},
{
"font_class": "home-filled",
"unicode": "\ue663"
},
{
"font_class": "image",
"unicode": "\ue670"
},
{
"font_class": "image-filled",
"unicode": "\ue678"
},
{
"font_class": "images",
"unicode": "\ue650"
},
{
"font_class": "images-filled",
"unicode": "\ue64b"
},
{
"font_class": "info",
"unicode": "\ue669"
},
{
"font_class": "info-filled",
"unicode": "\ue649"
},
{
"font_class": "left",
"unicode": "\ue6b7"
},
{
"font_class": "link",
"unicode": "\ue6a5"
},
{
"font_class": "list",
"unicode": "\ue644"
},
{
"font_class": "location",
"unicode": "\ue6ae"
},
{
"font_class": "location-filled",
"unicode": "\ue6af"
},
{
"font_class": "locked",
"unicode": "\ue66b"
},
{
"font_class": "locked-filled",
"unicode": "\ue668"
},
{
"font_class": "loop",
"unicode": "\ue633"
},
{
"font_class": "mail-open",
"unicode": "\ue643"
},
{
"font_class": "mail-open-filled",
"unicode": "\ue63a"
},
{
"font_class": "map",
"unicode": "\ue667"
},
{
"font_class": "map-filled",
"unicode": "\ue666"
},
{
"font_class": "map-pin",
"unicode": "\ue6ad"
},
{
"font_class": "map-pin-ellipse",
"unicode": "\ue6ac"
},
{
"font_class": "medal",
"unicode": "\ue6a2"
},
{
"font_class": "medal-filled",
"unicode": "\ue6c3"
},
{
"font_class": "mic",
"unicode": "\ue671"
},
{
"font_class": "mic-filled",
"unicode": "\ue677"
},
{
"font_class": "micoff",
"unicode": "\ue67e"
},
{
"font_class": "micoff-filled",
"unicode": "\ue6b0"
},
{
"font_class": "minus",
"unicode": "\ue66f"
},
{
"font_class": "minus-filled",
"unicode": "\ue67d"
},
{
"font_class": "more",
"unicode": "\ue64d"
},
{
"font_class": "more-filled",
"unicode": "\ue64e"
},
{
"font_class": "navigate",
"unicode": "\ue66e"
},
{
"font_class": "navigate-filled",
"unicode": "\ue67a"
},
{
"font_class": "notification",
"unicode": "\ue6a6"
},
{
"font_class": "notification-filled",
"unicode": "\ue6c1"
},
{
"font_class": "paperclip",
"unicode": "\ue652"
},
{
"font_class": "paperplane",
"unicode": "\ue672"
},
{
"font_class": "paperplane-filled",
"unicode": "\ue675"
},
{
"font_class": "person",
"unicode": "\ue699"
},
{
"font_class": "person-filled",
"unicode": "\ue69d"
},
{
"font_class": "personadd",
"unicode": "\ue69f"
},
{
"font_class": "personadd-filled",
"unicode": "\ue698"
},
{
"font_class": "personadd-filled-copy",
"unicode": "\ue6d1"
},
{
"font_class": "phone",
"unicode": "\ue69c"
},
{
"font_class": "phone-filled",
"unicode": "\ue69b"
},
{
"font_class": "plus",
"unicode": "\ue676"
},
{
"font_class": "plus-filled",
"unicode": "\ue6c7"
},
{
"font_class": "plusempty",
"unicode": "\ue67b"
},
{
"font_class": "pulldown",
"unicode": "\ue632"
},
{
"font_class": "pyq",
"unicode": "\ue682"
},
{
"font_class": "qq",
"unicode": "\ue680"
},
{
"font_class": "redo",
"unicode": "\ue64a"
},
{
"font_class": "redo-filled",
"unicode": "\ue655"
},
{
"font_class": "refresh",
"unicode": "\ue657"
},
{
"font_class": "refresh-filled",
"unicode": "\ue656"
},
{
"font_class": "refreshempty",
"unicode": "\ue6bf"
},
{
"font_class": "reload",
"unicode": "\ue6b2"
},
{
"font_class": "right",
"unicode": "\ue6b5"
},
{
"font_class": "scan",
"unicode": "\ue62a"
},
{
"font_class": "search",
"unicode": "\ue654"
},
{
"font_class": "settings",
"unicode": "\ue653"
},
{
"font_class": "settings-filled",
"unicode": "\ue6ce"
},
{
"font_class": "shop",
"unicode": "\ue62f"
},
{
"font_class": "shop-filled",
"unicode": "\ue6cd"
},
{
"font_class": "smallcircle",
"unicode": "\ue67c"
},
{
"font_class": "smallcircle-filled",
"unicode": "\ue665"
},
{
"font_class": "sound",
"unicode": "\ue684"
},
{
"font_class": "sound-filled",
"unicode": "\ue686"
},
{
"font_class": "spinner-cycle",
"unicode": "\ue68a"
},
{
"font_class": "staff",
"unicode": "\ue6a7"
},
{
"font_class": "staff-filled",
"unicode": "\ue6cb"
},
{
"font_class": "star",
"unicode": "\ue688"
},
{
"font_class": "star-filled",
"unicode": "\ue68f"
},
{
"font_class": "starhalf",
"unicode": "\ue683"
},
{
"font_class": "trash",
"unicode": "\ue687"
},
{
"font_class": "trash-filled",
"unicode": "\ue685"
},
{
"font_class": "tune",
"unicode": "\ue6aa"
},
{
"font_class": "tune-filled",
"unicode": "\ue6ca"
},
{
"font_class": "undo",
"unicode": "\ue64f"
},
{
"font_class": "undo-filled",
"unicode": "\ue64c"
},
{
"font_class": "up",
"unicode": "\ue6b6"
},
{
"font_class": "top",
"unicode": "\ue6b6"
},
{
"font_class": "upload",
"unicode": "\ue690"
},
{
"font_class": "upload-filled",
"unicode": "\ue68e"
},
{
"font_class": "videocam",
"unicode": "\ue68c"
},
{
"font_class": "videocam-filled",
"unicode": "\ue689"
},
{
"font_class": "vip",
"unicode": "\ue6a8"
},
{
"font_class": "vip-filled",
"unicode": "\ue6c6"
},
{
"font_class": "wallet",
"unicode": "\ue6b1"
},
{
"font_class": "wallet-filled",
"unicode": "\ue6c2"
},
{
"font_class": "weibo",
"unicode": "\ue68b"
},
{
"font_class": "weixin",
"unicode": "\ue691"
}
]
// export const fontData = JSON.parse<IconsDataItem>(fontDataJson)
@@ -0,0 +1,111 @@
{
"id": "uni-icons",
"displayName": "uni-icons 图标",
"version": "2.0.12",
"description": "图标组件,用于展示移动端常见的图标,可自定义颜色、大小。",
"keywords": [
"uni-ui",
"uniui",
"icon",
"图标"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": "^3.2.14",
"uni-app": "^4.08",
"uni-app-x": "^4.61"
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"dependencies": [
"uni-scss"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "x",
"aliyun": "x",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "-",
"android": {
"extVersion": "",
"minVersion": "29"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "√",
"baidu": "√",
"kuaishou": "-",
"jd": "-",
"harmony": "-",
"qq": "√",
"lark": "-"
},
"quickapp": {
"huawei": "√",
"union": "√"
}
},
"uni-app-x": {
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"android": {
"extVersion": "",
"minVersion": "29"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√"
}
}
}
}
}
}
@@ -0,0 +1,8 @@
## Icons 图标
> **组件名:uni-icons**
> 代码块: `uIcons`
用于展示 icons 图标 。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-icons)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,8 @@
## 1.0.32022-01-21
- 优化 组件示例
## 1.0.22021-11-22
- 修复 / 符号在 vue 不同版本兼容问题引起的报错问题
## 1.0.12021-11-22
- 修复 vue3中scss语法兼容问题
## 1.0.02021-11-18
- init
@@ -0,0 +1 @@
@import './styles/index.scss';
@@ -0,0 +1,82 @@
{
"id": "uni-scss",
"displayName": "uni-scss 辅助样式",
"version": "1.0.3",
"description": "uni-sass是uni-ui提供的一套全局样式 ,通过一些简单的类名和sass变量,实现简单的页面布局操作,比如颜色、边距、圆角等。",
"keywords": [
"uni-scss",
"uni-ui",
"辅助样式"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": "^3.1.0"
},
"dcloudext": {
"category": [
"JS SDK",
"通用 SDK"
],
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "u"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "n",
"联盟": "n"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
@@ -0,0 +1,4 @@
`uni-sass``uni-ui`提供的一套全局样式 ,通过一些简单的类名和`sass`变量,实现简单的页面布局操作,比如颜色、边距、圆角等。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-sass)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,7 @@
@import './setting/_variables.scss';
@import './setting/_border.scss';
@import './setting/_color.scss';
@import './setting/_space.scss';
@import './setting/_radius.scss';
@import './setting/_text.scss';
@import './setting/_styles.scss';
@@ -0,0 +1,3 @@
.uni-border {
border: 1px $uni-border-1 solid;
}
@@ -0,0 +1,66 @@
// TODO 暂时不需要 class ,需要用户使用变量实现 ,如果使用类名其实并不推荐
// @mixin get-styles($k,$c) {
// @if $k == size or $k == weight{
// font-#{$k}:#{$c}
// }@else{
// #{$k}:#{$c}
// }
// }
$uni-ui-color:(
// 主色
primary: $uni-primary,
primary-disable: $uni-primary-disable,
primary-light: $uni-primary-light,
// 辅助色
success: $uni-success,
success-disable: $uni-success-disable,
success-light: $uni-success-light,
warning: $uni-warning,
warning-disable: $uni-warning-disable,
warning-light: $uni-warning-light,
error: $uni-error,
error-disable: $uni-error-disable,
error-light: $uni-error-light,
info: $uni-info,
info-disable: $uni-info-disable,
info-light: $uni-info-light,
// 中性色
main-color: $uni-main-color,
base-color: $uni-base-color,
secondary-color: $uni-secondary-color,
extra-color: $uni-extra-color,
// 背景色
bg-color: $uni-bg-color,
// 边框颜色
border-1: $uni-border-1,
border-2: $uni-border-2,
border-3: $uni-border-3,
border-4: $uni-border-4,
// 黑色
black:$uni-black,
// 白色
white:$uni-white,
// 透明
transparent:$uni-transparent
) !default;
@each $key, $child in $uni-ui-color {
.uni-#{"" + $key} {
color: $child;
}
.uni-#{"" + $key}-bg {
background-color: $child;
}
}
.uni-shadow-sm {
box-shadow: $uni-shadow-sm;
}
.uni-shadow-base {
box-shadow: $uni-shadow-base;
}
.uni-shadow-lg {
box-shadow: $uni-shadow-lg;
}
.uni-mask {
background-color:$uni-mask;
}
@@ -0,0 +1,55 @@
@mixin radius($r,$d:null ,$important: false){
$radius-value:map-get($uni-radius, $r) if($important, !important, null);
// Key exists within the $uni-radius variable
@if (map-has-key($uni-radius, $r) and $d){
@if $d == t {
border-top-left-radius:$radius-value;
border-top-right-radius:$radius-value;
}@else if $d == r {
border-top-right-radius:$radius-value;
border-bottom-right-radius:$radius-value;
}@else if $d == b {
border-bottom-left-radius:$radius-value;
border-bottom-right-radius:$radius-value;
}@else if $d == l {
border-top-left-radius:$radius-value;
border-bottom-left-radius:$radius-value;
}@else if $d == tl {
border-top-left-radius:$radius-value;
}@else if $d == tr {
border-top-right-radius:$radius-value;
}@else if $d == br {
border-bottom-right-radius:$radius-value;
}@else if $d == bl {
border-bottom-left-radius:$radius-value;
}
}@else{
border-radius:$radius-value;
}
}
@each $key, $child in $uni-radius {
@if($key){
.uni-radius-#{"" + $key} {
@include radius($key)
}
}@else{
.uni-radius {
@include radius($key)
}
}
}
@each $direction in t, r, b, l,tl, tr, br, bl {
@each $key, $child in $uni-radius {
@if($key){
.uni-radius-#{"" + $direction}-#{"" + $key} {
@include radius($key,$direction,false)
}
}@else{
.uni-radius-#{$direction} {
@include radius($key,$direction,false)
}
}
}
}
@@ -0,0 +1,56 @@
@mixin fn($space,$direction,$size,$n) {
@if $n {
#{$space}-#{$direction}: #{$size*$uni-space-root}px
} @else {
#{$space}-#{$direction}: #{-$size*$uni-space-root}px
}
}
@mixin get-styles($direction,$i,$space,$n){
@if $direction == t {
@include fn($space, top,$i,$n);
}
@if $direction == r {
@include fn($space, right,$i,$n);
}
@if $direction == b {
@include fn($space, bottom,$i,$n);
}
@if $direction == l {
@include fn($space, left,$i,$n);
}
@if $direction == x {
@include fn($space, left,$i,$n);
@include fn($space, right,$i,$n);
}
@if $direction == y {
@include fn($space, top,$i,$n);
@include fn($space, bottom,$i,$n);
}
@if $direction == a {
@if $n {
#{$space}:#{$i*$uni-space-root}px;
} @else {
#{$space}:#{-$i*$uni-space-root}px;
}
}
}
@each $orientation in m,p {
$space: margin;
@if $orientation == m {
$space: margin;
} @else {
$space: padding;
}
@for $i from 0 through 16 {
@each $direction in t, r, b, l, x, y, a {
.uni-#{$orientation}#{$direction}-#{$i} {
@include get-styles($direction,$i,$space,true);
}
.uni-#{$orientation}#{$direction}-n#{$i} {
@include get-styles($direction,$i,$space,false);
}
}
}
}
@@ -0,0 +1,167 @@
/* #ifndef APP-NVUE */
$-color-white:#fff;
$-color-black:#000;
@mixin base-style($color) {
color: #fff;
background-color: $color;
border-color: mix($-color-black, $color, 8%);
&:not([hover-class]):active {
background: mix($-color-black, $color, 10%);
border-color: mix($-color-black, $color, 20%);
color: $-color-white;
outline: none;
}
}
@mixin is-color($color) {
@include base-style($color);
&[loading] {
@include base-style($color);
&::before {
margin-right:5px;
}
}
&[disabled] {
&,
&[loading],
&:not([hover-class]):active {
color: $-color-white;
border-color: mix(darken($color,10%), $-color-white);
background-color: mix($color, $-color-white);
}
}
}
@mixin base-plain-style($color) {
color:$color;
background-color: mix($-color-white, $color, 90%);
border-color: mix($-color-white, $color, 70%);
&:not([hover-class]):active {
background: mix($-color-white, $color, 80%);
color: $color;
outline: none;
border-color: mix($-color-white, $color, 50%);
}
}
@mixin is-plain($color){
&[plain] {
@include base-plain-style($color);
&[loading] {
@include base-plain-style($color);
&::before {
margin-right:5px;
}
}
&[disabled] {
&,
&:active {
color: mix($-color-white, $color, 40%);
background-color: mix($-color-white, $color, 90%);
border-color: mix($-color-white, $color, 80%);
}
}
}
}
.uni-btn {
margin: 5px;
color: #393939;
border:1px solid #ccc;
font-size: 16px;
font-weight: 200;
background-color: #F9F9F9;
// TODO 暂时处理边框隐藏一边的问题
overflow: visible;
&::after{
border: none;
}
&:not([type]),&[type=default] {
color: #999;
&[loading] {
background: none;
&::before {
margin-right:5px;
}
}
&[disabled]{
color: mix($-color-white, #999, 60%);
&,
&[loading],
&:active {
color: mix($-color-white, #999, 60%);
background-color: mix($-color-white,$-color-black , 98%);
border-color: mix($-color-white, #999, 85%);
}
}
&[plain] {
color: #999;
background: none;
border-color: $uni-border-1;
&:not([hover-class]):active {
background: none;
color: mix($-color-white, $-color-black, 80%);
border-color: mix($-color-white, $-color-black, 90%);
outline: none;
}
&[disabled]{
&,
&[loading],
&:active {
background: none;
color: mix($-color-white, #999, 60%);
border-color: mix($-color-white, #999, 85%);
}
}
}
}
&:not([hover-class]):active {
color: mix($-color-white, $-color-black, 50%);
}
&[size=mini] {
font-size: 16px;
font-weight: 200;
border-radius: 8px;
}
&.uni-btn-small {
font-size: 14px;
}
&.uni-btn-mini {
font-size: 12px;
}
&.uni-btn-radius {
border-radius: 999px;
}
&[type=primary] {
@include is-color($uni-primary);
@include is-plain($uni-primary)
}
&[type=success] {
@include is-color($uni-success);
@include is-plain($uni-success)
}
&[type=error] {
@include is-color($uni-error);
@include is-plain($uni-error)
}
&[type=warning] {
@include is-color($uni-warning);
@include is-plain($uni-warning)
}
&[type=info] {
@include is-color($uni-info);
@include is-plain($uni-info)
}
}
/* #endif */
@@ -0,0 +1,24 @@
@mixin get-styles($k,$c) {
@if $k == size or $k == weight{
font-#{$k}:#{$c}
}@else{
#{$k}:#{$c}
}
}
@each $key, $child in $uni-headings {
/* #ifndef APP-NVUE */
.uni-#{$key} {
@each $k, $c in $child {
@include get-styles($k,$c)
}
}
/* #endif */
/* #ifdef APP-NVUE */
.container .uni-#{$key} {
@each $k, $c in $child {
@include get-styles($k,$c)
}
}
/* #endif */
}
@@ -0,0 +1,146 @@
// @use "sass:math";
@import '../tools/functions.scss';
// 间距基础倍数
$uni-space-root: 2 !default;
// 边框半径默认值
$uni-radius-root:5px !default;
$uni-radius: () !default;
// 边框半径断点
$uni-radius: map-deep-merge(
(
0: 0,
// TODO 当前版本暂时不支持 sm 属性
// 'sm': math.div($uni-radius-root, 2),
null: $uni-radius-root,
'lg': $uni-radius-root * 2,
'xl': $uni-radius-root * 6,
'pill': 9999px,
'circle': 50%
),
$uni-radius
);
// 字体家族
$body-font-family: 'Roboto', sans-serif !default;
// 文本
$heading-font-family: $body-font-family !default;
$uni-headings: () !default;
$letterSpacing: -0.01562em;
$uni-headings: map-deep-merge(
(
'h1': (
size: 32px,
weight: 300,
line-height: 50px,
// letter-spacing:-0.01562em
),
'h2': (
size: 28px,
weight: 300,
line-height: 40px,
// letter-spacing: -0.00833em
),
'h3': (
size: 24px,
weight: 400,
line-height: 32px,
// letter-spacing: normal
),
'h4': (
size: 20px,
weight: 400,
line-height: 30px,
// letter-spacing: 0.00735em
),
'h5': (
size: 16px,
weight: 400,
line-height: 24px,
// letter-spacing: normal
),
'h6': (
size: 14px,
weight: 500,
line-height: 18px,
// letter-spacing: 0.0125em
),
'subtitle': (
size: 12px,
weight: 400,
line-height: 20px,
// letter-spacing: 0.00937em
),
'body': (
font-size: 14px,
font-weight: 400,
line-height: 22px,
// letter-spacing: 0.03125em
),
'caption': (
'size': 12px,
'weight': 400,
'line-height': 20px,
// 'letter-spacing': 0.03333em,
// 'text-transform': false
)
),
$uni-headings
);
// 主色
$uni-primary: #2979ff !default;
$uni-primary-disable:lighten($uni-primary,20%) !default;
$uni-primary-light: lighten($uni-primary,25%) !default;
// 辅助色
// 除了主色外的场景色,需要在不同的场景中使用(例如危险色表示危险的操作)。
$uni-success: #18bc37 !default;
$uni-success-disable:lighten($uni-success,20%) !default;
$uni-success-light: lighten($uni-success,25%) !default;
$uni-warning: #f3a73f !default;
$uni-warning-disable:lighten($uni-warning,20%) !default;
$uni-warning-light: lighten($uni-warning,25%) !default;
$uni-error: #e43d33 !default;
$uni-error-disable:lighten($uni-error,20%) !default;
$uni-error-light: lighten($uni-error,25%) !default;
$uni-info: #8f939c !default;
$uni-info-disable:lighten($uni-info,20%) !default;
$uni-info-light: lighten($uni-info,25%) !default;
// 中性色
// 中性色用于文本、背景和边框颜色。通过运用不同的中性色,来表现层次结构。
$uni-main-color: #3a3a3a !default; // 主要文字
$uni-base-color: #6a6a6a !default; // 常规文字
$uni-secondary-color: #909399 !default; // 次要文字
$uni-extra-color: #c7c7c7 !default; // 辅助说明
// 边框颜色
$uni-border-1: #F0F0F0 !default;
$uni-border-2: #EDEDED !default;
$uni-border-3: #DCDCDC !default;
$uni-border-4: #B9B9B9 !default;
// 常规色
$uni-black: #000000 !default;
$uni-white: #ffffff !default;
$uni-transparent: rgba($color: #000000, $alpha: 0) !default;
// 背景色
$uni-bg-color: #f7f7f7 !default;
/* 水平间距 */
$uni-spacing-sm: 8px !default;
$uni-spacing-base: 15px !default;
$uni-spacing-lg: 30px !default;
// 阴影
$uni-shadow-sm:0 0 5px rgba($color: #d8d8d8, $alpha: 0.5) !default;
$uni-shadow-base:0 1px 8px 1px rgba($color: #a5a5a5, $alpha: 0.2) !default;
$uni-shadow-lg:0px 1px 10px 2px rgba($color: #a5a4a4, $alpha: 0.5) !default;
// 蒙版
$uni-mask: rgba($color: #000000, $alpha: 0.4) !default;
@@ -0,0 +1,19 @@
// 合并 map
@function map-deep-merge($parent-map, $child-map){
$result: $parent-map;
@each $key, $child in $child-map {
$parent-has-key: map-has-key($result, $key);
$parent-value: map-get($result, $key);
$parent-type: type-of($parent-value);
$child-type: type-of($child);
$parent-is-map: $parent-type == map;
$child-is-map: $child-type == map;
@if (not $parent-has-key) or ($parent-type != $child-type) or (not ($parent-is-map and $child-is-map)){
$result: map-merge($result, ( $key: $child ));
}@else {
$result: map-merge($result, ( $key: map-deep-merge($parent-value, $child) ));
}
}
@return $result;
};
@@ -0,0 +1,31 @@
// 间距基础倍数
$uni-space-root: 2;
// 边框半径默认值
$uni-radius-root:5px;
// 主色
$uni-primary: #2979ff;
// 辅助色
$uni-success: #4cd964;
// 警告色
$uni-warning: #f0ad4e;
// 错误色
$uni-error: #dd524d;
// 描述色
$uni-info: #909399;
// 中性色
$uni-main-color: #303133;
$uni-base-color: #606266;
$uni-secondary-color: #909399;
$uni-extra-color: #C0C4CC;
// 背景色
$uni-bg-color: #f5f5f5;
// 边框颜色
$uni-border-1: #DCDFE6;
$uni-border-2: #E4E7ED;
$uni-border-3: #EBEEF5;
$uni-border-4: #F2F6FC;
// 常规色
$uni-black: #000000;
$uni-white: #ffffff;
$uni-transparent: rgba($color: #000000, $alpha: 0);
@@ -0,0 +1,62 @@
@import './styles/setting/_variables.scss';
// 间距基础倍数
$uni-space-root: 2;
// 边框半径默认值
$uni-radius-root:5px;
// 主色
$uni-primary: #2979ff;
$uni-primary-disable:mix(#fff,$uni-primary,50%);
$uni-primary-light: mix(#fff,$uni-primary,80%);
// 辅助色
// 除了主色外的场景色,需要在不同的场景中使用(例如危险色表示危险的操作)。
$uni-success: #18bc37;
$uni-success-disable:mix(#fff,$uni-success,50%);
$uni-success-light: mix(#fff,$uni-success,80%);
$uni-warning: #f3a73f;
$uni-warning-disable:mix(#fff,$uni-warning,50%);
$uni-warning-light: mix(#fff,$uni-warning,80%);
$uni-error: #e43d33;
$uni-error-disable:mix(#fff,$uni-error,50%);
$uni-error-light: mix(#fff,$uni-error,80%);
$uni-info: #8f939c;
$uni-info-disable:mix(#fff,$uni-info,50%);
$uni-info-light: mix(#fff,$uni-info,80%);
// 中性色
// 中性色用于文本、背景和边框颜色。通过运用不同的中性色,来表现层次结构。
$uni-main-color: #3a3a3a; // 主要文字
$uni-base-color: #6a6a6a; // 常规文字
$uni-secondary-color: #909399; // 次要文字
$uni-extra-color: #c7c7c7; // 辅助说明
// 边框颜色
$uni-border-1: #F0F0F0;
$uni-border-2: #EDEDED;
$uni-border-3: #DCDCDC;
$uni-border-4: #B9B9B9;
// 常规色
$uni-black: #000000;
$uni-white: #ffffff;
$uni-transparent: rgba($color: #000000, $alpha: 0);
// 背景色
$uni-bg-color: #f7f7f7;
/* 水平间距 */
$uni-spacing-sm: 8px;
$uni-spacing-base: 15px;
$uni-spacing-lg: 30px;
// 阴影
$uni-shadow-sm:0 0 5px rgba($color: #d8d8d8, $alpha: 0.5);
$uni-shadow-base:0 1px 8px 1px rgba($color: #a5a5a5, $alpha: 0.2);
$uni-shadow-lg:0px 1px 10px 2px rgba($color: #a5a4a4, $alpha: 0.5);
// 蒙版
$uni-mask: rgba($color: #000000, $alpha: 0.4);
+76
View File
@@ -0,0 +1,76 @@
const luchRequest = require('luch-request')
const Request = luchRequest.default || luchRequest
const { generateSignatureHeaders } = require('./signature')
const store = require('../store/index')
const BASE_URL = 'http://192.168.101.5:8084/api'
const http = new Request({
baseURL: BASE_URL,
timeout: 15000,
header: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
http.interceptors.request.use(
(config) => {
// 注入 JWT token
const token = store.getToken()
if (token) {
config.header = config.header || {}
config.header.Authorization = 'Bearer ' + token
}
// 注入签名头
const method = (config.method || 'GET').toUpperCase()
const url = config.url || ''
const body = config.data
const signatureHeaders = generateSignatureHeaders(method, url, body)
config.header = config.header || {}
Object.assign(config.header, signatureHeaders)
return config
},
(error) => Promise.reject(error)
)
// 响应拦截器
http.interceptors.response.use(
(response) => {
if (response.statusCode === 200) {
return response.data
}
return response
},
(error) => {
if (error.statusCode === 401) {
store.clearLogin()
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
if (currentPage && currentPage.route !== 'pages/login/login') {
uni.reLaunch({ url: '/pages/login/login' })
}
}
return Promise.reject(error)
}
)
/**
* 将 coverImage 字段值解析为完整图片 URL
*/
function resolveCoverUrl(coverImage) {
if (!coverImage) return ''
if (/^\/api\/files\/\d+\/preview$/.test(coverImage)) {
return BASE_URL + coverImage.substring(4)
}
if (/^\d+$/.test(coverImage)) {
return BASE_URL + '/files/' + coverImage + '/preview'
}
return coverImage
}
module.exports = http
module.exports.resolveCoverUrl = resolveCoverUrl
@@ -0,0 +1,59 @@
const CryptoJS = require('crypto-js')
const SIGNATURE_SECRET = 'NovalonManageSystemSecretKey2026'
/**
* 生成 HMAC-SHA256 签名
*/
function generateSignature(method, path, query, body, timestamp, nonce) {
const stringToSign = [method, path, query || '', body || '', String(timestamp), nonce].join('\n')
const signature = CryptoJS.HmacSHA256(stringToSign, SIGNATURE_SECRET)
return CryptoJS.enc.Base64.stringify(signature)
}
/**
* 生成随机 nonce
*/
function generateNonce() {
const timestamp = Date.now().toString(36)
const randomPart = Math.random().toString(36).substring(2, 15)
return timestamp + '-' + randomPart
}
/**
* 从 URL 解析 path 和 query
*/
function parseUrl(url) {
if (url.startsWith('http://') || url.startsWith('https://')) {
const withoutProtocol = url.substring(url.indexOf('://') + 3)
const pathStart = withoutProtocol.indexOf('/')
if (pathStart === -1) return { path: '/', query: '' }
const pathAndQuery = withoutProtocol.substring(pathStart)
const queryIndex = pathAndQuery.indexOf('?')
if (queryIndex === -1) return { path: pathAndQuery, query: '' }
return { path: pathAndQuery.substring(0, queryIndex), query: pathAndQuery.substring(queryIndex + 1) }
}
const queryIndex = url.indexOf('?')
if (queryIndex === -1) return { path: url, query: '' }
return { path: url.substring(0, queryIndex), query: url.substring(queryIndex + 1) }
}
/**
* 生成签名请求头
*/
function generateSignatureHeaders(method, url, body) {
const timestamp = Date.now()
const nonce = generateNonce()
const { path, query } = parseUrl(url)
const bodyStr = body ? (typeof body === 'string' ? body : JSON.stringify(body)) : ''
const signature = generateSignature(method.toUpperCase(), path, query, bodyStr, timestamp, nonce)
return {
'X-Signature': signature,
'X-Timestamp': String(timestamp),
'X-Nonce': nonce
}
}
module.exports = { generateSignatureHeaders }
-156
View File
@@ -1,156 +0,0 @@
# 小程序 E2E 自动化测试
## 测试范围
| 套件 | 文件 | 用例数 | 覆盖内容 |
|---|---|---|---|
| 冒烟测试 | `smoke/app-launch.spec.js` | 2 | 首页加载、TabBar 导航(4 个 tab 互切) |
| 个人中心旅程 | `journeys/profile-journey.spec.js` | 2 | 我的课程页、个人中心(会员信息) |
| 团课预约旅程 | `journeys/booking-journey.spec.js` | 3 | 首页课程元素、搜索功能("瑜伽")、课程卡片→详情 |
---
## 环境要求
- 微信开发者工具(安装路径 `D:\微信web开发者工具\`
- 小程序项目已编译:`unpackage/dist/dev/mp-weixin`
- 服务端口:`63956`(默认,可通过 `WECHAT_DEVTOOLS_PORT` 环境变量修改)
---
## 触发方式
### 1. npm scripts(日常开发首选)
| 命令 | 说明 | IDE 管理 |
|---|---|---|
| `npm test` | 全量测试 | 自动启动,保持运行 |
| `npm run test:smoke` | 仅冒烟测试 | 自动启动,保持运行 |
| `npm run test:journeys` | 仅用户旅程测试 | 自动启动,保持运行 |
| `npm run test:profile` | 仅个人中心 | 自动启动,保持运行 |
| `npm run test:booking` | 仅团课预约 | 自动启动,保持运行 |
| `npm run test:all` | 全量 + 测试后关闭 IDE | 自动启动,自动关闭 |
| `npm run test:watch` | Watch 模式(文件变更自动重测) | 需要 IDE 预先运行 |
| `npm run test:quick` | 快速运行(IDE 需已开启) | 不管理 IDE |
| `npm run test:quick:smoke` | 快速冒烟(IDE 需已开启) | 不管理 IDE |
### 2. 一键脚本
```powershell
# 全量测试
node e2e/run-tests.js
# 仅冒烟
node e2e/run-tests.js --smoke
# 仅用户旅程
node e2e/run-tests.js --journeys
# 全量 + 关闭 IDECI 用)
node e2e/run-tests.js --close
# 详细日志
node e2e/run-tests.js --verbose
# Watch 模式
node e2e/run-tests.js --watch
```
### 3. IDE 保持运行 + 反复快测
```powershell
# 首次:启动 IDE
npm test
# 后续修改代码后:秒级快速验证
npm run test:quick
npm run test:quick:smoke
```
### 4. Git Pre-commit Hook
安装:
```bash
# 方式 AHusky(推荐)
npx husky init
npx husky add .husky/pre-commit "sh gym-manage-uniapp/scripts/pre-commit-miniapp-test.sh"
# 方式 B:手动
cp scripts/pre-commit-miniapp-test.sh .git/hooks/pre-commit
```
行为:
- 仅当 `gym-manage-uniapp/pages/``gym-manage-uniapp/e2e/` 有变更 **且** IDE 在运行时触发
- 不满足条件 → 静默跳过,不阻塞提交
- 失败时提示 `git commit --no-verify` 可跳过
### 5. Jenkins CI
```
Jenkins → Build with Parameters → TEST_SCOPE = miniapp
```
Pipeline 自动完成:编译 → 启动 IDE → 测试 → 关闭 IDE → 归档报告。
---
## 架构
```
e2e/
├── jest.config.js # Jest 配置(maxWorkers:1 顺序执行)
├── setup.js # 全局变量注入
├── globalSetup.js # 测试前准备
├── globalTeardown.js # 测试后清理(不关 IDE)
├── run-tests.js # ★ 主入口:IDE 管理 + 测试调度
├── helpers/
│ └── automator.js # 连接/断开 IDE(单例模式)
├── pages/ # Page Object 层
│ ├── HomePage.js
│ ├── LoginPage.js
│ ├── SearchPage.js
│ ├── CourseDetailPage.js
│ ├── ProfilePage.js
│ └── MyCoursesPage.js
├── smoke/
│ └── app-launch.spec.js # 冒烟测试
└── journeys/
├── profile-journey.spec.js
└── booking-journey.spec.js
```
---
## 执行顺序与状态管理
```
suite 执行顺序(jest.config.js 中 testMatch 固定):
1. smoke/app-launch.spec.js → 结束于 index tabbar ✓
2. journeys/profile-journey → 结束于 index tabbar ✓
3. journeys/booking-journey → 最后一个测试进入 course-detail(非 tabbar
↑ 放在最后执行,不影响后续套件
```
**关键约束**`miniprogram-automator``switchTab` / `reLaunch` 从非 tabbar 页面调用会超时。所有测试必须确保:
- 从 tabbar 页面开始(每个测试自己 `switchTab` 到目标 tab
- 最后一个套件的最后一个测试可以进入非 tabbar 页面
---
## 环境变量
| 变量 | 默认值 | 说明 |
|---|---|---|
| `WECHAT_DEVTOOLS_CLI` | `D:\微信web开发者工具\cli.bat` | 微信开发者工具 CLI 路径 |
| `UNIAPP_OUTPUT` | `unpackage/dist/dev/mp-weixin` | 小程序编译输出目录 |
| `WECHAT_DEVTOOLS_PORT` | `63956` | 自动化服务端口 |
---
## 已知限制
1. `miniprogram-automator``switchTab` / `reLaunch` 从非 tabbar 页(如 course-detail)调用会超时 10s
2. 微信开发者工具 CLI 路径含中文,需 `shell: true` 启动
3. 多个测试套件不能共享 IDE 时同时运行(`maxWorkers: 1`
4. 搜索页 `.clickResult()` 不会触发页面跳转(搜索结果为同页内展示)
-18
View File
@@ -1,18 +0,0 @@
const path = require('path');
const fs = require('fs');
module.exports = async function globalSetup() {
const port = parseInt(process.env.WECHAT_DEVTOOLS_PORT || '63956', 10);
// 将共享配置写入临时文件,供测试套件读取
const stateFile = path.resolve(__dirname, '.test-state.json');
fs.writeFileSync(stateFile, JSON.stringify({
port,
launched: true,
timestamp: Date.now()
}), 'utf8');
console.log('\n=== 全局测试环境初始化 ===');
console.log('服务端口:', port);
console.log('状态文件:', stateFile);
};
-15
View File
@@ -1,15 +0,0 @@
const path = require('path');
const fs = require('fs');
module.exports = async function globalTeardown() {
console.log('\n=== 全局测试环境清理 ===');
// 清理状态文件
const stateFile = path.resolve(__dirname, '.test-state.json');
if (fs.existsSync(stateFile)) {
fs.unlinkSync(stateFile);
}
// 注意:不主动关闭 IDE,保持开发者工具运行以便后续使用
console.log('测试环境清理完成(IDE 保持运行)');
};
@@ -1,78 +0,0 @@
const automator = require('miniprogram-automator');
let sharedInstance = null;
let connectPromise = null;
/**
* 连接小程序自动化实例(使用共享单例,避免多个套件重复启动)
* @returns {Promise<import('miniprogram-automator').MiniProgram>}
*/
async function connectMiniProgram() {
if (sharedInstance) {
return sharedInstance;
}
if (connectPromise) {
return connectPromise;
}
const port = global.DEVTOOLS_PORT || 63956;
connectPromise = (async () => {
console.log('连接小程序自动化...');
console.log(' 端口:', port);
const mp = await automator.connect({
wsEndpoint: `ws://127.0.0.1:${port}`
});
sharedInstance = mp;
console.log('连接小程序自动化成功');
return mp;
})();
try {
return await connectPromise;
} catch (error) {
connectPromise = null;
sharedInstance = null;
throw error;
}
}
/**
* 断开小程序自动化连接(仅在全局 teardown 时使用)
*/
async function disconnectMiniProgram() {
if (sharedInstance) {
try {
await sharedInstance.close();
} catch (_) {
// 忽略关闭错误
}
sharedInstance = null;
connectPromise = null;
console.log('小程序自动化已断开');
}
}
async function waitForText(miniProgram, text, timeout = 10000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const page = await miniProgram.currentPage();
const content = await page.data();
if (JSON.stringify(content).includes(text)) {
return true;
}
await new Promise(resolve => setTimeout(resolve, 500));
}
return false;
}
module.exports = {
connectMiniProgram,
disconnectMiniProgram,
launchMiniProgram: connectMiniProgram, // 兼容旧引用名
closeMiniProgram: disconnectMiniProgram, // 兼容旧引用名
waitForText
};
-31
View File
@@ -1,31 +0,0 @@
const path = require('path');
/** @type {import('jest').Config} */
module.exports = {
testEnvironment: 'node',
rootDir: path.resolve(__dirname, '..'),
// 按顺序执行:smoke → profile-journey → booking-journey
// booking 最后运行因为其最后一个测试会进入非 tabbar 页面
testMatch: [
'<rootDir>/e2e/smoke/**/*.spec.js',
'<rootDir>/e2e/journeys/profile-journey.spec.js',
'<rootDir>/e2e/journeys/booking-journey.spec.js'
],
testTimeout: 120000,
verbose: true,
// 顺序运行,避免多个套件同时操作同一实例
maxWorkers: 1,
globalSetup: '<rootDir>/e2e/globalSetup.js',
globalTeardown: '<rootDir>/e2e/globalTeardown.js',
setupFiles: ['<rootDir>/e2e/setup.js'],
globals: {
// 微信开发者工具 CLI 路径
CLI_PATH: process.env.WECHAT_DEVTOOLS_CLI || 'D:\\微信web开发者工具\\cli.bat',
// UniApp 编译输出路径
PROJECT_PATH: process.env.UNIAPP_OUTPUT || path.resolve(__dirname, '../unpackage/dist/dev/mp-weixin'),
// 微信开发者工具服务端口
DEVTOOLS_PORT: parseInt(process.env.WECHAT_DEVTOOLS_PORT || '63956', 10),
// 小程序 AppID(测试用)
APP_ID: process.env.MP_APP_ID || ''
}
};
@@ -1,158 +0,0 @@
const { launchMiniProgram } = require('../helpers/automator');
const { HomePage } = require('../pages/HomePage');
const { MyCoursesPage } = require('../pages/MyCoursesPage');
const { SearchPage } = require('../pages/SearchPage');
// 测试参数:预约目标课程
const BOOKING_COURSE = { name: '流瑜伽', id: 2 };
const QR_CONTENT = JSON.stringify({ courseId: BOOKING_COURSE.id });
describe('团课预约用户旅程', () => {
let miniProgram;
let homePage;
beforeAll(async () => {
try {
miniProgram = await launchMiniProgram();
homePage = new HomePage(miniProgram);
} catch (error) {
console.warn('小程序连接失败:', error.message);
}
});
afterAll(async () => {
if (miniProgram) {
try { await miniProgram.restoreWxMethod('scanCode'); } catch (_) {}
try { await miniProgram.switchTab('/pages/index/index'); } catch (_) {}
}
});
test('首页课程元素展示', async () => {
if (!miniProgram) {
console.log('跳过:小程序环境未就绪');
return;
}
try { await miniProgram.switchTab('/pages/index/index'); } catch (_) {}
await new Promise(resolve => setTimeout(resolve, 1000));
await homePage.waitForReady();
const page = await miniProgram.currentPage();
console.log('当前页:', page.path);
const allElements = await page.$$('[class*="course"]');
console.log('首页课程相关元素数量:', allElements.length);
expect(page.path).toBeTruthy();
});
test('搜索页搜索功能', async () => {
if (!miniProgram) {
console.log('跳过:小程序环境未就绪');
return;
}
try { await miniProgram.switchTab('/pages/index/index'); } catch (_) {}
await new Promise(resolve => setTimeout(resolve, 1000));
await miniProgram.switchTab('/pages/search/search');
await new Promise(resolve => setTimeout(resolve, 1000));
const page = await miniProgram.currentPage();
console.log('搜索页路径:', page.path);
const searchPage = new SearchPage(miniProgram);
await searchPage.search('瑜伽');
await new Promise(resolve => setTimeout(resolve, 1000));
const data = await searchPage.getPageData();
console.log('搜索页数据:', JSON.stringify(data).substring(0, 200));
expect(data).toBeDefined();
expect(data.searchKeyword).toBe('瑜伽');
});
// 【核心】预约团课 + 扫码签到完整流程
test(`预约「${BOOKING_COURSE.name}」并扫码签到`, async () => {
if (!miniProgram) {
console.log('跳过:小程序环境未就绪');
return;
}
// ── 步骤 1: 直接进入「我的课程」页(核心测试起点)──
console.log(`\n━━━ 步骤 1/3: 进入「我的课程」页`);
try { await miniProgram.switchTab('/pages/my-courses/my-courses'); } catch (_) {}
await new Promise(resolve => setTimeout(resolve, 2000));
let page = await miniProgram.currentPage();
console.log('当前页面:', page.path);
expect(page.path).toContain('my-courses');
// ── 步骤 2: 注入模拟预约数据 ──
console.log(`\n━━━ 步骤 2/3: 注入「${BOOKING_COURSE.name}」预约数据`);
await miniProgram.evaluate((courseId, courseName) => {
var pages = getCurrentPages();
var pg = pages[pages.length - 1];
if (pg && pg.setData) {
pg.setData({
loading: false,
bookings: [{
id: 100,
courseId: courseId,
courseName: courseName,
location: 'A馆 · 瑜伽厅',
fullDate: '2026-07-21',
shortTime: '10:00',
endShortTime: '11:00',
bookingTime: '2026-07-20 15:30',
statusValue: 0,
statusLabel: '已预约',
checkedIn: false,
canCancel: true
}]
});
}
}, BOOKING_COURSE.id, BOOKING_COURSE.name);
await new Promise(resolve => setTimeout(resolve, 1000));
const myCoursesPage = new MyCoursesPage(miniProgram);
const myData = await myCoursesPage.getPageData();
console.log('我的课程数据:', JSON.stringify(myData).substring(0, 300));
expect(myData.bookings).toBeDefined();
expect(myData.bookings.length).toBeGreaterThan(0);
// ── 步骤 3: Mock 扫码并签到 ──
console.log(`\n━━━ 步骤 3/3: Mock wx.scanCode → 扫码签到`);
// Mock wx.scanCode 返回课程的二维码内容(模拟扫描 fl.png)
console.log(`Mock scanCode 返回: ${QR_CONTENT}`);
await miniProgram.mockWxMethod('scanCode', {
result: QR_CONTENT,
scanType: 'QR_CODE',
charSet: 'UTF-8',
errMsg: 'scanCode:ok'
});
console.log(`点击「${BOOKING_COURSE.name}」扫码签到按钮`);
const signed = await myCoursesPage.scanSignIn(BOOKING_COURSE.name);
if (signed) {
console.log('扫码签到按钮已点击,等待签到完成...');
await new Promise(resolve => setTimeout(resolve, 2500));
page = await miniProgram.currentPage();
console.log('签到后当前页面:', page.path);
} else {
console.log(`未找到「${BOOKING_COURSE.name}」的签到按钮`);
}
// 恢复 mock
await miniProgram.restoreWxMethod('scanCode');
console.log('已恢复 wx.scanCode');
// 验证页面未崩溃
const finalPage = await miniProgram.currentPage();
expect(finalPage.path).toBeTruthy();
console.log('\n✅ 预约+扫码签到流程完成');
});
});

Some files were not shown because too many files have changed in this diff Show More